Skip to content

Circuit breaker: fail fast when a dependency is down

How a circuit breaker stops a slow dependency from dragging your whole service down, with thresholds, half-open probes and fallbacks.

11 min readSystem pattern

Stop calling a dependency that is failing, fail fast with a fallback while it recovers, and check periodically whether it's back.

A circuit breaker sits between your service and a dependency and watches how calls go. While they succeed, it does nothing. When too many fail, it «opens» and rejects calls immediately, without touching the network, for a cool-down period. Then it lets a handful through to test the water and closes again only if they succeed. It doesn't fix the dependency: it stops you from piling up waiting requests until you fall over too.

The problem

A situation where the obvious design starts to hurt.

Your online shop's checkout calls a carrier's rates API to show delivery options and prices. It normally answers in 120 ms. On a Friday evening, during a sale, the carrier starts answering in 25 seconds, and some calls never answer at all.

Each checkout instance can hold about 200 requests in flight. At 300 checkouts a minute, in under a minute every slot is taken by a request waiting on the carrier. New requests queue up, the load balancer's health checks start timing out, instances get restarted, and checkout —payment included— is down. The payment provider is perfectly healthy; a non-essential call has taken out the essential one.

Retrying makes it worse: every failed call becomes two or three, aimed at a provider that is already drowning. You need something that notices the carrier is unhealthy and stops sending it traffic, so checkout can carry on without it.

The solution

What the pattern proposes.

Wrap every call to the carrier in a breaker with three states. Closed: calls go through and the breaker records the outcome of the last 20. If at least 10 have been recorded and half or more failed —timeouts, connection errors, 5xx— it trips to open. Open: every call fails instantly, without a network round trip, and checkout falls back to a flat-rate shipping table. After 15 seconds the breaker goes half-open and lets three trial calls through; if all three succeed it closes, if any fails it opens again for another 15 seconds.

Two things make it work. First, a tight timeout on the call (2 seconds here): without it, a hanging request never counts as a failure and the breaker never opens. Second, a fallback that makes sense to the business: the shopper sees «standard delivery, 4,95 €» instead of the exact quote, and the order still goes through. While the carrier is down, checkout's latency goes back to normal and the carrier gets the quiet it needs to recover.

An everyday analogy

The same idea, outside software.

Think of a shop assistant who phones the warehouse to check stock. If the warehouse line rings out three times in a row, a sensible assistant doesn't keep every customer waiting while they redial: for the next quarter of an hour they say «we'll confirm by email» and serve the next person. Every so often they try the warehouse again, and when it picks up, they go back to checking live.

Structure

The pieces and how they relate.

Checkout calls the carrier through a circuit breaker; when the breaker is open, it answers from a flat-rate table instead.Shopper's browser calls Checkout API. Checkout API calls Circuit breaker. Circuit breaker calls Carrier rates API (2 s timeout). Circuit breaker sends to Flat-rate table (when open).Shopper's browserCheckout APIshippingOptions(cart)Circuit breakerclosed · open ·half-openCarrier rates APIthird partyFlat-rate tablefallback pricesWhen it trips≥ 50 % failed of the last 20 · probes after 15 s2 s timeoutwhen open
Checkout calls the carrier through a circuit breaker; when the breaker is open, it answers from a flat-rate table instead.

Participants

Checkout API (caller)
Needs shipping options to build the order. Decides what to do when the breaker refuses: here, use flat rates.
Circuit breaker
Wraps calls to one dependency. Keeps the recent outcomes, the state and the cool-down timer, and decides whether a call may go out.
Carrier rates API (dependency)
The third-party service that may slow down or fail. It never knows the breaker exists.
Flat-rate table (fallback)
A degraded but valid answer the caller can use without the dependency: static prices, a cached value, a default.

Pseudocode

The solution to the scenario, language-neutral.

state = CLOSED, recent = last 20 results

call(request):
    if state is OPEN:
        if cool-down (15 s) not over: fail fast  // no network call at all
        state = HALF_OPEN                        // time to probe
    if state is HALF_OPEN and 3 probes already in flight: fail fast
    try:
        result = send(request) with a 2 s timeout
        record(success)
        return result
    on timeout, connection error or 5xx:
        record(failure)
        rethrow

record(outcome):
    if state is HALF_OPEN:
        failure  -> state = OPEN, restart cool-down
        3rd success in a row -> state = CLOSED, forget history
        return
    add outcome to recent
    if at least 10 results and failure rate >= 50%:
        state = OPEN, restart cool-down

shippingOptions(cart):
    try: return call(carrier.rates(cart))
    on any failure: return flatRates(cart)      // degrade, don't break checkout

The code

The same solution in TypeScript, Python and PHP.

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

export class CircuitOpenError extends Error {}

export class CircuitBreaker {
  private state: State = "closed";
  private results: boolean[] = []; // last calls, true = failed
  private openedAt = 0;
  private inFlight = 0; // trial calls while half-open
  private successes = 0;

  constructor(
    private readonly opts = { window: 20, failureRate: 0.5, minCalls: 10, openMs: 15_000, probes: 3 },
    private readonly now = () => Date.now(),
  ) {}

  async call<T>(fn: () => Promise<T>): Promise<T> {
    if (this.state === "open") {
      if (this.now() - this.openedAt < this.opts.openMs) throw new CircuitOpenError("circuit open");
      this.state = "half-open"; // cool-down over: let a few calls through
      this.inFlight = 0;
      this.successes = 0;
    }
    if (this.state === "half-open") {
      if (this.inFlight >= this.opts.probes) throw new CircuitOpenError("probing");
      this.inFlight++;
    }
    try {
      const value = await fn();
      this.record(false);
      return value;
    } catch (err) {
      this.record(true);
      throw err;
    }
  }

  private record(failed: boolean) {
    if (this.state === "half-open") {
      if (failed) this.trip();
      else if (++this.successes >= this.opts.probes) this.reset();
      return;
    }
    this.results.push(failed);
    if (this.results.length > this.opts.window) this.results.shift();
    const failures = this.results.filter(Boolean).length;
    if (this.results.length >= this.opts.minCalls && failures / this.results.length >= this.opts.failureRate)
      this.trip();
  }

  private trip() {
    this.state = "open";
    this.openedAt = this.now();
    this.results = [];
  }

  private reset() {
    this.state = "closed";
    this.results = [];
  }
}

// One breaker per dependency, shared by every request of this instance.
const carrierBreaker = new CircuitBreaker();

export async function shippingOptions(cart: Cart): Promise<ShippingOption[]> {
  try {
    return await carrierBreaker.call(() => fetchCarrierRates(cart, { timeoutMs: 2_000 }));
  } catch {
    // Breaker open, timeout or carrier error: checkout goes on with flat rates.
    return flatRates(cart);
  }
}

When to use it

Situations where it pays off.

  • A synchronous call to a dependency you don't control sits on a request path that matters.

    That's exactly where a slow dependency eats your capacity: the breaker caps the damage to the duration of the timeout, and only until it opens.

  • You have a reasonable fallback, even a partial one.

    Failing fast is only half the value. Answering with cached data, a default or a «try later» keeps the user's flow alive.

  • Your retries could turn a struggling dependency into a dead one.

    An open breaker stops retries at the source, so the dependency gets the breathing room it needs to recover.

  • Many instances call the same dependency and you want them to back off together.

    Each instance's breaker reacts to the same symptoms, so traffic to the dependency drops quickly across the fleet.

How to implement it

Steps to introduce it in existing code.

  1. Put a timeout on the call first. A breaker can't count a failure that never ends.

  2. Decide what counts as a failure: timeouts, connection errors and 5xx do; 4xx and validation errors don't —they're your bug, not the dependency's.

  3. Pick a window and thresholds from real traffic: a minimum number of calls (so 2 failures out of 2 at 3 a.m. don't trip it), a failure rate and a cool-down.

  4. Create one breaker per dependency, or per endpoint if their health differs, and share it across requests in the process.

  5. Write the fallback with the product team and make it visible: a flag in the response, a metric, a log line per state change.

  6. Test it: inject latency and errors in staging and check that the breaker opens, checkout stays fast and it closes again when the dependency recovers.

Pros and cons

What you gain and what you pay.

Pros

  • Caps the damage a slow dependency can do to your capacity and latency.
  • Gives the failing dependency room to recover instead of hammering it.
  • Makes failures explicit and fast, so callers can degrade gracefully.
  • State changes are a clear, alertable signal that a dependency is in trouble.

Cons

  • Thresholds are guesses until tuned with real traffic; wrong ones either never trip or trip on noise.
  • While open, some requests that would have succeeded are rejected too.
  • Per-instance breakers see only their own traffic and may disagree with each other.
  • Adds a moving part that has to be tested, monitored and understood by whoever is on call.

Trade-offs

Decisions you'll have to make, each with its price.

  • Failure-rate threshold vs consecutive-failure count

    You gainA rate over a window (50 % of the last 20) ignores isolated blips and works at any traffic level.

    You payNeeds a minimum number of calls, and at low traffic it reacts slowly. Consecutive failures are simpler but trip on short bursts.

  • Short vs long cool-down

    You gainShort (5-15 s) recovers quickly when the outage was brief.

    You payProbes a struggling dependency more often. Long cool-downs, or ones that grow after each failed probe, are gentler but keep the fallback on for longer.

  • One breaker per host vs per endpoint

    You gainPer endpoint isolates a broken /rates from a healthy /labels.

    You payMore breakers to configure and watch, and less data per breaker to decide with.

  • Local state per instance vs shared state

    You gainLocal is simple, fast and has no new dependency.

    You payInstances learn separately; shared state (Redis) makes them agree but adds a dependency on the critical path.

How it fails

What goes wrong in production and how to prevent it.

  • The breaker never opens because calls hang for 30 seconds before failing

    What to doSet a timeout below your own latency budget (2 s here). The breaker only reacts to outcomes it gets to see.

  • It flaps between open and closed every few seconds

    What to doRequire a minimum number of calls in the window, several successful probes before closing, and a cool-down that grows when probes fail.

  • Client errors trip it: a bad deploy on your side sends invalid requests and the breaker blames the carrier

    What to doCount only timeouts, connection errors and 5xx as failures. Alert separately on 4xx.

  • The fallback is silent and wrong for hours

    What to doMark degraded responses, emit a metric per state change and alert when a breaker stays open longer than a few minutes.

In a system design interview

When to bring it up and how to explain it.

Bring it up when your design has a synchronous call to something you don't own —payments, a carrier, another team's service— and the interviewer asks «what happens if that's slow?». Mention it together with timeouts and a fallback, never alone.

What you could say

The rates call is on the checkout path but it isn't essential, so I'd protect it three ways. A 2-second timeout so a slow carrier can't hold our requests. A circuit breaker per carrier: if half of the last 20 calls fail, it opens and we stop calling for 15 seconds, then let a few probes through. And a fallback: flat-rate shipping, flagged in the response so we can measure how often it happens. That way a carrier outage costs us precise quotes for a while, not checkout. I'd alert when a breaker stays open more than five minutes, and I wouldn't retry on top of an open breaker.

Likely follow-ups

Where does the breaker's state live if you have 30 instances?

In each instance by default: they all see the same symptoms and trip within seconds of each other. I'd share it in Redis only if probing from 30 instances at once were a problem for the dependency.

How do retries and the breaker fit together?

Retries go inside the breaker, few and with jittered backoff, so every attempt counts towards its statistics. Once it's open, nothing retries.

What if there's no sensible fallback, like payments?

Then fail fast with a clear error and let the user try again later; that's still better than holding the request for 30 seconds and taking down everything else.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Do I need to write my own breaker?

Rarely. Most languages have a solid library (opossum in Node, resilience4j in Java, pybreaker in Python) and service meshes offer outlier detection. Write one in an interview or to understand it; in production, configure a library and spend the time on thresholds and fallbacks.

Is a breaker the same as a rate limiter?

No. A rate limiter caps how much traffic you send or accept, whatever the outcome. A breaker reacts to outcomes: it lets everything through while the dependency is healthy and nothing while it isn't.

Should the breaker go on the client or the server side?

On the caller, because it protects the caller's capacity. The dependency can protect itself with rate limiting and load shedding.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide2 of 6 · ResilienceRetry with Backoff: Exponential Delays, Jitter and Retry BudgetsRead the next one