Circuit Breaker Half Open Probe

Implement a circuit breaker with closed open and half-open states that probes recovery with a single trial call before full traffic.

JavascriptResilience

Code

javascriptsnippet
1 line
export function circuitBreaker(fn,{failureThreshold=5,resetTimeout=30000}={}){let state='closed',failures=0,lastFail=0;async function g(...a){if(state==='open'){if(Date.now()-lastFail<resetTimeout)throw new Error('Circuit open');state='half-open';}try{const r=await fn.apply(this,a);if(state==='half-open'){state='closed';failures=0;}return r;}catch(e){failures++;lastFail=Date.now();if(state==='half-open'||failures>=failureThreshold)state='open';throw e;}}g.state=()=>state;return g;}

How the snippet works

Count the functions circuitBreaker and g as the entire surface area of Circuit Breaker Half Open Probe.

Await points sequence the asynchronous work; a rejection lands at the awaiting line. Error is the guard’s signal — thrown at the branch, before any partial work happens.

Using it in your own code

The main signature reads export function circuitBreaker(fn,{failureThreshold=5,resetTimeout=30000}={})

Treat circuitBreaker as the API: import it, and ignore the supporting code.

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
Validation comes first — `Error` marks the failure, before any partial work happens.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `circuitBreaker`, `g` at load time.