← All posts
ConceptsNovember 2, 202616 min read

Retries, Timeouts and Circuit Breakers: Stopping Cascading Failure

A dependency that is 25% short of capacity should degrade by 25%. In practice it goes to zero, and the thing that takes it there is almost always the retry logic its callers added to make themselves resilient. This is the single most common way a distributed system turns a partial failure into a total one, and it is the failure mode interviewers probe when they ask what happens when a downstream service gets slow.

This post works through the chain in the order it has to be reasoned about: why the timeout is the first decision and not the last, what makes a retry policy safe rather than amplifying, what a circuit breaker actually buys you (it is not "failing fast"), and why backpressure fixes the problem the other three only contain.

The retry is the outage

Take a service C that can serve 600 requests per second. Normal traffic is 800 rps and it has been fine, because 800 rps was within its old capacity — then a bad deploy, a cold cache, or a slow query plan knocks sustainable throughput down to 600.

The honest outcome is that 200 rps fail. Here is what a conventional three-attempt retry policy in the callers does instead:

  • 600 rps succeed, 200 rps fail or time out.
  • Those 200 are retried. Offered load is now 1,000 rps against 600 rps of capacity, so 400 rps fail.
  • Those 400 are retried. Offered load reaches the policy ceiling: three attempts per request means up to 3 × 800 = 2,400 rps.

A service 25% short of capacity is now receiving four times what it can serve. Queues fill, latency crosses every caller's timeout, and the success rate collapses to roughly zero — not because capacity went to zero, but because nearly everything served is served after the caller gave up. Nor does it stop when the dependency recovers: the system must work through the backlog it created, so the outage outlives its cause.

It gets worse with depth, because retries multiply rather than add.

Client 1 user action Service A 3 attempts Service B 9 arrivals Service C 27 arrivals Each hop retries a failed call up to three times. 3 × 3 × 3 = 27 The deepest service — the one already struggling — absorbs the whole product.
Retries compose multiplicatively down a call stack. Three layers that each look locally reasonable produce 27× amplification at the bottom. This is why a retry policy is a system-level decision, not a per-client one, and why the rule is to retry at exactly one layer.

Two conclusions fall out before any of the mechanisms: retry at one layer only, and cap retries as a share of traffic rather than per request.

Timeouts come first

You cannot reason about retries until you have decided how long a call is allowed to take, because a retry is just what happens after a timeout fires. Timeouts are also where most of the damage is done, and the reason is Little's Law: the concurrency a service carries is its arrival rate multiplied by its latency.

A service handling 500 rps with a 50 ms p99 is holding about 500 × 0.05 = 25 requests in flight. Now a dependency degrades and that call starts taking 10 seconds. If the timeout is generous enough to allow it:

500 × 10 = 5,000 requests in flight

Nothing survives that. A thread-per-request server with a 200-thread pool saturates and its throughput drops to 200 threads ÷ 10 s = 20 rps; an async server fares better on memory but still exhausts its connection pool. The important part is that every endpoint goes down, including the ones that never touch the slow dependency, because they all compete for the same threads and connections.

Picking a number

The common mistake is setting a timeout from the average latency, or from a round number like one second that nobody measured. Pick it from the healthy tail of the latency distribution:

p50p99p99.9TimeoutConcurrency at 500 rps
Measured, healthy8 ms40 ms120 ms—20
Timeout = 1 s1,000 msup to 500
Timeout = 250 ms250 msup to 125

A 1-second timeout on a call whose p99.9 is 120 ms is not a safety net, it is permission to hold a thread eight times longer than the worst healthy case. Set it at roughly 2× p99.9 and you abandon well under 0.1% of healthy calls while capping worst-case concurrency at a quarter of what the loose timeout allows. If losing that tail is unacceptable, that is an argument for making the retry cheap, not for a longer timeout.

Deadlines, not timeouts

Per-hop timeouts have a structural flaw: they do not compose. If each of four hops allows 1 second, a request can legitimately take 4 seconds — and the user's browser gave up at 2.

The fix is to propagate a deadline — an absolute point in time — rather than a duration. The entry point stamps deadline = now + 2s, passes it on every downstream call, and each hop does two things: sets its own timeout to the remaining budget rather than a fixed value, and rejects immediately if the deadline has already passed. gRPC does this natively and it is one of the better reasons to use it; if you are on plain HTTP, a propagated X-Request-Deadline header plus a middleware that checks it costs very little.

Deadline propagation also makes retries honest. A retry that cannot possibly finish before the deadline is pure amplification, so the policy's first check should be "is there time left?" and not "have I used my three attempts?"

Retrying without making it worse

Retries are only safe when three things hold, and all three are easy to get wrong.

The operation tolerates duplicates. A timeout tells the client nothing about whether the write landed, so retrying a non-idempotent write is a coin flip on double-applying it. That is a prerequisite, not a detail — see idempotency keys and safe retries for how to make the second attempt provably free.

The error is actually retryable. Retry connection failures, timeouts, 429, 502, 503, 504. Do not retry 400, 401, 403, 404, 422 — the request will fail identically forever, and retrying it is a pure waste that also consumes budget other calls need. 409 is a judgement call: it usually means the server is telling you to stop.

The retry is spread out in time. This is the part worth drawing.

Jitter is not optional

Imagine a dependency restarts and 1,000 clients fail simultaneously at t = 0. With textbook exponential backoff — 1 s, 2 s, 4 s — all thousand retry at exactly the same instants, because they all failed at the same instant. The dependency, which has just come up with cold caches and empty connection pools, is hit by a 1,000-request wall three times in a row. That is how a recovery becomes a second outage.

Exponential backoff spreads attempts across time for one client. It does nothing to decorrelate clients from each other. Only randomisation does that:

no jitter sleep = 2ⁿ 1s 2s 4s 8s peak ≈ 1,000 requests in one 100 ms bucket full jitter sleep = rand(0, 2ⁿ) peak ≈ 12 requests in the same bucket Same clients, same number of attempts, same backoff ceiling — only the sleep is randomised.
Backoff spreads one client's attempts; jitter spreads the fleet's. Both rows represent the same 1,000 clients making the same three retries. Without jitter the retries arrive as walls, which is precisely when a recovering dependency is least able to absorb them.

The formula to remember is full jitter, from AWS's write-up on the subject: sleep = random(0, min(cap, base × 2^attempt)). Avoid the half-measures that keep a floor under the sleep — a floor keeps the clustering.

The arithmetic: 1,000 clients at attempt 3, spread uniformly over [0, 8s], average 125 rps and roughly 12 per 100 ms bucket — an 80-fold cut in peak load for a one-line change.

Budgets beat attempt counts

Here is the position I would defend in an interview: "maximum 3 attempts" is the wrong shape for a retry policy. It is a per-request limit, and the thing you actually need to bound is fleet-wide amplification. Three attempts means that in the worst case — which is exactly the case you are designing for, because that is when everything fails at once — your dependency gets 3× its normal load.

A retry budget bounds it directly: maintain a token bucket where successes add tokens and retries spend them, sized so retries can never exceed some fraction of successful traffic. At a 10% budget, worst-case offered load is 1.1× normal, not 3×. Return to the opening example: instead of 2,400 rps against 600 rps of capacity, the dependency sees 600 successes plus 60 retries. It stays at capacity, serves 600 rps, and the 200 rps that cannot be served fail quickly and honestly. The system degrades by 25%, which is what should have happened.

Finagle has shipped retry budgets for years and gRPC's retryThrottling is the same token bucket, but hand-rolled clients rarely have one, so naming it is a strong signal.

PolicyWorst-case load on the dependencyBehaviour during a brownout
3 fixed attempts3×Amplifies; turns a shortfall into an outage
3 attempts + jitter3×Same total, spread out; still amplifies
10% retry budget1.1×Degrades proportionally; cannot run away

A policy that fits on one screen

import random, time

RETRYABLE_STATUS = {429, 500, 502, 503, 504}

class RetriesExhausted(Exception):
    pass

class RetryBudget:
    """Token bucket: a retry is allowed only against recent successes."""
    def __init__(self, ratio: float = 0.10, floor: float = 10.0):
        self.ratio, self.floor = ratio, floor
        self.tokens = floor

    def record_completion(self) -> None:          # any terminal response, 2xx or 4xx
        self.tokens = min(self.tokens + self.ratio, self.floor * 10)

    def withdraw(self) -> bool:
        if self.tokens < 1.0:
            return False                          # budget spent: fail now, do not amplify
        self.tokens -= 1.0
        return True

def call(send, budget, deadline, attempts=3, base=0.05, cap=2.0):
    """`send` must carry the SAME idempotency key on every attempt."""
    for attempt in range(attempts):
        try:
            resp = send()
        except TimeoutError:
            pass
        else:
            if resp.status not in RETRYABLE_STATUS:
                budget.record_completion()
                return resp
        if attempt == attempts - 1 or not budget.withdraw():
            raise RetriesExhausted()
        sleep = random.uniform(0, min(cap, base * 2 ** attempt))   # full jitter
        if time.monotonic() + sleep > deadline:                    # no time to try again
            raise RetriesExhausted()
        time.sleep(sleep)
    raise RetriesExhausted()

Four details carry the weight. The idempotency key is minted outside this loop, so every attempt is the same intent. A non-retryable status returns immediately instead of burning attempts. The budget check precedes the sleep, so an exhausted budget fails fast rather than after two seconds of waiting. And a retry that cannot finish before the deadline is never made.

Circuit breakers

A breaker wraps calls to one dependency and watches the failure rate. Above a threshold it opens: subsequent calls fail instantly without touching the network. After a cooldown it goes half-open, lets a probe through, and closes again if the probe succeeds.

The usual explanation is "fail fast so you do not waste time," and it is the less important half. The real value is that an open breaker removes load from the failing dependency. A service in a GC death spiral, or with a 10,000-deep request queue, cannot recover while it is still being hammered — it needs quiet to drain, and the breaker manufactures that quiet. It is load shedding imposed by the client on behalf of the server.

CLOSED calls pass through outcomes counted OPEN calls fail instantly dependency gets quiet HALF-OPEN one probe allowed everything else fails errors ≥ 50% of ≥ 20 requests in a 10 s window after 5 s probe fails → re-open, reset timer probe succeeds Every call is attempted.
The open state exists for the dependency, not the caller. Failing fast saves the caller some threads; the silence is what lets a saturated service drain its queue and recover. A breaker with no cooldown, or one that admits every call in half-open, delivers the first benefit and not the second.

The numbers that make one work

Three parameters decide whether a breaker helps or hurts.

Minimum request volume. Without it, one failure out of one call is a 100% error rate and the breaker trips. Hystrix defaulted to 20 requests in the rolling window before the error percentage is even evaluated; Resilience4j's sliding window defaults to 100 calls. Any breaker on a low-traffic endpoint without this will flap.

Error threshold over a rolling window. 50% over 10 seconds is a sane default. Resist tightening it: a 10% threshold trips on the normal background noise of a healthy distributed system.

Cooldown. Long enough for the dependency to drain: 5 seconds is the usual starting point (Hystrix's default sleep window), 30–60 seconds when the failure mode is a restart.

One parameter people forget: trip on latency, not only on errors. The dangerous failure is not a service returning 500s, it is one returning 200s after 9 seconds. Counting a timed-out call as a failure covers it — another reason the timeout must be tight enough to fire during a brownout and not only during a hard outage.

Where to put it

Per dependency and per endpoint, not per service — a slow /search should not open the breaker for /health. Ideally per upstream host too, because the common failure is one bad instance out of twenty rather than the whole fleet, which is where breaking overlaps with load balancer outlier ejection. Envoy ejects a host after 5 consecutive 5xx responses for a base 30 seconds and caps ejections at 10% of the pool. That cap is what hand-rolled breakers miss: a breaker with no ceiling on how much capacity it can remove is a new way to cause an outage.

Backpressure is the thing that actually fixes it

Timeouts, retries and breakers are all client-side containment. None of them changes the fact that the server accepted more work than it could do. That is a server-side problem with a server-side fix.

Bound the queue to the deadline

Every overloaded service has a queue, designed or inherited from a thread pool, a connection backlog or the kernel's accept queue. Depth converts straight to latency by Little's Law: at 100 rps, a queue holding 1,000 requests makes the request at the tail wait 10 seconds.

If callers time out after 1 second, only the first 100 entries can possibly be served in time. The other 900 are dead on arrival — the server will faithfully execute them, spend CPU on them, and write responses that no one is listening for. Goodput goes to roughly 10% while utilisation reads 100%, which is why "the dashboards were all green" is such a common line in these postmortems.

worker 100 rps arrivals 0 100 1,000 served in time will time out before a worker reaches it Queue depth 1,000 ÷ 100 rps = 10 s of wait. The caller's deadline is 1 s. So 900 of the 1,000 queued requests are already dead, and the server does not know it. Bound the queue at rate × timeout = 100, and the 901st arrival gets an honest, instant 503.
A queue deeper than rate × deadline is a latency generator, not a buffer. The only useful queue is one short enough that everything in it can still be served in time; beyond that, rejecting is strictly better than accepting, for the caller and for the server.

So size every queue at service_rate × client_timeout and reject beyond it. A fast 503 with Retry-After beats a slow success, because it lets the caller shed, fall back or degrade while there is still time. If the work can legitimately happen later, move it off the request path and onto a message queue — which is the opposite of buffering a synchronous call, and works precisely because nobody is waiting.

LIFO under load

Under sustained overload, serve the newest request first. FIFO hands the worker whichever request has waited longest and is therefore most likely to have been abandoned, so under heavy overload it can approach zero goodput while the server runs flat out; LIFO always picks the request with the most deadline left. Facebook described this as adaptive LIFO — FIFO normally because it is fairer, flipping to LIFO only when queue depth signals overload, paired with CoDel-style detection of standing queues — in "Fail at Scale."

What this does not solve

None of it creates capacity. If a dependency is provisioned for 600 rps and demand is 800 rps, every mechanism here only decides who gets the error. Budgets, breakers and bounded queues make the failure proportional and recoverable instead of total; they do not serve the extra 200 rps. If the shortfall is structural the answer is capacity or a cheaper request path, and saying so beats adding another layer of resilience config.

Breakers are per-process. A thousand instances each running their own breaker means the dependency sees a thousand independent probes in half-open. Each is locally "one probe"; together they are a load spike at exactly the moment of recovery. Jitter the cooldown per instance, and remember breaker state is unsynchronised unless you paid to share it.

The recovery is its own failure mode. When a breaker closes or a dependency restarts, caches are cold and pools are empty, and full load arrives at once against a service that is temporarily slower than normal — which is where cache stampedes and the second outage come from. Ramp traffic back; do not restore it in one step.

Nothing here makes a write safe to retry. That is a separate property of the operation, and no amount of backoff provides it.

Partial failure inside a request is untouched. If a handler updates two services and the second call opens a breaker, you have a half-applied operation — a saga problem, not a retry-policy one.

Gray failure evades all of it. A dependency returning fast, confident, wrong answers — a stale replica, an empty result set from a broken index — looks healthy to every mechanism here. Success-rate and latency signals miss it; data-quality monitoring does not.

The alternatives worth naming

Adaptive concurrency limits. Instead of a static breaker and a static pool size, measure the latency gradient and let the limit find itself: when observed latency rises above the no-load baseline, the in-flight limit shrinks. This is TCP congestion control applied to RPC; Netflix's concurrency-limits is the reference implementation. I would reach for it before a hand-tuned breaker on any service whose traffic shape changes, because the numbers in the breaker section are guesses that go stale and a gradient algorithm does not need them.

Hedged requests. For read-heavy tail-latency problems, send a second request to another replica once the first exceeds its p95 and take whichever returns first. Dean and Barroso's "The Tail at Scale" reported cutting 99.9th-percentile latency from about 1.8 s to 74 ms on a BigTable benchmark for roughly 2% extra requests. This attacks slow, not failed, and only works for cheap read-only operations.

Service mesh outlier detection. Envoy or Linkerd can do breaking, budgeted retries and per-host ejection outside application code, identically for every language in the fleet. If you already run a mesh, prefer it to a library per service: those drift, and config drift is itself a failure you are designing for.

Load shedding by priority. Shedding background sync and prefetch traffic before user-initiated requests buys far more useful capacity than any uniform policy, and it costs one header and one bucket.

Graceful degradation. A stale cached value, a default ranking or a partial page usually beats an error, and it is the answer interviewers most want after "the dependency is down." Decide it per feature before you need it.

Saying this in an interview

When asked what happens if a dependency gets slow, the ordering that lands best:

  1. Name the amplification first. "The risk isn't the slow dependency, it's that my retries turn a 25% shortfall into a total outage, and retries multiply across hops."
  2. Timeout from the measured tail, and give the Little's Law number for why a loose one takes the whole service down.
  3. Propagate a deadline instead of per-hop timeouts, and reject work whose deadline has passed.
  4. Retry at one layer, with full jitter and a budget — and say the budget is 10% of successes, so worst-case load is 1.1× rather than 3×.
  5. Add the breaker, and say what it is for: giving the dependency quiet so it can drain, not saving your own threads.
  6. Bound the queue at rate × timeout and shed, because that is the part that fixes the problem rather than containing it.
  7. Volunteer the limit. None of it creates capacity; it only makes the failure proportional.

Steps 4, 6 and 7 are where candidates separate. Almost everyone says "retry with exponential backoff and a circuit breaker"; the budget, the queue bound and the honesty about what resilience cannot do are what make it sound like you have run a system rather than read about one.

If you want to hear how this holds up under follow-up questions, practising it out loud in a voice system design mock on Whitepad is a decent way to find the gaps.

Practice this out loud

Reading is the easy part. Sit across from a senior AI interviewer that talks, watches your whiteboard, and scores you like the real thing — your first mock is free.

Start a free mock →