Skip to content

Timeouts, retries and circuit breakers

Phase 6 · Distributed systems · 15 min read

What you'll be able to do

  • Set a call timeout and retry policy that fits an end-to-end deadline.
  • Predict when retries make a dependency outage worse, including their multiplied load.
  • Use circuit breakers, bulkheads, and fallbacks to keep one slow dependency from taking down a service.

A remote call has three possible outcomes

A remote call can succeed, fail, or hang from the caller's point of view. The server may finish a write after the reply is lost. A slow server and a dead server look alike until you impose a time limit; even then, a timeout tells you only that you stopped waiting, not whether the server did the work. This is partial failure: one part of a distributed system fails while others keep running.

Imagine 100 request-handling threads, each waiting on a remote service that never responds. Without timeouts, eventually all 100 can be occupied. New requests queue even though your own process is healthy. Connection pools can fill the same way. This is why every remote call needs a finite timeout, including calls made by libraries inside your code.

Give every call a budget

There are three useful limits. A connect timeout bounds establishing a connection. A read timeout bounds waiting for data after connecting; in many clients it measures inactivity between reads, so a stream that keeps trickling can outlive it. A total timeout or deadline bounds the whole operation, including retries and backoff. Check your client's exact semantics when configuring it.

Choose a per-attempt timeout from observed latency and the caller's remaining budget. If successful calls take 0.8 seconds at p99, 1 second might be a starting point; measure false timeouts and adjust. Suppose an HTTP request has 2.0 seconds left and needs 0.3 seconds to format its response. Downstream work has at most 1.7 seconds. A 5-second library default cannot fit.

Pass the caller's deadline downstream, so each layer works with the time remaining rather than starting a fresh full timeout. Within one process, carry a deadline measured by that process's monotonic clock:

def remaining(deadline, now):
    return max(0.0, deadline - now())

Across service boundaries, propagate a remaining timeout or a wall-clock deadline, with an allowance for transit and clock skew; the receiver converts it to a local monotonic deadline. Never compare raw monotonic timestamps from different machines, because their clocks share no starting point.

When the deadline expires, cancel downstream work if the transport supports cancellation, and stop starting new attempts. Cancellation saves resources but cannot undo a side effect that already happened. If a synchronous call cannot be interrupted, its own timeout must also fit within the remaining budget.

Retry only when another attempt is safe

Transient timeouts, connection resets, overload responses such as HTTP 429, and temporary unavailability such as 503 may be retryable. A validation error such as HTTP 400 normally is not: sending the same invalid input again changes nothing. A timeout after a write is ambiguous. Retry a read or another idempotent operation; for a write that could happen twice, use an idempotency key and server-side deduplication. See delivery and idempotency.

Bound retries by maximum attempts and the total deadline. “Three attempts” means the initial call plus two retries. Choose one layer to own retries, usually the layer that knows whether the operation is safe.

An exponential schedule doubles the maximum delay after each failure: with a 0.2-second base and 1-second cap, the first three ceilings are 0.2, 0.4, and 0.8 seconds. Full jitter draws each delay uniformly from zero to that ceiling. Thus the second retry waits somewhere in [0, 0.4] seconds rather than exactly 0.4. Jitter spreads clients that failed together over time. Recheck the deadline before sleeping: a 0.8-second delay is pointless when only 0.3 seconds remain.

import random

def full_jitter(base, cap, retry_number, rng):
    ceiling = min(cap, base * pow(2, retry_number - 1))
    return rng.random() * ceiling

print(full_jitter(0.2, 1.0, 2, random.Random(7)))

Retries also need a budget across traffic, such as allowing at most 10 retry attempts per 100 original requests in a time window. When that budget is empty, fail rather than adding load. If three layers each make three attempts, one top-level request can produce 3 × 3 × 3 = 27 calls at the bottom. If each layer instead makes three retries after its initial call, the count is 4 × 4 × 4 = 64. During an outage, this amplification becomes a retry storm.

Stop calling a failing dependency

A circuit breaker sits around a dependency call. In closed state, it passes calls and measures failures. Once a configured failure rate or slow-call threshold is exceeded over a useful sample, it moves open and fails new calls immediately. After a cooldown it becomes half-open, allowing a limited probe. A successful probe can close it; a failed probe reopens it. A call admitted before the circuit opened may finish later; its stale result must not close or reopen the circuit. The application can return a fallback while the circuit is open.

Place a breaker at the boundary for the dependency it protects, such as an agent tool. Tune the sample size, threshold, and cooldown: too high never trips; too low can flap. Count slow calls when they consume scarce resources. Avoid sending a burst of probes when recovery begins.

Keep capacity separate and degrade deliberately

A bulkhead assigns separate concurrency or connection limits to dependencies. A nonblocking 10-slot limit allows at most 10 simultaneous search calls. Reject excess calls promptly, or use a small bounded queue that does not tie up request workers, and release database connections before waiting on search. A limit whose callers block while waiting for a slot can still consume all 100 request threads. Load shedding similarly rejects excess traffic before it consumes the last resources.

A fallback might serve cached data, use a cheaper model, omit a recommendation panel, or return a clear error. It must have bounded work and be tested; calling the same broken dependency merely moves the failure. Trigger it only for errors that mean the dependency is unavailable, such as a timeout, a connection failure, or an open circuit. A bug such as an invalid argument should surface, not turn into a degraded success. A hedged request sends a second copy to another replica after the first is unusually slow, then uses the first good answer and cancels the other. It can reduce tail latency but spends extra capacity and requires safe duplicate execution. Do not hedge into an overloaded service.

Trace and test the failure chain

Follow one incident: a dependency slows; waiting requests fill threads and connections; upstream callers time out; they retry; the extra load slows the dependency further; the service collapses. Timeouts and cancellation release waiters, a deadline caps wasted time, a retry budget limits extra load, a breaker fails fast, a bulkhead protects unrelated work, and a fallback keeps a reduced service available.

Test this before an outage. Inject a timeout, reset, 429, slow response, and recovery into a fake dependency. Assert attempts, budget, breaker state, and fallback result. Then run controlled fault injection or chaos testing in a realistic environment, watching latency, retry volume, saturation, and errors.

For AI engineers

For AI engineers

Your training script or agent may call an LLM API and wait through a long generation. Give that call a read timeout long enough for expected progress but still an overall deadline. With streaming, distinguish time to first token from the gap between tokens: receiving one token should not renew the entire request budget. If a generation times out after the provider processed it, a retry may duplicate token cost and side effects. Retry only safe calls or calls protected by an idempotency key where supported.

Treat 429 as a signal to slow down, respecting any server-provided wait time that fits your deadline; a temporary 5xx may merit a bounded retry. A provider outage might trigger a fallback model or provider, cached answer, or clear error. Put a circuit breaker around a flaky tool in an agent so one tool cannot consume every worker. Track attempts and token spend per user request so retries do not silently multiply cost.

Common mistakes

  • No timeout: hung calls occupy threads or connections until the service cannot accept more work.
  • Infinite or immediate retries: attempts ignore the caller's deadline and increase load during overload.
  • Identical backoff across clients: everyone retries together; add jitter and a shared retry budget.
  • Retrying in every layer: attempt counts multiply; assign ownership to one layer.
  • Retrying ambiguous writes: a timeout does not prove the write failed; use idempotency protection.
  • Untested breakers and fallbacks: a breaker may never open or may flap, while the fallback fails when needed.

Check yourself

A request has 0.4 seconds left. Its next backoff is 0.6 seconds. Should it retry?

No. Sleeping would cross the total deadline before the next attempt starts. Return the last failure or a bounded fallback.

Three services in a call chain each make an initial call and two retries. How many bottom-layer calls can one user request cause?

Three attempts at each of three layers yield 3 × 3 × 3 = 27 bottom-layer calls. Make one layer own retries to avoid this amplification.

A write times out, but the server might have committed it. What makes retrying safe?

An idempotent operation or an idempotency key checked by the server. The timeout alone gives no proof that the first write failed.

A search dependency is slow while database requests are healthy. What keeps search from occupying every worker, and what can users see?

A separate concurrency limit, or bulkhead, rejects excess search work quickly. A tested fallback can omit search results or serve recent cached results while other requests continue.

Lab

Build a deterministic resilience toolkit in code/timeouts-retries/. Implement capped backoff with injected randomness and a retry loop with an injected clock. Add a circuit breaker with a cooldown and half-open probe. Limit concurrency with a bulkhead, then route recoverable primary failures to a fallback. Calculate how attempts multiply across layers. Run: cd code/timeouts-retries && PYTHONPATH=starter python -m pytest tests -q

Go deeper