Retry, Backoff, and Circuit Breakers in Python
Distributed code fails in ways local code never does: the request timed out but the server actually completed it, the database is briefly unavailable, a rate limit returns a status that is technically an error but means "wait". Handled naively, these produce either a cascade of immediate retries that makes the outage worse, or a thread pool parked on dead connections while the rest of the service starves.
Three tools address the problem at different layers. An exception hierarchy makes failures classifiable at the boundary where you decide what to do. A retry policy with backoff and jitter gives a transient failure a bounded number of chances without amplifying load. A circuit breaker stops calling a dependency that is already known to be failing, so failures cost microseconds instead of full timeouts.
What You'll Learn
- 1Design exception types that carry machine-readable context
- 2Write a retry decorator that is idempotency-aware and jittered
- 3Implement the three-state circuit breaker with correct transitions
- 4Set the boundary rules for where exceptions should be caught or re-raised
Hierarchy first: make failures classifiable
A single except Exception at the top of a service turns every failure into the same undifferentiated blob. A hierarchy restores classification: callers can catch TransientError and retry, catch FatalError and abort, and let everything else propagate to the boundary where it becomes a log entry and a status code.
The design rule is that the type answers "what should happen next", while the payload answers "what exactly happened". Carrying a field name, an HTTP status, or a resource identifier on the exception object means the logging layer can produce a useful line without re-parsing a message string.
class AppError(Exception):
"""Base for every failure this application classifies."""
code = "app_error"
retryable = False
def __init__(self, message, **context):
super().__init__(message)
self.context = context
class TransientError(AppError):
code = "transient"
retryable = True
class DependencyTimeout(TransientError):
code = "dependency_timeout"
class RateLimited(TransientError):
code = "rate_limited"
def __init__(self, retry_after, **context):
super().__init__("rate limited", **context)
self.retry_after = retry_after
class ValidationError(AppError):
code = "validation"
def __init__(self, field, message):
super().__init__(f"{field}: {message}")
self.field = field
class NotFoundError(AppError):
code = "not_found"
def __init__(self, resource, identifier):
super().__init__(f"{resource} {identifier} not found")
self.resource = resource
self.identifier = identifier
def classify(exc):
if isinstance(exc, AppError):
return exc.retryable, exc.code
if isinstance(exc, (TimeoutError, ConnectionError)):
return True, "network"
if isinstance(exc, ValueError):
return False, "bad_input"
return False, "unknown"
Note the final fallback: unknown exceptions are treated as non-retryable. Retrying a programming error such as a KeyError wastes time and hides the bug behind a longer stack trace.
Retries with backoff and jitter
A retry policy has four knobs: how many attempts, how long to wait between them, which failures qualify, and whether the operation can safely be repeated. Exponential backoff grows the delay so a recovering dependency is not hammered, while jitter randomizes it so that a thousand clients do not all return at the same instant and recreate the original spike.
import random
import time
from functools import wraps
def retry(
attempts=4,
base=0.25,
cap=8.0,
retry_on=(TransientError, TimeoutError, ConnectionError),
jitter=0.25,
):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
delay = base
last = None
for attempt in range(1, attempts + 1):
try:
return fn(*args, **kwargs)
except retry_on as exc:
last = exc
if isinstance(exc, RateLimited):
delay = max(delay, exc.retry_after)
if attempt == attempts:
break
sleep_for = min(delay, cap)
sleep_for *= 1 + random.uniform(-jitter, jitter)
time.sleep(max(0.0, sleep_for))
delay = min(delay * 2, cap)
raise last
return wrapper
return decorator
@retry(attempts=3, base=0.1)
def fetch_inventory(sku):
raise DependencyTimeout("inventory", sku=sku)
The retryable set must be chosen deliberately. Timeouts and connection resets usually qualify. A 400 from an API does not: the same request will fail identically forever. Most importantly, retries are only safe when the operation is idempotent. Re-sending a payment is not idempotent; re-reading a record is. When an operation is not idempotent, attach an idempotency key so the server can deduplicate rather than trusting the client not to try again.
The circuit breaker as a state machine
Retries still cost time. If a dependency has been failing for the last thirty seconds, every caller will burn its full retry budget before giving up. A circuit breaker removes that cost by failing fast while the dependency is unhealthy, and by probing occasionally to discover when it recovers.
| State | Behaviour on call | Transition out |
|---|---|---|
| Closed | Requests pass through; failures are counted | Failure count reaches the threshold, becomes open |
| Open | Calls raise immediately without touching the network | Recovery timeout elapses, becomes half-open |
| Half-open | A limited number of trial requests pass | Trial succeeds, becomes closed; trial fails, becomes open |
import time
from enum import Enum
class State(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class CircuitBreaker:
def __init__(self, threshold=5, reset_after=30.0, probes=1):
self.threshold = threshold
self.reset_after = reset_after
self.probes = probes
self.state = State.CLOSED
self.failures = 0
self.opened_at = 0.0
self.in_flight_probes = 0
def before_call(self):
if self.state is State.CLOSED:
return
if self.state is State.OPEN:
if time.monotonic() - self.opened_at < self.reset_after:
raise DependencyTimeout("circuit open")
self.state = State.HALF_OPEN
self.in_flight_probes = 0
if self.in_flight_probes >= self.probes:
raise DependencyTimeout("circuit half-open, probe limit reached")
self.in_flight_probes += 1
def on_success(self):
self.failures = 0
self.in_flight_probes = 0
self.state = State.CLOSED
def on_failure(self):
self.failures += 1
self.opened_at = time.monotonic()
self.in_flight_probes = 0
if self.state is State.HALF_OPEN or self.failures >= self.threshold:
self.state = State.OPEN
Two details separate a usable breaker from a demo. First, time.monotonic() rather than wall-clock time, because a system clock adjustment must not extend or shorten the recovery window. Second, a probe budget in the half-open state: without it, a burst of waiting callers all probe at once, overwhelm the recovering dependency, and bounce it straight back to open.
Timeouts first: bounding the call you are about to retry
A retry policy without a timeout cannot bound latency, because the first attempt may never return. Before any backoff logic exists, every outbound call needs an upper bound on how long it may take, and the bound should be smaller than the caller's own deadline so there is room left for the remaining attempts and the backoff sleeps between them. In synchronous code that usually means passing a timeout into the client library; in asynchronous code it means an awaited call wrapped in a timeout, with the timeout treated as a transient failure rather than as a crash.
The relationship between attempt count, per-attempt timeout, and backoff is arithmetic worth writing down. Four attempts with a two-second timeout and a base delay of half a second, doubling and capped at eight, has a worst case that can be computed before deployment. If that worst case exceeds what a user or an upstream gateway will wait, the policy is wrong regardless of how well it performs in a unit test.
Two further details matter in practice. A timeout on connect and a timeout on the whole request are different settings and often want different values, because a server that accepts connections slowly is a different failure from one that accepts them and then hangs. And a timeout does not cancel the work on the server side; it only abandons the wait, which is another reason idempotency keys matter when the request may have completed.
Observability: making every retry and trip visible
A retry policy that runs silently is invisible until it causes an incident, and then it is the first thing people wish they had counted. Every attempt should emit one structured record containing the operation name, the attempt number, the delay before the next try, and the exception type that triggered it. The final failure after the budget is spent should be logged as a distinct event, because that is the line the on-call engineer will search for.
The circuit breaker needs the same treatment. Transitions between states are rare and significant, so each one deserves a log line and a metric, with a counter for calls rejected while open and another for probes that flipped the state back to closed. Without those numbers, a breaker that is tripping every few minutes looks identical to one that has been steady for a week, and the difference is exactly what you need during an investigation.
Correlation identifiers complete the picture. When a request fans out to three dependencies and each one retries twice, the only way to reconstruct what happened is a single identifier carried through every attempt and every log line. Adding it at the boundary where the request enters the process is cheap, and it turns a scattered set of messages into one story.
Boundaries: where to catch, where to re-raise
Layered systems need a consistent rule. Catch at the layer that can actually do something about the failure: the command-line entry point converts exceptions into messages and exit codes, the HTTP layer converts them into status codes, the worker converts them into retry records. Lower layers should raise rich exceptions and let them travel, because swallowing an error where context is lost produces the log lines nobody can act on.
Beware the bare except and the bare raise in the wrong place. A bare except catches SystemExit, KeyboardInterrupt, and GeneratorExit, which breaks cancellation and Ctrl-C. A raise with no active exception inside an except block re-raises correctly, but the same statement outside one is a runtime error. And never use exceptions for ordinary control flow when a return value is clearer; the cost of an exception is real, and tracing tools count them.
Common Mistakes
Retrying every exception until the budget is spent
Fix: Retry only a whitelist of transient failures and treat unknown exceptions as fatal
Retrying a non-idempotent operation
Fix: Attach an idempotency key or make the operation safe to repeat before enabling retries
Exponential backoff without jitter across many clients
Fix: Add random jitter so synchronized callers do not recreate the thundering herd
Using wall-clock time to time the breaker's recovery window
Fix: Use time.monotonic so clock adjustments cannot extend or shorten the open state
Best Practices
- Let exception types carry structure such as field names, statuses, and identifiers
- Cap the backoff delay and the attempt count so a caller's latency budget is respected
- Put the breaker around the dependency, not around your own business logic
- Log each retry once with attempt number and delay, and log the final failure with its cause
- Set timeouts first; a retry without a timeout cannot bound total latency
Interview Questions
Q1: Why is jitter necessary in exponential backoff?
Without it, every client that failed at the same moment retries after the same delay, producing a synchronized spike. Jitter spreads those attempts over a window so the dependency sees a smooth load instead of a wall.
Q2: What problem does a circuit breaker solve that retries do not?
Retries still spend the full timeout and backoff budget on a dead dependency. A breaker fails fast once the failure threshold is crossed, freeing callers and threads while it waits for the recovery window.
Q3: When is retrying a request unsafe?
When the operation is not idempotent, such as charging a card or incrementing a counter, because the first attempt may have succeeded even though the response was lost. An idempotency key lets the server deduplicate the replay.
Key Takeaways
- Classify failures by type so the boundary knows whether to retry, reject, or propagate
- Retry transient errors with exponential backoff, a cap, and jitter, and only when the operation is idempotent
- A three-state breaker fails fast while a dependency is unhealthy and probes carefully during recovery
- Use monotonic time for all interval measurements
- Catch exceptions only where something can be done about them, and never swallow them silently