How-To Guide

How to Build a Circuit Breaker in Node.js

Implement a circuit breaker in Node.js with closed, open, and half-open states, failure thresholds, timeouts, fallbacks, and tests for every transition.

On this page

  1. Introduction
  2. The three states
  3. Wrap the call
  4. Timeouts and failure classification
  5. Half-open, probes, and recovery
  6. Fallbacks and bulkheads
  7. Metrics and tuning thresholds
  8. Testing state transitions
  9. Common pitfalls
  10. Conclusion

Introduction

A circuit breaker stops a process from repeatedly calling a dependency that is already failing. Without one, a slow or broken downstream turns into a pile-up of requests that exhaust sockets, memory, and threads, and the failure spreads to services that were healthy. The breaker watches the outcome of calls, and when the failure rate crosses a threshold it trips open and rejects calls immediately instead of waiting for a timeout. After a cool-down it lets a small number of probes through; if they succeed it closes, and if they fail it opens again.

This tutorial implements a circuit breaker in Node.js with TypeScript, covering the state machine, failure classification, timeouts, half-open probing, fallbacks, metrics, and the tests that pin every transition. The goal is a component small enough to audit and specific enough to make failure behavior obvious instead of emergent.

The three states

The breaker has exactly three states. Closed is normal operation: calls pass through and the breaker counts successes and failures. Open is tripped: calls are rejected immediately, before any network I/O, and a timer counts down to the probe. Half-open is the recovery trial: a limited number of calls are allowed through; if enough succeed the breaker closes, and if any fail it reopens and resets the timer.

The transition from closed to open is driven by a failure ratio over a rolling window, not a single error. The transition from open to half-open is driven by time, so the dependency gets a chance to recover. The transition from half-open back to open is driven by the probe results. Every transition should be an explicit function with a log line, because a breaker that changes state without evidence is a breaker you cannot debug at 3 a.m.

Wrap the call

The breaker must see every call to the dependency; a caller that bypasses the wrapper bypasses the protection. The clean shape is a execute(fn) method that applies the state policy, runs the function under a timeout, records the outcome, and optionally calls a fallback.

type State = 'closed' | 'open' | 'half-open';

interface BreakerOptions {
  failureThreshold: number;   // ratio 0..1 that trips the breaker
  minimumCalls: number;       // do not trip below this many calls in the window
  windowMs: number;           // rolling window for the ratio
  cooldownMs: number;         // time in open before a probe
  halfOpenMaxCalls: number;   // probes allowed while half-open
  timeoutMs: number;          // per-call timeout
}

class CircuitBreaker {
  private state: State = 'closed';
  private outcomes: { at: number; failure: boolean }[] = [];
  private openedAt = 0;
  private probesInFlight = 0;

  constructor(private opts: BreakerOptions) {}

  async execute<T>(fn: () => Promise<T>, fallback?: () => Promise<T>): Promise<T> {
    if (this.state === 'open') {
      if (Date.now() - this.openedAt >= this.opts.cooldownMs) {
        this.state = 'half-open';
        this.probesInFlight = 0;
      } else {
        return this.reject(fallback);
      }
    }
    if (this.state === 'half-open' && this.probesInFlight >= this.opts.halfOpenMaxCalls) {
      return this.reject(fallback);
    }

    if (this.state === 'half-open') this.probesInFlight++;
    try {
      const result = await withTimeout(fn, this.opts.timeoutMs);
      this.recordSuccess();
      return result;
    } catch (err) {
      this.recordFailure(err);
      if (fallback) return fallback();
      throw err;
    }
  }

  private async reject<T>(fallback?: () => Promise<T>): Promise<T> {
    const err = new Error('circuit_open');
    if (fallback) return fallback();
    throw err;
  }
}

The threshold logic lives in recordFailure and recordSuccess, which prune the window, append the outcome, and recompute the ratio.

Timeouts and failure classification

A breaker is only as good as its timeout. A call that hangs forever never records an outcome, so it never contributes to the failure ratio and it holds a slot in the concurrency budget. Every call under the breaker must be bounded by an AbortController or a race against a timer, and the timeout should be shorter than the caller’s own deadline so the outer layer still has time to fall back.

Not every error should count as a failure. A 400 Bad Request from the dependency is a bug in your request, not evidence that the dependency is down; counting it can trip the breaker for the wrong reason. Count infrastructure faults: connection errors, socket timeouts, 5xx responses, and deadline exceeded. Treat 4xx-equivalent errors as caller mistakes and either let them propagate or count them separately. If the dependency returns a non-recoverable error, map it to a distinct exception type before it reaches recordFailure, so the classification is explicit rather than inferred from a status code scattered across call sites.

Half-open, probes, and recovery

The half-open state is where most implementations go wrong. If it allows all traffic through, the recovering dependency is immediately overwhelmed and fails again. If it allows exactly one call and that call happens to hit a cold cache, the breaker reopens on a false signal. Allow a small, bounded number of probes (typically one to three), and require a minimum number of successes before closing. During half-open, reject everything beyond the probe budget so the dependency gets a genuine recovery window.

private recordSuccess() {
  if (this.state === 'half-open') {
    this.probesInFlight = Math.max(0, this.probesInFlight - 1);
    this.close();
    return;
  }
  this.pushOutcome(false);
}

private recordFailure(err: unknown) {
  if (this.state === 'half-open') {
    this.open();
    return;
  }
  this.pushOutcome(true);
  this.maybeTrip();
}

private maybeTrip() {
  const now = Date.now();
  this.outcomes = this.outcomes.filter((o) => now - o.at <= this.opts.windowMs);
  if (this.outcomes.length < this.opts.minimumCalls) return;
  const failures = this.outcomes.filter((o) => o.failure).length;
  if (failures / this.outcomes.length >= this.opts.failureThreshold) this.open();
}

A single failure during half-open reopens the breaker. This is intentionally strict: after a cool-down, any error is evidence that the dependency is not healthy yet. Some teams add a slow-start instead, closing and then ramping traffic; start strict and relax only with data.

Fallbacks and bulkheads

When the breaker rejects a call, the application still has to answer the request. A fallback is the code that runs when the breaker is open: serve a cached value, return a degraded but valid response, queue the work, or return a clear 503 with a Retry-After. The fallback must be fast and must not itself call the tripped dependency. Document which endpoints have a fallback and which fail hard; an undocumented fallback that silently returns stale data is a correctness bug waiting to surface.

Bulkheads complement the breaker by limiting the concurrency a dependency can consume. A breaker stops calls after failures; a bulkhead prevents one slow dependency from consuming every available connection while the failures are still being counted. Together they contain the blast radius: the bulkhead bounds in-flight work, the breaker bounds repeated attempts, and the timeout bounds each attempt.

Metrics and tuning thresholds

Emit a gauge for the breaker state (0 closed, 1 half-open, 2 open), a counter for rejected calls, and a counter for state transitions with the reason. The rejected-call counter is the metric that tells you the breaker is working; a breaker that never rejects is misconfigured or protecting nothing. Alert on transitions to open, because that is a real availability event, and dashboard the failure ratio next to the caller’s error rate so you can tell whether the breaker is masking a dependency problem.

Tune the ratio, the minimum call count, and the cooldown from traffic shape. High-traffic endpoints can use a short window and a high minimum count; low-traffic endpoints need a minimum count low enough to ever trip but high enough to avoid false positives. Never share a breaker across dependencies with different failure characteristics; one breaker per dependency keeps the signal clean.

Testing state transitions

Test the breaker with a fake clock and a stubbed function so you can drive every transition deterministically. Assert that the breaker opens exactly at the threshold and not before, that it rejects without calling the function while open, that it probes in half-open, and that it closes after the required successes.

test('opens at the threshold and rejects without calling the dependency', async () => {
  const clock = fakeClock();
  const breaker = new CircuitBreaker({ failureThreshold: 0.5, minimumCalls: 4, windowMs: 10_000, cooldownMs: 5_000, halfOpenMaxCalls: 1, timeoutMs: 1_000 });
  let calls = 0;
  const failing = async () => { calls++; throw new Error('boom'); };

  for (let i = 0; i < 4; i++) await breaker.execute(failing).catch(() => {});
  expect(calls).toBe(4); // four attempts, ratio 1.0 -> open

  await expect(breaker.execute(failing)).rejects.toThrow('circuit_open');
  expect(calls).toBe(4); // rejected fast, dependency not called

  clock.advance(5_000);
  await breaker.execute(async () => 'ok'); // one probe succeeds -> closed
  expect(breaker['state']).toBe('closed');
});

Cover the negative cases too: successes below the minimum count do not trip, a single failure in half-open reopens, and the timeout path records a failure rather than hanging. A concurrency test that fires many calls while open should show zero dependency calls.

Common pitfalls

  • No timeout. A hung call never records an outcome and never trips the breaker.
  • Counting every error. 4xx client errors trip the breaker for the wrong reason.
  • Allowing all traffic in half-open. The recovering dependency is overwhelmed again.
  • Sharing one breaker across dependencies. Different failure modes blur the signal.
  • Silent fallbacks. Stale data served without a label becomes a correctness bug.
  • No state metric. You cannot alert on or debug transitions you do not measure.
  • Per-instance breakers only. In a fleet, each process trips independently; consider aggregating.

Conclusion

A circuit breaker is a small, explicit state machine: pass calls while closed, reject fast when open, and probe carefully during half-open. Give every call a timeout, count only infrastructure faults, fall back quickly when open, and expose the state and rejection count as metrics. Test every transition with a fake clock so the behavior is pinned rather than assumed. The breaker does not make a dependency reliable; it makes your service degrade predictably instead of collapsing, which is the property that keeps an incident from becoming an outage.

Sources: Martin Fowler: CircuitBreaker, Microsoft Azure: Circuit Breaker pattern, opossum: Node.js circuit breaker.

FAQ

How is a circuit breaker different from a retry?
A retry assumes the failure is transient and tries again; a circuit breaker assumes the dependency might be down for a while and stops calling it. They are complementary: retry a few times inside the breaker, so the breaker counts the final outcome after the retries are exhausted rather than each attempt.
What failure threshold should I choose?
Express the threshold as a ratio over a minimum number of calls, not a raw count, so a low-traffic endpoint does not trip on three failures in an hour. A common starting point is a 50 percent failure rate over at least 20 calls in a 10 second window, then tune from observed data.
Should a circuit breaker fail open or closed?
The breaker itself fails open, meaning it rejects calls, when the dependency is down. What you do with a rejected call is the fallback decision: serve cached data, a degraded response, or a clear error. For critical paths, prefer a fast, well-labeled error over a slow timeout.

Related Examples