Circuit Breaker in Python with asyncio

Build an asyncio circuit breaker in Python: closed, open and half-open states, one recovery probe, stale-call protection and tests.

Guide ยท 9 min read

A circuit breaker wraps calls to a dependency and stops making them once the dependency looks unhealthy. It has three states. Closed passes every call through and counts failures. Open fails every call immediately, without touching the dependency, for a cool-down period. Half-open lets one trial call through, and closes the breaker if it succeeds or opens it again if it fails. Failing fast protects your own service from piling up slow, doomed requests, and gives the dependency room to recover. In Python with asyncio a breaker is about 50 lines: an enum for the state, a failure counter, a monotonic timestamp for when it opened, and a flag for the one probe in flight.

This guide builds that breaker, tests it with a fake clock, then fixes the concurrency bug most first versions have. It ends with the follow-ups interviewers ask and how a breaker fits with retries. Every snippet is complete and runs on Python 3.12 or newer.

The state machine

From Event To
Closed A call succeeds Closed, failure count reset to 0
Closed Failure count reaches the threshold Open, timer starts
Open A call arrives before the cool-down ends Open, call rejected with no attempt
Open A call arrives after the cool-down Half-open, this call becomes the probe
Half-open Another call arrives while the probe runs Half-open, call rejected
Half-open The probe succeeds Closed, failure count 0
Half-open The probe fails Open, timer restarts

Two design decisions come out of the table. The move from open to half-open happens lazily, on the next call after the cool-down, so there is no background timer. And half-open admits exactly one call. Letting every waiting request through the moment the timer expires would send a burst at a service that may still be down.

A first breaker

The clock is a parameter so the tests can move time forward without sleeping.

import asyncio
import time
from enum import Enum


class State(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


class CircuitOpenError(Exception):
    pass


class CircuitBreaker:
    def __init__(self, threshold: int, cooldown: float, clock=time.monotonic) -> None:
        self.threshold = threshold
        self.cooldown = cooldown
        self.clock = clock
        self.state = State.CLOSED
        self.failures = 0
        self.opened_at = 0.0
        self.probing = False

    def _admit(self) -> bool:
        if self.state is State.OPEN:
            if self.clock() - self.opened_at < self.cooldown:
                raise CircuitOpenError("circuit open")
            self.state = State.HALF_OPEN
        if self.state is State.HALF_OPEN:
            if self.probing:
                raise CircuitOpenError("probe in flight")
            self.probing = True
            return True
        return False

    def _open(self) -> None:
        self.state, self.failures, self.probing = State.OPEN, 0, False
        self.opened_at = self.clock()

    def _close(self) -> None:
        self.state, self.failures, self.probing = State.CLOSED, 0, False

    async def call(self, fn):
        is_probe = self._admit()
        try:
            result = await fn()
        except asyncio.CancelledError:
            if is_probe:
                self._open()
            raise
        except Exception:
            self.failures += 1
            if is_probe or self.failures >= self.threshold:
                self._open()
            raise
        if is_probe or self.state is State.CLOSED:
            self._close()
        return result


class FakeClock:
    def __init__(self) -> None:
        self.now = 0.0

    def __call__(self) -> float:
        return self.now


async def healthy() -> str:
    return "ok"


async def failing() -> str:
    raise ConnectionError("backend down")


async def main() -> None:
    clock = FakeClock()
    breaker = CircuitBreaker(threshold=3, cooldown=30, clock=clock)
    log = []
    for fn in (failing, failing, failing, healthy):
        try:
            await breaker.call(fn)
            log.append("ok")
        except Exception as exc:
            log.append(type(exc).__name__)
    print(log, breaker.state.value)
    clock.now = 31
    print(await breaker.call(healthy), breaker.state.value)


asyncio.run(main())
# ['ConnectionError', 'ConnectionError', 'ConnectionError', 'CircuitOpenError'] open
# ok closed

Three failures open the circuit, and the fourth call is rejected without running healthy. After the cool-down, the next call is the probe, it succeeds, and the breaker closes.

_admit checks and sets self.probing with no await in between. In asyncio, code between two awaits runs without interruption, so two callers can't both become the probe and no lock is needed. In a threaded version that check-and-set needs a threading.Lock.

CancelledError is handled on its own. A caller that gives up, perhaps because its own timeout fired, says nothing about the backend's health, so it does not count as a failure. A cancelled probe is different. If it left probing set, the breaker would be stuck half-open forever and reject everything, so it reopens instead.

The bug: stale calls

In the closed state calls run concurrently. A slow call that started before the breaker opened can finish long after, and the first version lets it change state it knows nothing about.

import asyncio
import time
from enum import Enum


class State(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


class CircuitOpenError(Exception):
    pass


class NaiveBreaker:
    def __init__(self, threshold: int, cooldown: float) -> None:
        self.threshold, self.cooldown = threshold, cooldown
        self.state, self.failures, self.opened_at, self.probing = State.CLOSED, 0, 0.0, False

    async def call(self, fn):
        if self.state is State.OPEN:
            if time.monotonic() - self.opened_at < self.cooldown:
                raise CircuitOpenError
            self.state = State.HALF_OPEN
        is_probe = self.state is State.HALF_OPEN
        if is_probe:
            if self.probing:
                raise CircuitOpenError
            self.probing = True
        try:
            result = await fn()
        except Exception:
            self.failures += 1
            if is_probe or self.failures >= self.threshold:
                self.state, self.failures, self.probing = State.OPEN, 0, False
                self.opened_at = time.monotonic()
            raise
        self.state, self.failures, self.probing = State.CLOSED, 0, False
        return result


async def slow_ok() -> str:
    await asyncio.sleep(0.05)
    return "late success"


async def failing() -> str:
    raise ConnectionError


async def main() -> None:
    breaker = NaiveBreaker(threshold=2, cooldown=10)
    slow = asyncio.create_task(breaker.call(slow_ok))
    await asyncio.sleep(0)
    for _ in range(2):
        try:
            await breaker.call(failing)
        except ConnectionError:
            pass
    print("after failures:", breaker.state.value)
    await slow
    print("after the slow call returns:", breaker.state.value)


asyncio.run(main())
# after failures: open
# after the slow call returns: closed

The breaker opened because the backend was failing, then a request admitted before the outage returned and closed it 50 ms later, well before the 10-second cool-down. The mirror case is a stale failure arriving after recovery and reopening a healthy circuit, or restarting the recovery timer while a probe is in flight.

The fix is a generation counter. Increment it on every move into open or closed, record it when a call is admitted, and let a call touch the breaker only if the generation is still the one it was admitted in. The caller still gets its result or its exception. Only the bookkeeping is skipped.

import asyncio
import time
from enum import Enum


class State(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


class CircuitOpenError(Exception):
    pass


class CircuitBreaker:
    def __init__(self, threshold: int, cooldown: float, clock=time.monotonic) -> None:
        self.threshold, self.cooldown, self.clock = threshold, cooldown, clock
        self.state, self.failures, self.opened_at = State.CLOSED, 0, 0.0
        self.probing = False
        self.generation = 0

    def _move(self, state: State) -> None:
        self.state, self.failures, self.probing = state, 0, False
        self.generation += 1
        if state is State.OPEN:
            self.opened_at = self.clock()

    def _admit(self) -> bool:
        if self.state is State.OPEN:
            if self.clock() - self.opened_at < self.cooldown:
                raise CircuitOpenError("circuit open")
            self.state = State.HALF_OPEN
        if self.state is State.HALF_OPEN:
            if self.probing:
                raise CircuitOpenError("probe in flight")
            self.probing = True
            return True
        return False

    async def call(self, fn):
        is_probe = self._admit()
        generation = self.generation
        try:
            result = await fn()
        except asyncio.CancelledError:
            if is_probe and generation == self.generation:
                self._move(State.OPEN)
            raise
        except Exception:
            if generation == self.generation:
                self.failures += 1
                if is_probe or self.failures >= self.threshold:
                    self._move(State.OPEN)
            raise
        if generation == self.generation:
            if is_probe:
                self._move(State.CLOSED)
            else:
                self.failures = 0
        return result


async def slow_ok() -> str:
    await asyncio.sleep(0.05)
    return "late success"


async def failing() -> str:
    raise ConnectionError


async def main() -> None:
    breaker = CircuitBreaker(threshold=2, cooldown=10)
    slow = asyncio.create_task(breaker.call(slow_ok))
    await asyncio.sleep(0)
    for _ in range(2):
        try:
            await breaker.call(failing)
        except ConnectionError:
            pass
    print(await slow, "->", breaker.state.value)


asyncio.run(main())
# late success -> open

The move from open to half-open does not bump the generation. Calls admitted while closed already carry an older number, and calls arriving while open are rejected, so the probe is the only call that can carry the current generation in half-open.

Opening on a failure rate

Consecutive failures are easy to reason about, but one success in a stream of errors resets the count. Production breakers usually open on a failure rate over the last N calls, with a minimum number of calls so that two failures out of two don't open the circuit at startup.

from collections import deque


class FailureRate:
    def __init__(self, window: int, min_calls: int, max_rate: float) -> None:
        self.outcomes: deque[bool] = deque(maxlen=window)
        self.failures = 0
        self.min_calls, self.max_rate = min_calls, max_rate

    def record(self, ok: bool) -> bool:
        if len(self.outcomes) == self.outcomes.maxlen:
            self.failures -= not self.outcomes[0]
        self.outcomes.append(ok)
        self.failures += not ok
        n = len(self.outcomes)
        return n >= self.min_calls and self.failures / n >= self.max_rate


rate = FailureRate(window=10, min_calls=5, max_rate=0.5)
pattern = [True, False, True, False, False, True, False, False]
print([rate.record(ok) for ok in pattern])
# [False, False, False, False, True, True, True, True]

deque(maxlen=10) drops the oldest outcome on append, and the running failures count keeps each record O(1). Swap this in for the consecutive counter and call _move(State.OPEN) when record returns True. A time-based window, failures in the last 60 seconds, works the same way with timestamps in the deque.

Circuit breakers and retries

Put the retry outside the breaker and never retry CircuitOpenError. The breaker's job is to stop calls to a dead dependency. A retry loop that catches CircuitOpenError and tries again just spins against the open circuit.

import asyncio


class CircuitOpenError(Exception):
    pass


async def retry(fn, attempts: int = 3, base: float = 0.01):
    for attempt in range(attempts):
        try:
            return await fn()
        except CircuitOpenError:
            raise
        except ConnectionError:
            if attempt == attempts - 1:
                raise
            await asyncio.sleep(base * 2**attempt)


calls = 0


async def always_open() -> None:
    global calls
    calls += 1
    raise CircuitOpenError


try:
    asyncio.run(retry(always_open))
except CircuitOpenError:
    print("failed fast after", calls, "call")  # failed fast after 1 call

When the breaker is open, the caller needs a fallback: a cached value, a default, a degraded response, or a clear error such as HTTP 503 with a Retry-After header set to the remaining cool-down. The retry and backoff guide covers jitter and deadlines for the retry side.

Follow-ups interviewers ask

  • Which errors count as failures? Timeouts, connection errors and 5xx responses do. A 400 or 404 is the caller's fault and should not open the circuit. Take a predicate, is_failure(exc) -> bool.
  • Slow calls. A backend that hangs is worse than one that fails. Put a timeout inside the breaker so a hang counts as a failure, or open on the share of calls slower than a threshold.
  • Several probes. Allow N trial calls in half-open and close only after M of them succeed, which avoids closing on one lucky request.
  • One breaker per what? Per dependency, and often per host or per endpoint. One global breaker lets a single bad endpoint block the healthy ones.
  • Several processes. Each process normally keeps its own breaker, which is simple and good enough. Sharing state through Redis makes every call pay a network round trip to decide whether to make a network call.
  • Observability. Emit a metric or log line on each state change. An open circuit nobody notices is an outage nobody is fixing.

Common mistakes

  • Letting every caller through in half-open. The recovering service gets the full load at once.
  • Counting CancelledError as a failure. Client timeouts then open the circuit on a healthy backend.
  • Forgetting to clear the probe flag, or not handling a cancelled probe. The breaker gets stuck half-open.
  • Letting stale calls update state. One slow success from before the outage closes the circuit.
  • A background timer task for the cool-down. Checking the clock on the next call is simpler and cannot leak tasks.
  • Using time.time(). Wall-clock jumps open or close the circuit early.

Practise it

The Async Circuit Breaker problem asks for exactly this breaker, including the single probe, cancellation rules and stale in-flight calls, and its hidden tests run concurrent calls across every transition. It is one of the harder problems on the site, so give it 40 minutes.

  1. 16Async Circuit Breakerhard

    Implement an asyncio circuit breaker with closed, open and half-open states, a single recovery probe, and protection against stale in-flight calls.

  2. 22Async Retry with Exponential Backoffmedium

    Retry a failing coroutine with capped exponential backoff, re-raise the last error, and never swallow cancellation.

The circuit breaker and concurrency topic pages collect related problems. The asyncio interview guide explains why code between two awaits needs no lock, which this breaker relies on.

Frequently asked questions

What is the circuit breaker pattern?

A wrapper around calls to a dependency that stops making them once the dependency looks unhealthy. Closed passes calls through and counts failures, open rejects calls immediately for a cool-down period, and half-open lets one trial call decide whether to close again or reopen.

What happens in the half-open state?

One probe call is allowed through while every other call is rejected. If the probe succeeds the breaker closes and the failure count resets. If it fails, or is cancelled, the breaker opens again and the cool-down restarts.

What is the difference between a circuit breaker and a retry?

A retry repeats one call in the hope that a transient error goes away. A circuit breaker watches many calls and stops sending any of them when a dependency is failing. Use both, with the retry outside the breaker, and never retry the breaker's open error.

Does an asyncio circuit breaker need a lock?

Not if every check and update of the breaker's state happens without an await in between, because asyncio only switches tasks at an await. A breaker used from several threads does need a threading.Lock around those sections.

Should a cancelled call count as a failure?

No for ordinary calls, because the caller gave up and the backend may be fine. A cancelled probe is the exception: the breaker must reopen or release the probe slot, otherwise it stays half-open and rejects everything.

Is there a Python circuit breaker library?

Yes, for example pybreaker for synchronous code and aiobreaker or purgatory for asyncio. In an interview you write the state machine yourself, and knowing the three states, the single probe and the failure predicate covers what the libraries do.