← Back to Node.js, page 10

nodejs-0199 · Hard senior

Implement a circuit breaker for calls to an unreliable service. What are its states, and what settings matter?

A circuit breaker stops calling a failing dependency so that it can recover and so that callers fail fast. It has three states. Closed: calls go through and failures are counted. Open: calls fail at once for a cool-down period. Half-open: after the cool-down, a limited number of trial calls are allowed, and one success closes the breaker while a failure opens it again. Combine it with timeouts, retries with backoff, and fallbacks.

Full answer

States

  • Closed (normal): calls pass through. Track failures. When consecutive failures reach a threshold (or the failure rate in a window crosses a limit), switch to open and record the time.
  • Open: do not call the dependency. Reject at once with a clear error (fail fast), or use a fallback (cached data, a default). This protects the failing service from extra load and protects your own resources (threads, sockets, queue length).
  • Half-open: when the reset timeout has passed, allow one trial call (or a few). On success, go back to closed and reset the counters. On failure, go back to open and restart the timer. Only the allowed number of trial calls may pass while others are rejected.

Settings

  • failureThreshold (or error percentage and minimum number of calls in a window), resetTimeout, call timeout, and which errors count as failures (a 400 caused by a bad request is not a dependency failure, a timeout or a 503 is).
  • Per dependency, not one global breaker.

Details and pairing

  • Always put a timeout on the wrapped call. A slow dependency is the main reason for breakers.
  • Retries belong inside or outside of the breaker by design, but they must not multiply the load on a failing service. Use backoff with jitter.
  • Expose state and counters as metrics and logs, and alert when a breaker opens.
  • In a cluster each process has its own breaker unless the state is shared. That is usually fine.
  • Libraries: opossum is a well-known Node implementation.
javascript
class CircuitBreaker {
  #state = 'closed'; #failures = 0; #openedAt = 0; #trialInFlight = false;
  constructor(fn, { failureThreshold = 3, resetTimeout = 1000, now = Date.now } = {}) {
    this.fn = fn; this.failureThreshold = failureThreshold; this.resetTimeout = resetTimeout; this.now = now;
  }
  get state() { return this.#state; }

  async call(...args) {
    if (this.#state === 'open') {
      if (this.now() - this.#openedAt < this.resetTimeout) throw new Error('circuit open');
      this.#state = 'half-open';
    }
    if (this.#state === 'half-open') {
      if (this.#trialInFlight) throw new Error('circuit half-open, trial in progress');
      this.#trialInFlight = true;
    }
    try {
      const result = await this.fn(...args);
      this.#failures = 0; this.#state = 'closed';
      return result;
    } catch (err) {
      this.#failures++;
      if (this.#state === 'half-open' || this.#failures >= this.failureThreshold) { this.#state = 'open'; this.#openedAt = this.now(); }
      throw err;
    } finally {
      this.#trialInFlight = false;
    }
  }
}

(async () => {
  let clock = 0, healthy = false, upstreamCalls = 0;
  const service = async () => { upstreamCalls++; if (!healthy) throw new Error('503 from service'); return 'ok'; };
  const breaker = new CircuitBreaker(service, { failureThreshold: 3, resetTimeout: 1000, now: () => clock });
  const attempt = async (label) => {
    const result = await breaker.call().catch((e) => e.message);
    console.log(label.padEnd(30), 'state =', breaker.state.padEnd(9), '|', result, '| upstream calls so far:', upstreamCalls);
  };

  for (let i = 1; i <= 3; i++) await attempt(`failure ${i}`);
  await attempt('call while open');
  await attempt('call while open (again)');

  clock += 1000;                                   // the cool-down has passed
  await attempt('trial fails (still broken)');
  await attempt('call right after reopening');

  clock += 1000; healthy = true;
  await attempt('trial succeeds');
  await attempt('normal call');
})();

The clock is injected, so the cool-down is simulated by changing a number. Concurrent calls were not tested in this script. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): failure 1 state = closed | 503 from service | upstream calls so far: 1 failure 2 state = closed | 503 from service | upstream calls so far: 2 failure 3 state = open | 503 from service | upstream calls so far: 3 call while open state = open | circuit open | upstream calls so far: 3 call while open (again) state = open | circuit open | upstream calls so far: 3 trial fails (still broken) state = open | 503 from service | upstream calls so far: 4 call right after reopening state = open | circuit open | upstream calls so far: 4 trial succeeds state = closed | ok | upstream calls so far: 5 normal call state = closed | ok | upstream calls so far: 6

Key points

  • Closed counts failures, open fails fast, half-open tests recovery.
  • Only the allowed trial calls pass in half-open.
  • Choose which errors count as failures.
  • Use one breaker per dependency, with timeouts and metrics.
  • Combine with retries and fallbacks, carefully.

Common mistakes

  • Opening the breaker for client errors such as 400 or 404.
  • No timeout, so slow calls never count as failures.
  • Letting every request through in half-open state.
  • One global breaker for many unrelated dependencies.
  • Retrying aggressively behind an open breaker.

Follow-ups

  • How does a failure rate window differ from a consecutive failure count?
  • What fallback would you use for a read endpoint?
  • How do bulkheads relate to circuit breakers?

Tips

  • Draw the three states.
  • Mention timeouts and what counts as failure.
  • Say that the library opossum exists.