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;}Report a problem with this exampleOpens a pre-filled issue on GitHub.