Sub topic 6
Circuit breakers: stop calling a failing dependency
This chapter assumes you have read the chapters on timeouts and retries. You should be comfortable with exceptions in Python, with the idea of a fallback response, and with how latency adds up when a service waits on a slow dependency.
Why timeouts and retries are not enough
A timeout bounds how long one call can wait. Retries give a call more chances to succeed. Neither one helps when a dependency is down for minutes. Every request still pays the full timeout, and every retry adds more traffic to a service that is already struggling.
A circuit breaker sits between your code and the dependency. It counts recent failures. When there are too many, it stops sending calls and returns a fallback immediately. After a cool-down it lets one call through to test whether the dependency has recovered.
This gives you two benefits:
- Callers get a fast answer instead of waiting for a timeout.
- The failing dependency gets a break from traffic, which helps it recover.
The three states
A breaker is a small state machine.
- Closed: Calls go through normally. Failures are counted.
- Open: Calls are not made. The fallback is returned at once.
- Half-open: The cool-down has ended. A trial call goes through. If it succeeds, the breaker closes. If it fails, the breaker opens again.
A simple implementation
The sketch below keeps two numbers: a count of consecutive failures and the time the breaker opened. It has no explicit state variable. The breaker is open when opened_at is set and the cool-down has not yet passed.
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 cases:
- Closed.
opened_atisNone, sofn()runs. A success resets the failure count. A failure increments it and returns the fallback. On the third consecutive failure,opened_atis set. - Open. The elapsed time is below
reset_after, so the function returnsfallback()without callingfn. - Half-open. The elapsed time has passed, so the code falls through to the
tryblock. This call is the trial. Success clearsopened_at. Failure increments the count, which is already at the threshold, soopened_atis reset and the cool-down starts over.
Use time.monotonic() for the timer. Wall-clock time can jump when the system clock is adjusted, which would open or close the breaker at the wrong moment.
Using it with a fallback
Pair the breaker with a fallback from the previous chapter's pattern: cached data or a default value.
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()
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 result
def flaky_service():
raise ConnectionError("recommendation service unreachable")
breaker = CircuitBreaker(max_failures=2, reset_after=5.0)
for i in range(4):
result = breaker.call(
flaky_service,
fallback=lambda: {"items": [], "degraded": True},
)
print(i, result, "open" if breaker.opened_at else "closed")The first two calls reach flaky_service and fail. The breaker opens after the second failure. Calls three and four skip the service entirely.
Common errors
- Counting the wrong failures. A
400 Bad Requestcaused by the caller's own bug is not a dependency failure. Count timeouts, connection errors, and 5xx responses. Catching bareException, as the sketch does, is acceptable for a demo but too broad for production code. - Thresholds that are too sensitive. One failure in a hundred calls should not open the breaker. Real libraries use a failure rate over a window of recent calls, often with a minimum call volume.
- Letting every caller trial at once. In the sketch, when the cool-down ends, all concurrent requests may fall through as trials. A production breaker admits one or a few trial calls in the half-open state.
- Ignoring thread safety. The sketch updates shared counters without a lock. Under concurrency, use a lock or a tested library.
- One breaker for everything. A breaker per dependency, and sometimes per endpoint, keeps one bad route from blocking healthy ones.
- A silent fallback. An open breaker is a degraded state. Record it in metrics and mark responses, as the next chapters on fallbacks and visibility describe.
Tuning
| Setting | Too low | Too high |
|---|---|---|
| Failure threshold | Opens on normal noise | Opens late, after many slow calls |
| Cool-down (`reset_after`) | Hammers a dependency that has not recovered | Keeps serving fallbacks after recovery |
Start with the dependency's observed behavior. If it usually recovers within seconds, a cool-down of 30 seconds is long. If outages typically last minutes, a short cool-down wastes trial calls.
Exercise
A breaker has maxfailures=3 and resetafter=30. It opened 31 seconds ago. The next call to the dependency fails. What happens to the breaker, and what does the caller receive?
Show answer
The cool-down has elapsed, so the call runs as a trial. It fails, so the failure count increases and is at or above the threshold, which sets opened_at to the current time. The breaker is open again for another 30 seconds. The caller receives the fallback result.
Exercise
Why does a circuit breaker help a dependency recover, when a timeout alone does not?
Show answer
A timeout still lets every request send a call to the dependency, so the load continues. An open breaker stops those calls entirely during the cool-down, which reduces traffic and gives the dependency room to recover.