Async Circuit Breaker
Description
When a model backend goes down, hammering it with requests makes recovery slower and ties up your own workers. Wrap backend calls in a circuit breaker that fails fast while the backend is unhealthy and lets a single probe test whether it has recovered.
class CircuitOpenError(Exception): ... # provided
class CircuitBreaker:
def __init__(self, failure_threshold: int, recovery_timeout: float): ...
async def call(self, fn): ...fn is a zero-argument async function. call(fn) either runs it and returns its result (or re-raises its exception), or raises CircuitOpenError without running it.
The breaker has three states.
- CLOSED (initial). Every call runs
fn, concurrently if callers overlap. EachExceptionfromfncounts as a failure. Each success resets the count to 0. Whenfailure_thresholdconsecutive failures are reached, the breaker opens. - OPEN. Calls raise
CircuitOpenErrorimmediately and never runfn. Oncerecovery_timeoutseconds have passed since it opened, the next call moves the breaker to half-open. - HALF_OPEN. Exactly one call (the probe) runs
fn. Every other call raisesCircuitOpenErrorwhile the probe is in flight. If the probe succeeds, the breaker closes with a failure count of 0. If the probe fails or is cancelled, the breaker opens again and the recovery timer restarts.
Two more rules:
- Cancellation (
asyncio.CancelledError) of a CLOSED-state call is not a failure. - A call that started before the most recent transition into OPEN or CLOSED is stale. When it finishes, its result or exception still reaches its caller, but it must not touch the breaker: not the state, not the failure count, and not the recovery timer. For example, a success that started before the breaker opened must not close it or reset the count after a recovery, and a failure that started before a recovery must not reopen it, restart the timer, or interfere with a probe in flight.
__init__ raises ValueError if failure_threshold <= 0 or recovery_timeout <= 0.
Example
breaker = CircuitBreaker(failure_threshold=2, recovery_timeout=0.1)
await breaker.call(failing) # raises RuntimeError, 1 failure
await breaker.call(failing) # raises RuntimeError, breaker opens
await breaker.call(healthy) # raises CircuitOpenError, healthy never runs
await asyncio.sleep(0.15)
await breaker.call(healthy) # probe runs and succeeds, breaker closes
await breaker.call(healthy) # runs normallyConstraints
1 <= failure_threshold <= 100,0 < recovery_timeout <= 60- Use a monotonic clock.
Solution
Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.Reveal solution
Approach
Model the breaker as an explicit state machine with three fields that matter: the state, the consecutive failure count, and when it opened. All transitions go through one _transition helper so that entering OPEN or CLOSED always resets the count, clears the probe flag and stamps the time.
Admission happens before fn runs. OPEN either rejects or, once the timeout has passed, flips to HALF_OPEN. HALF_OPEN admits one call and marks it as the probe. Because asyncio is single-threaded and there is no await between checking _probe_in_flight and setting it, no lock is needed.
The hard part is concurrency across transitions. Calls in CLOSED run concurrently, so a slow call can finish after the breaker has opened and recovered. Give the breaker a generation counter that increments on every transition. Each call records the generation it was admitted in and only touches the state if that generation is still current. Old successes cannot close an open circuit, and old failures cannot reopen a recovered one.
Handle CancelledError separately from Exception. In CLOSED it is the caller giving up, not the backend failing, so it does not count. A cancelled probe, though, must reopen the circuit. Otherwise the probe flag stays set and the breaker is stuck half-open forever.
Complexity
O(1) time and space per call.
Pitfalls
- Forgetting to clear the probe flag after a successful probe. The next recovery attempt finds it set and the breaker never closes again.
- Catching
BaseExceptionand counting cancellation as a failure. A burst of client timeouts then opens the circuit on a healthy backend. - Not handling a cancelled probe at all. The breaker sits in HALF_OPEN with the flag set and rejects everything.
- Letting stale calls update state, so one slow success from before the outage closes the breaker.
- Starting a background timer task to move OPEN to HALF_OPEN. Checking the clock lazily on the next call is simpler and cannot leak tasks.
- Using
time.time(). A wall-clock jump can open or close the circuit early. - Guarding only state transitions against stale calls but still letting a stale success reset the failure count, or a stale failure restart the recovery timer. A stale call must not touch any breaker field.
Follow-ups interviewers ask
- Open on failure rate over a sliding window instead of consecutive failures, with a minimum request count.
- Treat some exceptions (a 400 from bad input) as not the backend's fault.
- Allow N probes in half-open and close only after M of them succeed.
- Export state transitions as metrics and add a per-call timeout so a hanging backend counts as a failure.
Reference solution
import asyncio
import time
class CircuitOpenError(Exception):
pass
class CircuitBreaker:
def __init__(self, failure_threshold: int, recovery_timeout: float):
if failure_threshold <= 0 or recovery_timeout <= 0:
raise ValueError("failure_threshold and recovery_timeout must be positive")
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self._state = "CLOSED"
self._failures = 0
self._opened_at = 0.0
self._probe_in_flight = False
# Bumped on every transition into OPEN or CLOSED. A call only updates
# state if the generation it started in is still current.
self._generation = 0
def _transition(self, state: str) -> None:
self._state = state
self._failures = 0
self._probe_in_flight = False
self._generation += 1
if state == "OPEN":
self._opened_at = time.monotonic()
def _admit(self) -> bool:
"""Return whether this call is the half-open probe, or raise if it may not run."""
if self._state == "OPEN":
if time.monotonic() - self._opened_at < self.recovery_timeout:
raise CircuitOpenError("circuit is open")
self._state = "HALF_OPEN"
if self._state == "HALF_OPEN":
if self._probe_in_flight:
raise CircuitOpenError("recovery probe in flight")
self._probe_in_flight = True
return True
return False
async def call(self, fn):
is_probe = self._admit()
generation = self._generation
try:
result = await fn()
except Exception:
if generation == self._generation:
self._failures += 1
if is_probe or self._failures >= self.failure_threshold:
self._transition("OPEN")
raise
except asyncio.CancelledError:
if is_probe and generation == self._generation:
self._transition("OPEN")
raise
if generation == self._generation:
if is_probe:
self._transition("CLOSED")
else:
self._failures = 0
return resultNotes
import asyncio
import time
class CircuitOpenError(Exception):
pass
class CircuitBreaker:
def __init__(self, failure_threshold: int, recovery_timeout: float):
"""States: CLOSED -> OPEN -> HALF_OPEN -> CLOSED or OPEN. ValueError on bad args."""
raise NotImplementedError
async def call(self, fn):
"""Run fn() or raise CircuitOpenError without running it."""
raise NotImplementedErrorRun checks the 2 example tests. Submit runs all 15 and marks the problem solved when they pass.