Sub topic 13
Stopping calls during sustained outages with a circuit breaker
This chapter assumes you can write Python classes and already know how retries with backoff work. Retries handle short failures. They do not help when a provider is down for minutes. Each request still waits through its timeouts and retries, and your application keeps adding load to a service that is already struggling. A circuit breaker fixes this by failing fast.
The working model
A circuit breaker sits between your code and the API. It counts consecutive failures. When the count reaches a threshold, the breaker opens. While it is open, calls are rejected immediately and no request is sent. After a cool-down period, the breaker lets a call through to probe the service. If that call succeeds, the breaker closes again.
- Closed: requests flow normally and failures are counted.
- Open: requests are refused without touching the network.
- Half-open: the cool-down has passed and a trial request is allowed.
A minimal implementation
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()The code has no explicit half-open state. Once reset_after seconds pass, allow() returns True. A success resets everything. A failure calls record_failure(). The count is still at or above the threshold, so opened_at is set again and the cool-down restarts.
Using it with your API call
Check the breaker before each call and report the outcome afterward. Wrap the whole retried call as one unit, so one exhausted retry sequence counts as one failure.
class CircuitOpenError(Exception):
pass
def call_llm(breaker, send):
if not breaker.allow():
raise CircuitOpenError("LLM API circuit is open")
try:
result = send()
except Exception:
breaker.record_failure()
raise
breaker.record_success()
return resultCallers can catch CircuitOpenError and switch to a fallback, such as a cached answer or a smaller model. The fallback chapter covers that step.
Common errors
- Counting permanent errors. A 400 or 401 means your request is wrong, not that the service is down. Record only retryable failures, such as timeouts, 5xx responses, and exhausted retries.
- Tripping on 429. A rate limit means you are sending too fast, not that the provider is unhealthy. Handle it with throttling and
Retry-After, and consider leaving it out of the breaker count. - Counting each retry. If every attempt inside a retry loop calls
record_failure(), one bad request can open the breaker. Count the final outcome. - One breaker for everything. Use a separate breaker for each provider or model. An outage in one should not block the others.
- Shared state. This class is not thread-safe, and each process has its own copy. Add a lock for threaded code, and accept that separate workers will trip independently unless you share state.
Exercise
A breaker has failurethreshold=3 and resetafter=10. Three requests fail, opening the breaker at time 0. A request arrives at time 4 and another at time 12, which fails. What happens to each request, and when can the next probe be sent?
Show answer
The request at time 4 is rejected without a network call because the cool-down has not passed. The request at time 12 is allowed as a probe. It fails, so recordfailure() sets openedat to 12 again. The next probe can be sent at time 22.
Exercise
Why should a 401 response not count toward opening the circuit breaker?
Show answer
A 401 means the credentials are invalid. The service is working, and retrying will not help. Opening the breaker would block calls and hide the real problem, which is a configuration error you should fix and report immediately.