Skip to curriculum
Jump to the editor

14.5. A circuit breaker

Hard
Topics
35–50 min

When 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

JAVASCRIPT
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, and resetTimeout (default 1000), how many ms the circuit stays open.
  • call(...args) returns a promise of fn(...args)'s result.
  • state is a getter: reading it says the state at that moment.

Requirements

  1. The circuit starts closed. A closed circuit calls fn with the arguments and returns its result or its error unchanged.
  2. failureThreshold failures 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.
  3. An open circuit does not call fn: call returns a promise that rejects at once with an Error whose name is "CircuitOpenError".
  4. The circuit stays open for exactly resetTimeout ms, then it is half-open (the state getter says so as soon as the time has passed).
  5. In half-open, the next call is a trial and goes through. Other calls made while the trial runs are rejected with CircuitOpenError.
  6. If the trial succeeds, the circuit closes and the failure count starts again from 0. If it fails, the circuit opens again, for resetTimeout ms from that failure.
  7. Results of calls that started before the circuit opened change nothing while it is open or half-open: only the trial decides.
  8. An error fn throws (instead of rejecting) counts as a failure, and call never throws. Each breaker has its own state.

Examples

JAVASCRIPT
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
JAVASCRIPT
// 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"
JAVASCRIPT
// fail, fail, success, fail, fail: still "closed" (the success reset the count)

Environment

  • Plain JavaScript in a browser page; the tests call the global createCircuitBreaker from circuit-breaker.js.
  • The tests run on a virtual clock that replaces Date.now, setTimeout and clearTimeout. Time is read with Date.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

  1. Does "half-open" have to be set by a timer, or can it be worked out from the time the circuit opened?
  2. 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
Back to the question
Loading the editor…