14.5. A circuit breaker
Topics
This question is in
14. Timeouts, retries and concurrencyWhen a service is down, every call to it waits for a time-out and then fails. Retrying makes it worse: the page stays slow, and the service gets a flood of requests just as it tries to recover. A circuit breaker notices the run of failures and stops calling for a while. Calls fail at once with a clear error, and after a pause one trial call checks whether the service is back.
Write createCircuitBreaker(fn, options) in circuit-breaker.js. It returns { call, state }: call(...args) runs fn through the breaker, and state reads "closed", "open" or "half-open".
Signature
function createCircuitBreaker(fn, options) // returns { call(...args), state }fn: the work. It may return a promise or a value, or throw.options(optional):failureThreshold(default 3), the failures in a row that open the circuit, andresetTimeout(default 1000), how many ms the circuit stays open.call(...args)returns a promise offn(...args)'s result.stateis a getter: reading it says the state at that moment.
Requirements
- The circuit starts closed. A closed circuit calls
fnwith the arguments and returns its result or its error unchanged. failureThresholdfailures in a row open the circuit. A success sets the count back to 0. A failure counts when it happens (when the promise rejects), not when the call starts.- An open circuit does not call
fn:callreturns a promise that rejects at once with anErrorwhosenameis"CircuitOpenError". - The circuit stays open for exactly
resetTimeoutms, then it is half-open (thestategetter says so as soon as the time has passed). - In half-open, the next call is a trial and goes through. Other calls made while the trial runs are rejected with
CircuitOpenError. - If the trial succeeds, the circuit closes and the failure count starts again from 0. If it fails, the circuit opens again, for
resetTimeoutms from that failure. - Results of calls that started before the circuit opened change nothing while it is open or half-open: only the trial decides.
- An error
fnthrows (instead of rejecting) counts as a failure, andcallnever throws. Each breaker has its own state.
Examples
const breaker = createCircuitBreaker(() => fetch("/api/prices"), { failureThreshold: 3, resetTimeout: 5000 });
// the service is down: three calls fail with network errors
breaker.state; // "open"
breaker.call().catch((error) => console.log(error.name)); // "CircuitOpenError", at once, no request sent// 5000 ms after the circuit opened
breaker.state; // "half-open"
breaker.call(); // the trial: a real request
breaker.call(); // rejected with CircuitOpenError while the trial runs
// the trial succeeds: breaker.state is "closed"// fail, fail, success, fail, fail: still "closed" (the success reset the count)Environment
- Plain JavaScript in a browser page; the tests call the global
createCircuitBreakerfromcircuit-breaker.js. - The tests run on a virtual clock that replaces
Date.now,setTimeoutandclearTimeout. Time is read withDate.now(); no timer is needed, but one is allowed if you clear it. - Retries are not part of the breaker: problem 14.4 is retries, and a real client puts the retry loop outside the breaker.
Hints
- Does "half-open" have to be set by a timer, or can it be worked out from the time the circuit opened?
- When a call settles, how does the breaker know whether that call was the trial?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it