Circuit Breaker State Machine Typed
Implement a typed circuit breaker state machine with closed open half-open transitions and metrics.
Code
type State='closed'|'open'|'half-open';export class CircuitBreaker{private state:State='closed';private failures=0;private lastFailure=0;constructor(private fn:Function,private opts:{threshold:number;resetMs:number}){}async call<T>(...args:any[]):Promise<T>{if(this.state==='open'&&Date.now()-this.lastFailure<this.opts.resetMs)throw new Error('open');if(this.state==='open')this.state='half-open';try{const r=await this.fn(...args);if(this.state==='half-open'){this.state='closed';this.failures=0;}return r;}catch(e){this.failures++;this.lastFailure=Date.now();if(this.state==='half-open'||this.failures>=this.opts.threshold)this.state='open';throw e;}}getState():State{return this.state;}}How it works
Circuit Breaker State Machine Typed comes down to the class CircuitBreaker.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
Putting it to use
Import CircuitBreaker from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
FAQ
- Does the code validate its input?
- `Error` is raised at the guard, so invalid state never reaches the main logic.
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches.
Report a problem with this exampleOpens a pre-filled issue on GitHub.