Circuit Breaker
Stop hammering a service that's already down, so one sick dependency doesn't drag the whole system under.
Circuit breaker in 30 seconds
- What: a wrapper around calls to a dependency that 'trips' when that dependency keeps failing.
- Why: stop piling requests onto something already down, and fail fast instead of making users wait for timeouts.
- Three states: Closed (calls flow), Open (fail instantly, don't even try), Half-open (let one test call through to see if it recovered).
- Pairs with: timeouts, retries with backoff, and a fallback (cached value, default, degraded mode).
- Stops cascading failure — one slow service can't exhaust every caller's threads and take them down too.
The breaker in your fuse box
There's a reason your home has circuit breakers and not just wires. When something shorts out — a faulty appliance, too much load on one line — the breaker trips and cuts the power to that circuit. It's not being unhelpful; it's stopping a small fault from overheating the wiring and burning the house down. Crucially, it fails fast and loud (the lights go out instantly) rather than slowly (the wires quietly melting). And once you've fixed the problem, you flip it back on.
A software circuit breaker is that exact device for service calls. When a dependency starts failing, the breaker trips, stops sending requests its way, and makes callers fail instantly instead of waiting. The struggling service gets room to recover, and everything upstream is protected from the fault spreading.
The problem, told simply
Think of the electrical breaker in your home. When something shorts out, the breaker trips and cuts the power — not to annoy you, but to stop the fault from burning the house down. A software circuit breaker does the same for service calls. When a dependency starts failing, the breaker trips and stops sending requests its way, giving it room to recover and protecting everything upstream.
Why 'just retry' makes things worse
Here's the failure that circuit breakers prevent — a cascading failure:
- Service B gets slow. Service A keeps calling it and waits on each call.
- A's threads pile up waiting for B, so A gets slow too.
- Now C, which calls A, starts backing up. The slowness spreads outward.
- Retries pour even more load onto the already-struggling B, so it never recovers.
- Minutes later, a single sick service has taken down half the system.
The breaker breaks this chain: once B is clearly failing, A stops calling it and fails fast instead of waiting, so A stays healthy and B gets breathing room.
Why a slow failure is worse than a fast one
The subtle danger isn't the errors — it's the waiting. Each server has a limited pool of threads (or connections). When a dependency hangs, every request to it holds a thread hostage for the full timeout — often 30 seconds. At even modest traffic, those held threads pile up faster than they're released, the pool runs dry, and now the server can't answer any request, even ones that have nothing to do with the sick dependency. A fast failure returns the thread immediately; a slow one strangles the whole server. The breaker converts the slow, thread-eating failure into a fast one.
The three states
- Closed — normal. Calls flow through; the breaker just counts failures.
- Open — tripped. Too many recent failures, so calls fail instantly without even trying. After a cooldown, it moves to half-open.
- Half-open — cautious. Let a single trial call through. If it succeeds, close the breaker (recovered). If it fails, open again and wait longer.
def call(self, fn):
if self.state == OPEN:
# cooldown elapsed? give recovery one trial
if now() - self.opened_at >= self.cooldown:
self.state = HALF_OPEN
else:
raise CircuitOpen() # fail fast, don't even try
try:
result = fn() # the real downstream call
except Exception:
self.failures += 1
if self.failures >= self.threshold:
self.state = OPEN # trip: too many recent failures
self.opened_at = now()
raise
# success: a half-open trial that works means we've recovered
self.failures = 0
self.state = CLOSED
return resultWhat to do when the breaker is open
Failing fast is only half the answer — you also decide what the user sees. Good options, roughly in order of niceness:
- Serve a fallback — a cached value, a sensible default, or a trimmed-down response.
- Degrade gracefully — hide the feature that depends on the broken service, keep the rest working.
- Queue for later — accept the request and process it once the dependency is back.
- Fail clearly — if none of the above fit, return a clean error fast rather than a slow timeout.
def get_recommendations(user_id):
try:
# breaker may raise CircuitOpen instantly instead of hanging
return breaker.call(lambda: reco_service.fetch(user_id))
except CircuitOpen:
# dependency is known-down: degrade instead of erroring
cached = cache.get(f"recos:{user_id}")
if cached:
return cached # stale but useful
return DEFAULT_RECOMMENDATIONS # trimmed-down safe defaultThe resilience kit around the breaker
A circuit breaker rarely works alone — it coordinates a small toolbox, and each tool covers a different failure shape. The breaker decides whether to even try; the others shape how you try and what happens when you don't.
| Tool | What it does | Why it pairs with the breaker |
|---|---|---|
| Timeout | Caps how long one call may hang | Without it, a 'failure' never arrives — the call just waits forever |
| Retry + backoff | Re-attempts a transient blip, with growing gaps | Handles the one-off hiccup; the breaker stops retries from becoming a flood |
| Bulkhead | Isolates thread pools per dependency | Stops one sick dependency from draining threads the whole app shares |
| Fallback | Serves a cached/default/degraded response | Gives the user something when the breaker is open |
def guarded_call(fn):
# 1) timeout: a hang becomes a failure the breaker can SEE
# 2) a couple of backed-off retries absorb a transient blip
for attempt in range(3):
try:
return call_with_timeout(fn, seconds=2) # cap the wait
except Timeout:
sleep(0.2 * (2 ** attempt)) # exponential backoff
raise Timeout() # out of retries -> this counts toward tripping
# The breaker wraps guarded_call. Order matters: timeout makes hangs fail,
# retries smooth blips, and the breaker stops retries becoming a flood.Tuning it without shooting yourself
| Knob | Too low / short | Too high / long | Aim for |
|---|---|---|---|
| Failure threshold | Trips on a harmless blip | Lets the cascade start before tripping | A clear failure trend (e.g. 50% over a window) |
| Cooldown before half-open | Probes a still-sick service, re-trips | Stays dark long after recovery | Roughly the dependency's typical recovery time |
| What counts as 'failure' | Trips on expected 4xx client errors | Ignores timeouts that are the real problem | Count timeouts and 5xx; ignore user errors |
A circuit breaker is a small piece of code with an outsized job: it's one of the main things standing between a single slow dependency and a full-system outage, so it sits right at the heart of how resilient systems stay up.
Why it matters
- It converts a slow, hanging failure into a fast, predictable one — users get a quick answer instead of a 30-second spinner.
- It stops a struggling dependency from being buried under retries, giving it the quiet it needs to actually recover.
- It contains blast radius: one sick service can't exhaust every caller's threads and drag healthy services down with it.
If ignored
- Cascading failure — a single slow service backs up its callers, then their callers, until half the system is down.
- Thread-pool exhaustion as requests pile up waiting on timeouts that never come.
- A dependency that can't recover because the moment it tries, a wall of retries knocks it over again.
Where it fits
- Sits on the client side of every risky outbound call — to another service, a database, or a third-party API.
- Pairs with timeouts, retries with backoff, and a fallback; the breaker is the coordinator of that resilience kit.
- Often lives in a shared library, service mesh, or gateway so every call gets the protection by default.
Related topics
- Availability & reliability: the breaker is one of this topic's most practical tools
- Rate limiting: a sibling guardrail — one sheds load, the other stops hammering the fallen
- Service discovery: heartbeats detect the dead node; the breaker handles the dying one
- API gateway: a natural place to apply breakers across many downstream calls
Interview lens
Questions it unlocks
- How do you stop one failing service from taking down the whole system?
- What are the states of a circuit breaker?
- What do you return to the user when the breaker is open?
60-second answer
A circuit breaker wraps calls to a dependency and trips when it keeps failing, so instead of piling on requests and waiting through timeouts, callers fail fast and the sick service gets room to recover. It has three states — closed, open, and half-open, which lets a single trial call test recovery. I pair it with a timeout so hangs count as failures, retries with backoff, a bulkhead to isolate thread pools, and a fallback like a cached value or degraded mode so the user still gets something. The whole point is breaking the cascade where one slow service exhausts every caller's threads and spreads the outage.
Common traps
- Retrying hard against a failing service and accelerating its collapse.
- Leaving thresholds and cooldowns at defaults that don't match the dependency.
- Tripping the breaker but having no fallback, so the user still just gets an error.
- Running a breaker with no timeout, so hanging calls never trip it.