Sub topic 13
Stopping Calls During Sustained Outages with a Circuit Breaker
This chapter assumes you can write the retry loop from the earlier chapters: exponential backoff, jitter, Retry-After, and attempt limits. It also assumes you know which errors are retryable. Here you add a component that watches many calls and stops sending requests when the provider is clearly down.
Why retries are not enough
Retries handle brief faults. A request fails, the client waits, and the next attempt usually works. During a sustained outage that logic works against you:
- Every request spends its full retry budget, so each user waits for the slowest possible failure.
- Threads, connections, and async tasks stay occupied by calls that cannot succeed.
- Thousands of clients retrying at once add load to a provider that is already struggling, which can prolong the outage.
- Your own application can fail, even though it only depends on the provider, because its workers are all stuck waiting.
A circuit breaker counts recent failures. After enough of them, it rejects calls immediately for a cool-down period without contacting the provider. This is called failing fast. Your code can then switch to a fallback, such as a cached answer or a second model, instead of waiting for a timeout.
The three states
A breaker is a small state machine.
- Closed: normal operation. Calls go through, and the breaker counts failures.
- Open: calls are rejected immediately. The breaker stays open until the cool-down expires.
- Half-open: the cool-down is over. The breaker lets a limited number of probe calls through. If a probe succeeds, the breaker closes. If it fails, the breaker opens again for another cool-down.
A minimal breaker and its limits
This is the smallest useful version:
import time
class CircuitBreaker:
def __init__(self, failure_threshold=5, reset_after=30.0):
self.failure_threshold = failure_threshold
self.reset_after = reset_after
self.failures = 0
self.opened_at = None
def allow(self) -> bool:
if self.opened_at is None:
return True
# After the cool-down, let calls through again to probe the service.
return time.monotonic() - self.opened_at >= self.reset_after
def record_success(self) -> None:
self.failures = 0
self.opened_at = None
def record_failure(self) -> None:
self.failures += 1
if self.failures >= self.failure_threshold:
self.opened_at = time.monotonic()It has two weaknesses.
- No real half-open state. When the cool-down ends,
allow()returnsTruefor every caller. If 200 requests are waiting, all 200 hit the provider at the same moment. That is the load spike the breaker was meant to prevent. - No explicit state. You cannot log or report a transition, because the state is only implied by
opened_at.
A breaker with a single probe
The version below adds an explicit state and allows one probe at a time. It also takes an injectable clock, which lets you test it without sleeping.
import time
from enum import Enum
class State(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class TransientError(Exception):
"""A failure that suggests the service is unhealthy (timeout, 5xx)."""
class CircuitBreaker:
def __init__(self, failure_threshold=5, reset_after=30.0, clock=time.monotonic):
self.failure_threshold = failure_threshold
self.reset_after = reset_after
self.clock = clock
self.state = State.CLOSED
self.failures = 0
self.opened_at = 0.0
self.probe_in_flight = False
def allow(self) -> bool:
if self.state is State.CLOSED:
return True
if self.state is State.OPEN:
if self.clock() - self.opened_at < self.reset_after:
return False
self.state = State.HALF_OPEN
self.probe_in_flight = False
# Half-open: admit exactly one probe at a time.
if self.probe_in_flight:
return False
self.probe_in_flight = True
return True
def record_success(self) -> None:
self.state = State.CLOSED
self.failures = 0
self.probe_in_flight = False
def record_failure(self) -> None:
self.failures += 1
self.probe_in_flight = False
if self.state is State.HALF_OPEN or self.failures >= self.failure_threshold:
self.state = State.OPEN
self.opened_at = self.clock()
def guarded_call(breaker, fn, fallback):
"""Run fn through the breaker. Use fallback when the circuit is open or fn fails."""
if not breaker.allow():
return fallback()
try:
result = fn()
except TransientError:
breaker.record_failure()
return fallback()
except Exception:
# A permanent error such as a 400 means the service answered.
# Count it as healthy so a half-open probe is never left hanging.
breaker.record_success()
raise
breaker.record_success()
return result
now = [0.0]
breaker = CircuitBreaker(failure_threshold=3, reset_after=10.0, clock=lambda: now[0])
def call_llm(healthy):
if not healthy:
raise TransientError("503 from provider")
return "ok"
for t in (0, 1, 2, 3, 4, 12, 13):
now[0] = t
healthy = t >= 12
result = guarded_call(breaker, lambda: call_llm(healthy), lambda: "fallback")
print(t, result, breaker.state.value)Running it prints:
0 fallback closed
1 fallback closed
2 fallback open
3 fallback open
4 fallback open
12 ok closed
13 ok closedThe third failure at t=2 opens the circuit. At t=3 and t=4 the provider is never contacted. At t=12 the cool-down has passed, one probe goes out, and its success closes the circuit.
The class has no lock because an asyncio program runs on one thread, and allow() contains no await. If you share a breaker across threads, protect the state changes with a threading.Lock.
What counts as a failure
The breaker should measure provider health, not request quality. Counting the wrong errors either trips it by mistake or keeps it from ever tripping.
| Error | Count toward opening? | Reason |
|---|---|---|
| Connection error, DNS failure | Yes | The provider is unreachable. |
| Timeout | Yes | The provider is too slow to use. |
| 500, 502, 503, 504 | Yes | Server-side fault. |
| 429 | Usually no | This signals your quota or burst, not an outage. Use backoff and client-side throttling. |
| 400, 401, 404 | No | These are your request or credentials. The service is healthy. |
| Content-policy refusal | No | The service worked as designed. |
A 429 is the most debated entry. If your own traffic caused it, opening the breaker hides a throttling bug. If the provider is shedding load for everyone and 429 responses persist after you have backed off, you may choose to count them. Make that choice deliberately.
Where the breaker sits relative to retries
Check the breaker before every attempt, not once per logical request. If the circuit opens halfway through a retry loop, the loop should stop at once instead of using its remaining attempts. Record each attempt's outcome, not just the final one. Otherwise a request that failed twice and then succeeded looks like a clean success and hides the trouble.
def call_with_retries_and_breaker(breaker, attempt_fn, max_attempts=3):
for attempt in range(1, max_attempts + 1):
if not breaker.allow():
raise RuntimeError("circuit open")
try:
result = attempt_fn()
except TransientError:
breaker.record_failure()
if attempt == max_attempts:
raise
continue # sleep with backoff and jitter here
breaker.record_success()
return resultChoosing scope and settings
- One breaker per dependency. Key breakers by provider and model, and by region if you use several. A single global breaker lets a problem with one model block healthy ones.
- One breaker per process. Each worker keeps its own state. That is simple and adequate for most services. Sharing state across processes (for example in Redis) adds a dependency and its own failure modes.
- Threshold. Consecutive failures are easy to reason about. At high traffic, a failure rate over a sliding window (for example, 50% of the last 20 calls) copes better with a mix of successes and failures.
- Cool-down. Short values re-probe often and recover fast. Long values protect a struggling provider longer. Thirty seconds is a common starting point. Some designs lengthen it after each failed probe.
- Streaming. Count a stream that fails mid-response as a failure, the same as a failed request.
What to do when the circuit is open
An open circuit only helps if the caller has somewhere to go. Typical options are a cheaper or alternate model, a cached answer, a shorter degraded response, or a clear "temporarily unavailable" message. The next chapter covers these in detail. Pick the fallback in advance. Deciding during an outage is too late.
Log each state transition with the breaker's name and the last error. Also count rejected calls separately from provider errors. A dashboard that shows "calls rejected: 4,000" tells you the breaker is working, while a count of provider errors alone would suggest traffic had stopped.
Exercise
A breaker with failurethreshold=5 and resetafter=30 opens at time 100. At time 131, ten requests arrive at once. Using the single-probe version, how many reach the provider, and what happens to the other nine?
Show answer
One request reaches the provider. At time 131 the cool-down (30 seconds) has passed, so the first call moves the breaker to half-open and becomes the probe. The other nine see probeinflight set and are rejected immediately, so they go to the fallback. If the probe succeeds the breaker closes, and if it fails the breaker reopens for another 30 seconds.
Exercise
Your service gets a 401 response because an API key expired. Should this failure count toward opening the breaker? What happens if the call was a half-open probe and you ignore the result?
Show answer
No. A 401 is a permanent client error, and it shows the provider is reachable, so counting it would open the circuit without any outage. If the call was the half-open probe and you neither record success nor failure, probeinflight stays True and every later call is rejected, which leaves the breaker stuck. Treating the response as a sign of a healthy service, as guarded_call does, releases the probe and lets the error propagate so you can fix the key.