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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.SPDX License LookupSearch common SPDX license identifiers and see permissions, conditions, limitations, copyleft strength, and OSI or FSF approval status.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.