Part 11 / Topic 4 of 7
Retries and circuit breakers
Retries (Part 5) protect a request from a transient failure. But when the dependency is down, retries from every worker multiply load against a service already on its knees. The circuit breaker protects both sides — after repeated failures it stops calling for a cooldown, then cautiously tries again:
# examples/02_a_circuit_breaker_stops_hammering_a.py
import time
class CircuitBreaker:
def __init__(self, threshold=3, cooldown_s=30.0, clock=time.monotonic):
self.threshold, self.cooldown, self.clock = threshold, cooldown_s, clock
self.failures, self.opened_at = 0, None
def call(self, fn):
if self.opened_at is not None:
if self.clock() - self.opened_at < self.cooldown:
return "skipped: circuit open"
self.opened_at = None # half-open: let calls through; one more failure reopens it
try:
result = fn()
self.failures = 0
return result
except Exception as e:
self.failures += 1
if self.failures >= self.threshold:
self.opened_at = self.clock()
return f"failed: {e}"
now = [0.0]
breaker = CircuitBreaker(threshold=3, cooldown_s=30, clock=lambda: now[0])
def acme_down(): raise ConnectionError("Acme API timeout")
for t in [0, 1, 2, 3, 4, 40]:
now[0] = t
print(f"t={t:>2}s", breaker.call(acme_down))
# t= 0s failed: Acme API timeout
# t= 1s failed: Acme API timeout
# t= 2s failed: Acme API timeout
# t= 3s skipped: circuit open
# t= 4s skipped: circuit open
# t=40s failed: Acme API timeout
Trace the states: three failures open the circuit; at t=3 s and 4 s the breaker answers instantly without touching the dependency (your service stays responsive, their API gets room to recover); after the 30 s cooldown it goes half-open and tries one real call — which fails here, re-opening the circuit. Note the injected clock: the breaker is testable without sleeping, the same dependency-injection trick as TestClient.
Division of labour: timeouts bound one call, retries absorb blips, breakers survive outages. You want all three, in that order of wiring.
🧪 Quick quiz
- What does a circuit breaker do after repeated failures?
Show the answer
Stops calling the failing dependency for a cooldown, then tries again. After 3 failures, calls at t=3 s and 4 s were skipped; at t=40 s it tried again. (verified against the example output above)
Done here? The practice set for Part 11 — 4 exercises with solutions — is on the part page.