Course contents

09. Reliability and Resilience Lesson 4 of 10

Circuit Breaker

See why a slow dependency is dangerous, how retries amplify overload, and how a circuit breaker fails fast, backs off and detects recovery.

14 minIntermediate6 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A slow dependency ties up callers for the whole timeout; a queue at the dependency can make almost every call fail.
  • Retries help with brief faults and multiply load during overload; they never guarantee success.
  • A breaker opens when too many recent calls failed and then fails calls instantly without sending them.
  • After a pause it lets a few trial calls through (half-open) and closes again when they succeed.
  • A breaker does not fix the dependency; a fallback decides what users see while it is open.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A circuit breaker is a small state machine wrapped around calls to a dependency. While it is closed, calls go through and their outcomes are recorded. When the failure rate over a recent window crosses a threshold, it opens: for a cool-down period every call fails immediately, without being sent. Then it goes half-open and lets a few trial calls through; if they succeed it closes, if not it opens again. The name comes from the electrical breaker that cuts the circuit to stop damage from spreading.

Why it exists

When a dependency is down and refuses connections, callers find out at once. When it is slow, every call waits for the full timeout, holding a thread, a connection and memory in the caller. A caller with 200 threads and a 2 s timeout can then serve at most 100 requests per second, however fast its own code is. Meanwhile the dependency keeps working on requests whose callers have given up, so its useful throughput collapses. Retries make it worse by sending more calls exactly when there is no capacity. The breaker cuts this loop: it stops calls to a dependency that is clearly failing, frees the caller, and gives the dependency room to recover.

How it works

Closed. Calls pass through. The breaker keeps a sliding window of outcomes (by time or by count). Timeouts and errors count as failures; client errors such as validation failures usually do not.

Opening. If the window holds at least a minimum number of calls and the failure ratio is above the threshold (say 50% of at least 20 calls), the breaker opens. The minimum avoids opening on one unlucky call at low traffic.

Open. Every call fails immediately with a "circuit open" error, or goes straight to a fallback. No network call, no waiting.

Half-open. After the open period, a limited number of trial calls go through. If they succeed, the breaker closes and resets its window. If any fails, it opens for another period.

Together with timeouts and retries. The timeout caps how long one call may take. Retries, with exponential backoff and jitter, absorb short, random faults. The breaker stops both from hammering a dependency that is clearly in trouble: a good retry policy does not retry while the circuit is open.

When to use it

  • Around every call to a remote dependency whose failure or slowness could exhaust the caller: other services, databases, third-party APIs.
  • When there is a sensible fallback, or when failing fast is better for users than waiting.
  • In fan-out services, where one bad dependency would otherwise drag down every request.

When not to

  • Around purely local work, or calls that cannot fail independently of the caller.
  • Instead of fixing capacity: a breaker hides overload from the caller, it does not remove it.
  • With very low, bursty traffic, where the window rarely has enough calls to make a sound decision; rely on timeouts and retries.

Trade-offs

Choice You gain You pay
Low failure threshold / small window Opens quickly Opens on brief blips, rejecting calls that would have worked
High threshold / large window Ignores noise Callers wait on a failing dependency longer
Long open period Dependency gets real breathing room Slower to notice recovery
Few half-open trials Little risk while probing Slower, noisier recovery decision
One breaker per dependency (or endpoint) A bad dependency does not block healthy ones More configuration and metrics

Alternatives

  • Timeouts alone: cap waiting, but every call still waits the full timeout while the dependency is failing.
  • Bulkheads: separate thread or connection pools per dependency, so one cannot exhaust the caller; complements a breaker.
  • Load shedding and rate limiting at the dependency: protect the dependency from the server side.
  • Asynchronous messaging: remove the dependency from the request path entirely.
  • Adaptive concurrency limits: lower the number of in-flight calls when latency rises.

Failure modes

  • Flapping: thresholds tuned too tightly make the breaker open and close repeatedly; users see alternating success and errors.
  • Stuck open: a misconfigured check (wrong errors counted, no trial calls) keeps a recovered dependency cut off.
  • Shared breaker for unrelated calls: one failing endpoint opens the breaker for all endpoints of a service.
  • Retry storm despite the breaker: retries placed outside the breaker, or at many layers (client, gateway, service), multiply load anyway. Retry at one layer.
  • No fallback: the breaker fails fast, but every user still gets an error; the outage is shorter for the caller, not for the user.

In production

Use a library (Resilience4j, Polly, the circuit breaking in a service mesh) rather than writing one. Configure one breaker per dependency, combined with timeouts, bounded retries with jitter, and a bulkhead. Count timeouts and 5xx responses as failures, not 4xx. Publish breaker state as a metric and alert when it opens. Define the fallback per use case: cached data, a default, a degraded feature, or a queued request to complete later. Test it by injecting latency, not just errors.

Common misconceptions

  • "The circuit breaker fixes the failing service." It protects the caller and reduces load; the dependency still has to recover.
  • "Retries make calls reliable." They improve the odds against transient faults and make overload worse; success is never guaranteed.
  • "A slow service is better than a dead one." For callers, slow is often worse: it ties up their resources for the whole timeout.
  • "Open means the service is down." It means recent calls failed often enough; the service may already be recovering.

Interview angle

When a design has synchronous dependencies, mention timeouts, retries with backoff and jitter, and circuit breakers together, and explain the difference: timeouts cap waiting, retries absorb blips, breakers stop hammering. Interviewers probe the state machine (closed, open, half-open), how thresholds are chosen, where retries live so they do not multiply, and what the user sees while the circuit is open. A concrete fallback ("accept the order and charge asynchronously") is a strong answer.

Model assumptions

The simulation is a simplified model, not a benchmark. Checkout calls Payments 40 times per second (Poisson) with a 1 s timeout. Payments has 8 workers, an 80 ms mean service time (lognormal, cv 0.3) and room for 40 waiting calls; degraded, it is 4× slower. Calls whose caller timed out are still processed. Retries use up to 3 attempts with exponential backoff (100–400 ms, full jitter) and stop while the circuit is open. The breaker opens when at least half of at least 10 calls in the last 2 s failed, stays open 2 s and allows 3 half-open trial calls. Latency figures count successful calls only. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Checkout depends on Payments

    The Checkout service calls Payments about 40 times a second. Each call takes roughly 100 ms including the network. Checkout gives up on a call after a 1 second timeout.

    Payments can handle about 100 calls per second, so it is under half busy and every call succeeds.

    Scene: Checkout calls Payments 40 times per second. Payments is under half busy; calls take about 100 ms and all succeed.

    Key idea: Every remote call can be slow or fail. A timeout is the first line of defence: it caps how long you wait.

  2. 2. Payments becomes slow

    One second in, Payments slows down four times (a bad deploy, a struggling database). It can now finish only about 25 calls per second, but Checkout keeps sending 40.

    Calls pile up in Payments’ queue, and soon the wait alone is longer than Checkout’s 1 second timeout; when the queue is full, calls are rejected outright. Payments is 100% busy, yet almost nothing succeeds: it keeps working on calls whose caller already gave up.

    Scene: Payments slows down. Its queue fills, calls wait for the full 1 second timeout, and almost all of them fail with timeouts or rejections even though Payments is 100% busy.

    Key idea: A slow dependency is worse than a dead one: every call ties up the caller for the whole timeout.

  3. 3. Retries make it worse

    A natural reaction: retry failed calls, up to 3 attempts with exponential backoff. Against a brief glitch that helps. Against an overloaded dependency it does the opposite.

    Each failure now produces up to two more calls. Payments receives far more than 40 calls per second, its queue stays full, and the error rate does not improve. Retries do not create capacity; they spend it.

    Scene: Checkout retries failed calls. Payments receives many more calls than before, stays overloaded, and the error rate stays high.

    Key idea: Retries help with transient faults and hurt with overload. They never guarantee success.

  4. 4. A circuit breaker stops the calls

    Checkout now wraps the call in a circuit breaker. While it is *closed*, calls pass and it counts failures. When at least half of the calls in the last 2 seconds failed, it opens: for the next 2 seconds Checkout fails calls instantly, without sending them.

    Failing fast frees Checkout from waiting on timeouts and gives Payments room to breathe. It does not fix Payments: calls still fail, they just fail quickly and cheaply. Retries also stop while the breaker is open.

    Scene: The breaker on Checkout opens and closes repeatedly. While open, calls fail immediately without reaching Payments, which receives far fewer calls. The error rate stays high.

    Key idea: A circuit breaker turns slow failures into fast ones and takes pressure off a struggling dependency. It does not make the dependency work.

  5. 5. Testing the water

    After 2 seconds open, the breaker goes half-open: it lets 3 trial calls through. If any fails, it opens again for another 2 seconds. If all succeed, it closes and normal traffic resumes.

    To fix the slowness, the team restarts Payments: it is down for a moment, so trial calls fail and the breaker reopens. Payments comes back healthy 1.5 seconds in; the next trial calls succeed, the breaker closes and the errors stop on their own, without anyone touching Checkout.

    Scene: Payments is down while it restarts; the breaker’s trial calls fail and it stays open. When Payments is back, the next half-open trial calls succeed and the breaker closes; calls flow normally again.

    Key idea: Half-open probes let the caller notice recovery automatically, with only a few calls at risk.

  6. 6. What to do while the circuit is open

    An open breaker still means a failed checkout unless you plan a fallback: accept the order and charge later through a queue, show a cached answer, hide a non-essential feature, or return a clear "try again in a minute".

    Tune the thresholds from real data: too sensitive and one blip blocks a healthy service; too lax and callers waste time on a dead one. Use one breaker per dependency and alert when it opens.

    Scene: Checkout calls a healthy Payments service through a closed circuit breaker with timeouts and retries; every call succeeds.

    Key idea: Timeouts cap waiting, retries absorb blips, breakers stop hammering. A fallback decides what the user sees.