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.