Sub topic 6
Circuit breakers: stop calling a failing dependency
This chapter assumes you have read the earlier chapters on timeouts and retries. You should be comfortable with exceptions in Python, with what a timeout does to a request, and with the idea that a slow dependency can be as damaging as a dead one.
The problem a circuit breaker solves
Timeouts bound how long one call can wait. Retries give a flaky call another chance. Neither helps when a dependency is down for a few minutes. Every request still pays the full timeout, and every retry adds more load to a service that is already struggling.
Consider a checkout service that calls a recommendations service with a 500 ms timeout and 3 attempts. If recommendations is down, each page view spends up to 1.5 seconds waiting, plus backoff delays. Threads or connections pile up while they wait. The failing optional dependency now slows the critical path.
A circuit breaker fixes this by remembering recent failures. After enough of them, it stops sending calls and answers from a fallback immediately. This is called failing fast. The caller gets a quick, predictable answer. The dependency gets silence, which gives it room to recover.
The name comes from the electrical device. A breaker trips when too much current flows, and it protects the wiring until someone resets it.
The three states
A circuit breaker is a small state machine with three states.
- Closed: Normal operation. Calls go through to the dependency. The breaker counts failures.
- Open: The dependency is considered unhealthy. Calls are not attempted. The fallback runs immediately.
- Half-open: A cool-down has passed. The breaker lets a trial call through. Success closes the circuit. Failure opens it again.
The names follow the electrical analogy. A closed circuit conducts current, so requests flow. An open circuit does not, so requests are blocked.
A minimal implementation
The sketch below tracks consecutive failures and the time the circuit opened. It has no explicit state variable. The state is implied by opened_at: None means closed, a recent timestamp means open, and an old timestamp means the next call is a half-open trial.
import time
class CircuitBreaker:
def __init__(self, max_failures=3, reset_after=30.0):
self.max_failures = max_failures
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
def call(self, fn, fallback):
if self.opened_at is not None:
if time.monotonic() - self.opened_at < self.reset_after:
return fallback()
# Cool-down elapsed: let this call act as a trial request.
try:
result = fn()
except Exception:
self.failures += 1
if self.failures >= self.max_failures:
self.opened_at = time.monotonic()
return fallback()
self.failures = 0
self.opened_at = None
return resultWalk through the three paths:
- Closed, success.
opened_atisNone, so the call runs. It succeeds,failuresresets to 0, and the result is returned. - Closed, failure. The call raises.
failuresgoes up by one. When it reachesmax_failures,opened_atis set to the current time. The fallback answers this request. - Open. Within
reset_afterseconds,callreturnsfallback()without touching the dependency. After that interval, the next call goes through as the trial. If it fails,failuresis already at or above the threshold, soopened_atis refreshed and the circuit stays open for another full cool-down. If it succeeds, the breaker resets.
The code uses time.monotonic() instead of time.time(). A monotonic clock never jumps backward when the system clock is adjusted, so the cool-down measurement stays correct.
Using it with a fallback
You can pair the breaker with the cache-and-default function from the fallback chapter. The breaker decides whether to call. The fallback decides what to return.
import time
_cache = {}
def get_recommendations(user_id, fetch, timeout=0.5):
"""Return recommendations, falling back to cached or default data."""
try:
items = fetch(user_id, timeout=timeout)
_cache[user_id] = (items, time.monotonic())
return {"items": items, "degraded": False}
except (TimeoutError, ConnectionError):
if user_id in _cache:
items, _ = _cache[user_id]
return {"items": items, "degraded": True, "source": "cache"}
return {"items": [], "degraded": True, "source": "default"}Wrapping this function in breaker.call(...) would work, but notice a subtlety. get_recommendations already catches the exceptions and returns a normal value. The breaker would never see a failure. When you compose the two, the breaker must wrap the raw network call, and the fallback logic must sit outside it:
breaker = CircuitBreaker(max_failures=3, reset_after=30.0)
def recommendations_for(user_id, fetch):
def cached_or_default():
if user_id in _cache:
items, _ = _cache[user_id]
return {"items": items, "degraded": True, "source": "cache"}
return {"items": [], "degraded": True, "source": "default"}
def live():
items = fetch(user_id, timeout=0.5)
_cache[user_id] = (items, time.monotonic())
return {"items": items, "degraded": False}
return breaker.call(live, cached_or_default)Here live raises on failure, so the breaker counts it. cached_or_default never raises, so the response is always usable.
Choosing the parameters
The two parameters in the sketch, max_failures and reset_after, control the trade-off between caution and responsiveness.
| Parameter | Too low | Too high |
|---|---|---|
| `max_failures` | The breaker trips on a brief blip and degrades users unnecessarily. | Many requests suffer the full timeout before the breaker reacts. |
| `reset_after` | Trial calls arrive while the dependency is still down, and the circuit keeps reopening. | Users see degraded behavior long after the dependency has recovered. |
Some practical starting points:
- Set
reset_afternear the typical recovery time of the dependency. A restarting pod might need 10 to 30 seconds. A database failover might need a minute or more. - Count failures against the same definition of failure you use elsewhere. A timeout is a failure. A 5xx response is usually a failure. A 404 or a validation error (400) is usually the caller's mistake, not a sign of an unhealthy dependency, and should not trip the breaker.
- Treat slowness as failure. A dependency that answers every call in 4.9 seconds against a 5 second timeout is not healthy, even though nothing times out. Some libraries support a "slow call" threshold for this reason.
Limits of the simple sketch
The consecutive-failure counter is easy to understand, but it has weaknesses in production.
Consecutive counts versus failure rates
With consecutive counting, one success resets the counter to zero. A dependency that fails 80 percent of the time but succeeds now and then may never trip the breaker. Production libraries usually use a failure rate over a window: for example, open if at least 50 percent of the last 20 calls failed, with a minimum number of calls before the rate counts. This avoids tripping on 1 failure out of 2 calls and also catches intermittent failure.
Thread safety
The sketch is not thread-safe. Two threads can both read failures, both add one, and write back the same value. Worse, when the cool-down ends, every thread that arrives sees an expired timer and runs a "trial" call at once. In a busy service that is a burst of traffic aimed at a dependency that may still be fragile.
The fix has two parts. Protect shared state with a lock, and allow only one trial call, or a small number, in the half-open state. Calls that arrive during the trial get the fallback.
import threading
import time
class SafeCircuitBreaker:
def __init__(self, max_failures=3, reset_after=30.0):
self.max_failures = max_failures
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
self.trial_in_flight = False
self._lock = threading.Lock()
def _may_call(self):
with self._lock:
if self.opened_at is None:
return True, False
if time.monotonic() - self.opened_at < self.reset_after:
return False, False
if self.trial_in_flight:
return False, False
self.trial_in_flight = True
return True, True
def _record(self, ok, was_trial):
with self._lock:
if was_trial:
self.trial_in_flight = False
if ok:
self.failures = 0
self.opened_at = None
return
self.failures += 1
if self.failures >= self.max_failures:
self.opened_at = time.monotonic()
def call(self, fn, fallback):
allowed, was_trial = self._may_call()
if not allowed:
return fallback()
try:
result = fn()
except Exception:
self._record(False, was_trial)
return fallback()
self._record(True, was_trial)
return resultThe lock is held only while reading and updating counters, never during the network call. Holding a lock across fn() would serialize all traffic and defeat the purpose.
Per-instance state
Each process keeps its own breaker. In a fleet of 50 instances, each one must observe failures on its own before it opens. That is usually acceptable, and it avoids a shared store that could itself fail. Be aware that it means the dependency still receives some trial traffic from every instance.
One breaker per dependency
Use a separate breaker for each dependency, and often for each endpoint or host. A single global breaker would let a failing recommendations service shut off calls to a healthy payment service. This connects to the bulkhead chapter, which covers isolating failures in more depth.
How breakers interact with retries and timeouts
The three tools stack in a specific order. From the outside in:
- The circuit breaker decides whether any call is attempted.
- Retries repeat a failed attempt a bounded number of times.
- A timeout limits each individual attempt.
Placing the breaker outside the retry loop means one logical operation, with all of its retries, counts as one success or one failure. That keeps the failure count meaningful. If the breaker sat inside the retry loop, it could open midway through a retry sequence. That is also valid, and some designs prefer it because each attempt counts. What matters is that retries must stop retrying when the breaker is open. Retrying against an open breaker only produces fallback answers more slowly.
import random
import time
def call_with_retry(fn, attempts=3, base=0.1, cap=2.0):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(delay)
def guarded_fetch(user_id, fetch):
return breaker.call(
lambda: call_with_retry(lambda: fetch(user_id, timeout=0.5)),
lambda: {"items": [], "degraded": True, "source": "default"},
)In this arrangement, three failed attempts inside call_with_retry produce one exception, so the breaker records one failure. With max_failures=3, the circuit opens after nine failed network calls. Choose thresholds with that multiplication in mind.
Common mistakes
- Swallowing exceptions inside the guarded function. If
fncatches its own errors and returns a default, the breaker never sees a failure and never opens. - Counting client errors. A burst of 400 responses caused by a bad deploy of your own code should not make you stop calling a healthy dependency.
- A fallback that calls the dependency. If the fallback depends on the same failing service, the circuit breaker protects nothing.
- No visibility. A breaker that opens silently hides an outage. Emit a metric and a log line on every state change, and mark responses as degraded. The chapter on making degraded behavior visible covers this.
- Using a breaker on a critical dependency with no fallback. If there is no acceptable fallback, the breaker can only return an error faster. That can still be worthwhile, because failing fast frees resources, but be clear that it is not graceful degradation.
Testing the breaker
Time makes breakers awkward to test. Inject the clock instead of sleeping for 30 seconds in a test. A simple way is to pass a clock function into the constructor and default it to time.monotonic. Then a test can advance a fake clock and assert the state transitions: closed to open after the threshold, open serving the fallback without calling fn, and half-open closing on success. The final chapter covers fault injection against a running system.
Exercise
A service uses CircuitBreaker(maxfailures=3) around callwith_retry(attempts=3). The dependency goes fully down. How many network calls are made before the circuit opens, and what would change if the breaker wrapped each single attempt instead?
Show answer
With the breaker outside the retry loop, each logical operation makes 3 attempts and counts as 1 failure. The circuit opens after 3 failed operations, which is 9 network calls. If the breaker wrapped each attempt, every attempt would count as one failure, so the circuit would open after 3 network calls, in the middle of the first retry sequence.
Exercise
The half-open state in the simple CircuitBreaker lets every caller through once the cool-down expires. Describe the failure this causes under high concurrency and how to prevent it.
Show answer
When the timer expires, all concurrent requests see an expired cool-down and each runs its own trial call, sending a burst of traffic at a dependency that may still be unhealthy. Prevent it by guarding state with a lock and allowing only one trial call at a time (a trialinflight flag). Other callers receive the fallback until the trial finishes.