What Is the Circuit Breaker Pattern - and When You Actually Don't Need One
The circuit breaker pattern is a guard you put in front of a remote call so that when the dependency on the other end is already failing, you stop calling it and fail immediately instead. It exists because the circuit breaker pattern solves a problem that retries make worse: a sick service does not recover while you are still hammering it, and your own service dies waiting.
The name comes from the electrical device, and the analogy is tighter than most borrowed metaphors. A household breaker does not fix the fault in your wiring. It isolates the fault so the rest of the house keeps working, and it refuses to carry current again until someone decides the fault is cleared.
The failure it prevents is specific. When a downstream service slows from 20ms to a 30-second timeout, every caller thread sits blocked. Your thread pool fills. Requests that have nothing to do with that dependency start queueing behind the ones that do. The outage spreads from one service to everything that touches it — a cascading failure. The breaker's job is to convert a slow failure into a fast one, because a fast failure is survivable and a slow one is contagious.
This page covers the state machine, the counting, and the half-open probe that makes it work — then the cases where adding one is the wrong call.
| Concept | Circuit Breaker Pattern |
|---|---|
| Where it sits | Resilience - wraps the client side of a remote call, between your code and the network |
| In one sentence | A client-side state machine that stops sending requests to a dependency that is already failing, so the caller fails fast instead of exhausting its own resources waiting. |
The 60-Second Answer
What it does: wraps calls to a dependency, counts failures, and when the failure rate crosses a threshold it stops making the calls at all — returning an error or fallback immediately, without touching the network.
The one problem it solves: your service staying alive when a dependency is slow or down. It stops you from burning threads, connections, and latency budget on calls that are already going to fail, and it takes load off the dependency so it has room to recover.
The one cost it adds: state. Every breaker has thresholds you have to tune, and it will eventually fail requests that would have succeeded. You have now built a thing that can be wrong in both directions, and you need a dashboard and an alert for it.
When to skip it: if the call has no fallback, is not on a shared thread pool, and a bounded timeout already protects you, a timeout plus bounded retries is the simpler correct answer.
How It Actually Works
The mechanism, step by step
- 1. The breaker wraps one call site, not the whole service
- 2. Closed is the normal state, and it is still counting
- 3. The window decides what 'failing' means
- 4. Open means the call does not happen
- 5. Half-open sends a few real requests to find out
- 6. State is per process, so a fleet has many breakers
- 7. It composes with timeouts, retries, and bulkheads - in that order
1. The breaker wraps one call site, not the whole service
Scope is per dependency, per operation
A breaker is an object in your process that sits between your code and one remote dependency. You call through it instead of calling the client directly, and it decides whether the call happens at all. It lives on the caller's side — the dependency does not know it exists and does not need to cooperate.
The unit of scope matters more than people expect. One breaker per dependency is the common default, but the right unit is usually one breaker per dependency and operation class, because a slow search endpoint and a healthy write endpoint on the same host have nothing to do with each other.
// the breaker is a wrapper, not a side effect
const result = await inventoryBreaker.call(() =>
inventoryClient.checkStock(sku)
);
⚠️ In production — Scope too wide and one broken endpoint trips the breaker for every call to that service, including the healthy ones. Scope too narrow — a breaker per URL with a path parameter in it — and each breaker sees too few calls to ever reach a statistically meaningful failure rate, so it either never trips or trips on noise.
2. Closed is the normal state, and it is still counting
Traffic flows, outcomes are recorded
In the closed state every call passes through to the dependency. The breaker's only job here is bookkeeping: it records each call as a success or a failure and keeps that record in a bounded window.
What counts as a failure is a decision you make, and it is the decision people get wrong. A connection refused is a failure. A timeout is a failure. A 500 is a failure. A 404 or a 422 is not a failure — the dependency answered correctly, your request was simply wrong. If you count application-level rejections as failures, a burst of bad client input will trip the breaker and take down a service that was perfectly healthy.
⚠️ In production — Timeouts are the failure class that actually trips breakers in production, and they only register as failures if the underlying client has a timeout configured. A breaker in front of a client with no timeout is decoration: the call hangs, the thread blocks, nothing is ever recorded as a failure, and the breaker stays closed through the entire outage.
3. The window decides what 'failing' means
Rate over a bounded sample, not a raw count
The breaker needs to answer "is this dependency failing now", which means the measurement has to forget the past. Two shapes are common. A count-based window keeps the last N outcomes. A time-based window keeps the outcomes from the last N seconds, usually in rotating buckets so old data ages out smoothly.
Both almost always use a failure rate rather than a raw count, plus a minimum-calls floor before the rate is allowed to trip anything. Without that floor, the first two calls after a deploy failing gives you a 100% failure rate on a sample of two, and the breaker opens on nothing.
The tradeoff is the usual one: a short window reacts fast and is twitchy under low traffic; a long window is stable and leaves you failing calls for longer before it notices.
⚠️ In production — A time-based window on a low-traffic endpoint is a trap. If an endpoint gets a handful of calls per minute, a 10-second window will usually be empty, the minimum-calls floor never clears, and the breaker is effectively disabled exactly on the paths where a single stuck call hurts most. Low-traffic calls want a count-based window or no breaker at all.
4. Open means the call does not happen
Fail fast, locally, without the network
Once the threshold is crossed the breaker moves to open and the behaviour changes completely: calls are rejected locally. No socket, no DNS lookup, no thread parked waiting. The caller gets an error — or a fallback, if you have one — in microseconds instead of seconds.
This is the whole point, and it does two things at once. Your service stops spending resources on doomed calls, so the rest of your traffic keeps moving. And the dependency stops receiving load, which is often what it needs to recover: a service in a retry storm cannot drain its queue, flush its connection pool, or finish a GC pause while you keep pushing.
The breaker stays open for a fixed cooldown, then moves on by itself. Nobody pages a human to reset it.
⚠️ In production — An open breaker is a visible error to someone, and the error you return matters. Returning a 500 to your own caller just moves the failure up one layer and may trip their breaker. Decide deliberately per call site whether open means a degraded response (cached data, a default, a feature hidden) or a real error, and make sure the error you emit is distinguishable in logs from a genuine downstream failure — otherwise your dashboards will show an outage lasting far longer than the real one.
5. Half-open sends a few real requests to find out
Probe with limited traffic, decide, commit
After the cooldown the breaker enters half-open, the state that makes the pattern work. It allows a small number of trial calls through and blocks the rest. If the trials succeed, it closes and normal traffic resumes. If they fail, it goes straight back to open and the cooldown starts again.
The design choice here is that there is no way to check health without spending a real request. A separate health endpoint tells you whether the process is up, not whether your call pattern works — a database connection pool can be exhausted while /health returns 200 all day. So the breaker gambles a few real user requests as the probe.
Some implementations add backoff: each failed probe lengthens the next cooldown, so a dependency that is down for an hour is not probed every ten seconds for that hour.
⚠️ In production — Half-open concurrency is the one setting people forget. If the half-open state admits unlimited calls for its duration instead of a capped number of trials, every instance in your fleet dumps full traffic onto a barely-recovering dependency at the same moment, kills it again, and you oscillate between open and dead. Cap the trial count, and if you can, jitter the cooldown across instances so they do not probe in lockstep.
6. State is per process, so a fleet has many breakers
No shared brain, and that is deliberate
The breaker's counters live in memory in one process. Run fifty instances and you have fifty independent breakers, each with its own view of the dependency, tripping at different moments based on the traffic it happened to see.
This is a deliberate tradeoff rather than an oversight. A shared breaker state in Redis or a coordination service would give you a consistent fleet-wide decision — and a new network dependency in the hot path of every single call, which can itself fail, which you would then need a breaker for. Local state means the breaker can never be the thing that breaks.
The practical consequence is that the fleet degrades gradually. Instances trip over a spread of seconds rather than all at once, which is usually better behaviour than a synchronised fleet-wide cliff.
⚠️ In production — This destroys naive reasoning about what you see in production. A dependency can be fully down while a third of your instances still report the breaker closed, because they are the ones with low traffic and haven't filled their window. Emit breaker state as a per-instance metric, not an aggregate — an average across the fleet tells you nothing useful, and 'the breaker is open' is not a yes/no question you can answer for a cluster.
7. It composes with timeouts, retries, and bulkheads - in that order
The breaker is one layer of four
A breaker alone fixes very little. The layers stack in a specific order and each one does a job the others cannot.
The timeout bounds how long a single call can take; without it nothing else works. Retries handle the genuinely transient failure — one dropped packet, one instance rebooting — and must be bounded and jittered. The breaker sits outside the retries and handles the failure that is not transient, cutting off the retry budget once the pattern says the dependency is actually broken. A bulkhead (a separate thread pool or concurrency limit per dependency) makes sure that even when a breaker is late to trip, the damage is confined to one pool.
Get the nesting wrong and the layers fight: retries outside the breaker will retry the breaker's own fast rejection, hammering a fallback path at full speed.
⚠️ In production — Retry-inside-breaker means your failure counting is distorted: three retries of one failing call can register as three failures or one depending on where you count, which silently changes the effective threshold by 3x. Decide whether a retried call is one outcome or several, write it down, and check what your library actually does — the defaults differ between implementations.
## Where You Meet It
- A checkout service calls a recommendation service to populate a 'you might also like' panel. The recommendation service degrades under load and starts taking 20 seconds to respond. Without a breaker, checkout requests block on a non-essential call and the whole purchase flow stalls. With one, the breaker opens after the failure rate crosses the threshold, the panel renders empty, and checkout completes at full speed. This is the ideal case: a non-critical dependency with an obvious fallback.
- An API gateway fronts a dozen backend services on a shared thread pool. One backend's database runs out of connections and every call to it hangs. The gateway's threads fill up with requests to that one backend, and requests to the other eleven healthy services start timing out in the queue. Per-backend breakers plus per-backend concurrency limits keep the broken one from consuming the shared capacity — this is the cascading-failure scenario the pattern was built for.
- A mobile backend calls a third-party payment provider that has a rate limit and a published incident history. During a provider outage, retries from thousands of app instances turn into a stampede the moment the provider starts recovering. A breaker with backoff on each failed probe spreads the reconnection out, and the app shows 'payments temporarily unavailable' instead of a spinner that never resolves.
- A batch job enriches records by calling an internal service a few million times. Midway through, the service starts failing. Without a breaker, the job grinds on for hours, logging errors and generating load the whole time. With one, the job's calls start failing in microseconds — which means the job finishes fast and wrong unless you also decided what the job does when the breaker is open. The breaker made the failure fast; it did not make the batch correct.
When You Actually Need It
- You have measured, or seen in an incident, that your caller threads or connection pool fill up while waiting on one specific dependency — the resource exhaustion is observed, not hypothetical.
- The dependency is shared by multiple call paths in your process, so its slowness already demonstrably affects requests that do not use it.
- There is a meaningful degraded response available: cached data, a default value, a hidden feature, a queued write. A breaker is most valuable when open mode is better than waiting.
- The dependency's failure mode is slow rather than fast. Connection-refused is already a fast failure and hurts you much less than a 30-second hang.
- You are calling across a boundary you do not control — a third party, another team's service, another region — where failures are correlated across many of your requests rather than independent.
- You have retries in place and have seen them amplify an outage, turning a struggling dependency into a dead one.
When You Don't
- A single service calling a single database it owns. If the database is down your service cannot do its job anyway, and a breaker just changes the error message. A connection pool with a bounded acquisition timeout and a sane query timeout already gives you fail-fast behaviour. Use the timeout; skip the breaker.
- Low-traffic call paths. If a call site sees a handful of requests per minute, no window will produce a trustworthy failure rate. The breaker either never trips or trips on two unlucky calls. A per-call timeout plus one bounded retry is the correct implementation at that volume, and it has no thresholds to get wrong.
- When you have no fallback and no shared resource to protect. If an open breaker means returning the same error you would have returned after the timeout, and the call has its own dedicated connection pool so a hang hurts nothing else, the breaker adds configuration and a failure mode and buys you only the latency you would have spent on the timeout. Shorten the timeout instead.
- In-process and local calls. Function calls, in-memory caches, and local disk reads fail fast and deterministically. There is no queue of blocked threads to protect and no remote service to give breathing room. Wrapping them in a breaker is cargo-culting.
- Non-idempotent writes with no fallback path. An open breaker rejects the write, and if you have not built somewhere for that write to go — an outbox, a queue, a durable retry — you have converted a slow success into a fast data loss. Build the durable write path first; the breaker is only safe once rejection has a defined meaning.
- When a service mesh or gateway in your path already provides outlier detection. Adding a second breaker in application code on the same hop gives you two state machines with different thresholds on the same traffic, and incidents where you cannot tell which one rejected the call. Pick one layer and configure it properly.
What People Get Wrong
"Adding circuit breakers makes the system more resilient."
It makes the system fail differently, and whether that is better depends entirely on what you do in the open state. A breaker with no fallback converts a slow error into a fast error — real value if threads were the bottleneck, and nothing at all if they were not. The resilience lives in the degraded path you build, not in the state machine.
"The defaults in the library are fine to start with."
Default thresholds are picked for a hypothetical workload, usually a moderately busy HTTP endpoint. The two settings that actually determine behaviour — the minimum-calls floor and the window size relative to your real traffic rate — are the ones most sensitive to your specific volume. A default window on a low-traffic path produces a breaker that silently never trips.
"An open breaker means the dependency is down."
It means one process's bounded sample of calls crossed a threshold. That can happen from a network partition affecting only that instance, from one unlucky burst at low volume, or from counting client errors as failures. The breaker is an unreliable signal about the dependency's health and a reliable signal about one caller's recent experience — treat the alert as 'investigate', not 'the dependency is down'.
"Circuit breakers replace retries."
They solve opposite problems and you usually want both. Retries handle the independent transient failure, where trying again genuinely works. Breakers handle the correlated persistent failure, where trying again never works and makes things worse. The breaker's real job in that pair is to put a ceiling on the retry budget once the failure stops looking transient.
Why It Was Built This Way
The constraint that forced this design is that a caller cannot see the state of its dependency. All you have are the outcomes of calls you already made. There is no reliable remote signal — a health endpoint reports whether a process is accepting connections, which is almost uncorrelated with whether a particular query against a particular exhausted connection pool will return. So the breaker is built entirely from local observation of past calls, and every property of the pattern follows from that.
It explains the state machine's asymmetry. Opening is cheap and based on accumulated evidence you already have. Closing is expensive, because the only way to learn that a dependency recovered is to send it a real request and risk a real user's response on the answer. Half-open exists because that is the minimum-cost version of that gamble: spend a few requests, not all of them. It also explains why the counting uses a rate over a bounded window rather than a total — a cumulative count has no way to distinguish "failing right now" from "failed a lot last Tuesday", and forgetting is the only mechanism available for freshness.
What was traded away is correctness on individual requests. A breaker will reject calls that would have succeeded. That is not a bug being tolerated; it is the deal. The pattern assumes that when a dependency's failure rate is high, the expected value of the next call is negative once you price in the thread it occupies and the load it adds — so rejecting without trying is the better bet in aggregate, even though it is wrong for some specific requests. The second thing traded away is global consistency. Keeping state local means fifty instances hold fifty different opinions and the fleet never acts as one, which was accepted because the alternative — coordinating breaker state over the network — puts a failable dependency inside the mechanism whose entire purpose is surviving failable dependencies.
This is why tuning a breaker is uncomfortable and always will be. You are not configuring a detector of a knowable fact. You are setting how much evidence you need before you start making a deliberately wrong decision, and how much you are willing to pay to find out you can stop.
Related Briefs
What to Read Next
- bulkhead pattern vs circuit breaker
- exponential backoff and jitter for retries
- graceful degradation and fallback strategies
- service mesh outlier detection
Reach for a circuit breaker when you can point to a shared resource — a thread pool, a connection pool, a latency budget — that one slow dependency has already consumed, and when you have somewhere useful to go when the call is refused. If a bounded timeout already contains the damage and the open state returns the same error anyway, you are adding a tunable state machine for no gain. The breaker's value is never the state machine; it is the degraded path you built behind it, and the thresholds are a judgement about how much evidence buys the right to be deliberately wrong.
댓글
댓글 쓰기