Course contents

09. Reliability and Resilience Lesson 2 of 10

Retries

See retries absorb a crashed instance, then turn a short burst into a retry storm; learn retry budgets, one-layer retries and idempotency keys.

14 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Retries turn transient failures (a crashed instance, a dropped connection) into slightly slower successes.
  • Under overload each retry is extra load; a short trigger plus retries can become an outage that outlives the trigger.
  • A retry budget caps retries at a share of traffic, so they vanish exactly when failures are widespread.
  • Retries at several layers multiply: 3 × 3 × 3 = 27 calls. Retry at one layer.
  • A timed-out call may have succeeded. Retry writes only with an idempotency key the server de-duplicates.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A retry is a new attempt at an operation that failed, made automatically by the caller. A retry policy decides which failures to retry, how many attempts to make, how long to wait between them, and when to stop. Retries are one of the cheapest reliability tools and one of the easiest to get dangerously wrong.

Why it exists

Many failures in distributed systems are transient: an instance crashed and the load balancer has not noticed yet, a connection was reset, a leader election is in progress, a request landed in a garbage-collection pause. The same request a moment later, often on a different instance, succeeds. Retrying hides these faults from users at the cost of a little latency.

How it works

Classify the failure. Retry failures that can plausibly succeed next time: connection errors, timeouts, 503 Service Unavailable, 429 Too Many Requests (honouring Retry-After), and gRPC UNAVAILABLE. Do not retry errors that will repeat: validation failures (400), authorisation failures (401/403), not found (404), or business-rule rejections.

Bound the attempts. A maximum number of attempts (commonly 2–3 in total) and an overall deadline: the retries must fit inside the time the caller is willing to wait.

Wait between attempts. Exponential backoff with jitter (see the next lesson) so retries do not arrive in synchronised waves and give the dependency time to recover.

Budget the retries. A per-call cap is not enough: if every call fails, a cap of 3 attempts still triples the load. A retry budget limits retries to a share of the traffic, for example a token bucket that earns 0.1 tokens per successful call and spends 1 per retry. When failures are rare the budget has room; when they are widespread it drains and further failures are returned without retrying. gRPC’s retry throttling and Envoy’s retry budgets implement this idea.

Retry at one layer. If the browser, the gateway and the service each make 3 attempts, one click can become 3 × 3 × 3 = 27 calls to the dependency at the bottom. Choose one layer to retry (often the one closest to the failure or the outermost one) and have the others fail fast.

Make the operation idempotent. A timeout says only that the answer did not arrive in time; the request may have been processed. Retrying a non-idempotent write can then apply it twice. Reads, PUT of a full resource and DELETE are idempotent by design; for creates and payments, the client sends an idempotency key (the same key on every attempt) and the server stores the first result per key and returns it for repeats.

When to use it

  • For idempotent calls to dependencies that fail transiently: other services behind load balancers, managed cloud APIs, databases during failover.
  • When a short extra latency is acceptable and the call fits inside the caller’s deadline.
  • For writes, only together with idempotency keys or naturally idempotent operations.

When not to

  • For non-transient errors (bad input, missing permission).
  • When the dependency is overloaded: retries add load to the part that is failing. Let a budget or a circuit breaker stop them.
  • At several layers of the same call chain.
  • For non-idempotent operations without de-duplication on the server.
  • When the user has already given up: retrying past the caller’s deadline is wasted work.

Trade-offs

Choice You gain You pay
More attempts Survive longer or repeated transient faults More load during incidents; longer worst-case latency
Retry budget Retries vanish when failures are widespread Some transient failures during an incident are not retried
Retry at the edge only Simple accounting, no multiplication Retries travel the whole path again
Retry close to the failure Cheap, fast retries Other layers must not retry too
Idempotency keys Safe retries of writes Server-side storage of keys and results, with an expiry
Hedged requests (send a second copy early) Lower tail latency Extra load all the time; idempotent reads only

Alternatives

  • Fail fast and let the user retry, with a clear error message, for actions that are cheap to repeat.
  • Asynchronous processing: put the work on a queue; the queue redelivers on failure, with a dead-letter queue for poison messages.
  • Circuit breakers stop calls entirely while a dependency is clearly failing.
  • Fallbacks: cached data, a default, or a degraded feature instead of another attempt.
  • Hedging for latency-sensitive idempotent reads.

Failure modes

  • Retry storm: retries amplify load on an overloaded dependency until almost every call fails. It can be metastable: the overload continues after the original trigger is gone, because the retries sustain it. Try the Retry Storm scenario in the Failure Lab.
  • Multiplication across layers: retries at each hop multiply into tens of calls per user action.
  • Duplicate side effects: a retried payment, email or order without an idempotency key.
  • Retrying the unretryable: retrying 400s or 403s adds load and delays the real error.
  • Synchronised retries: fixed delays make many clients retry at the same instant, in waves.
  • Retries hiding problems: a dependency failing 5% of calls looks healthy on the caller’s dashboard; count retries as a metric and alert on them.

In production

Use the retry support in your client library, service mesh or gateway rather than ad-hoc loops, and configure it in exactly one place per call chain. Retry only transient error classes, cap attempts at 2–3, use exponential backoff with full jitter, and enforce an overall deadline. Add a retry budget (Envoy retry budgets, gRPC retry throttling, or a token bucket in your own client). Send idempotency keys on every non-idempotent request and store results per key on the server for at least as long as clients retry. Publish retry counts and the retry ratio per dependency; a rising ratio is an early warning of a struggling dependency.

Common misconceptions

  • "Retries make calls reliable." They improve the odds against transient faults. Against overload they reduce reliability.
  • "Backoff prevents retry storms." Backoff spreads retries out and slows them down; every retry is still sent. A budget or a breaker limits how many.
  • "If it timed out, it didn’t happen." The work may have completed; only the answer was late.
  • "Three attempts means at most three times the load." Per layer. With retries at three layers it is up to 27 times.

Interview angle

When you add retries to a design, say which errors are retried, how many attempts, with what backoff, at which layer, and how writes stay safe (idempotency keys stored on the server). Expect a follow-up about overload: explain retry amplification, retry budgets and circuit breakers, and mention the metastable-failure pattern (a trigger, then a sustaining effect such as retries). A strong answer connects retries to timeouts: retries must fit inside the caller’s deadline.

Model assumptions

The simulation is a simplified model, not a benchmark. The web app sends 200 calls per second (Poisson) with a 250 ms timeout through a round-robin load balancer (health checks every 500 ms; 2 failures eject, 2 successes restore) to three Payments instances, each with 4 workers, a 40 ms mean service time (lognormal, cv 0.5) and room for 30 waiting calls. "25% slower" reduces each instance’s speed to 0.75. Retries use up to 3 attempts with exponential backoff of 50 ms doubling to at most 200 ms, full jitter; a retry goes through the balancer again and the timed-out attempt keeps running. The retry budget is not modelled: the budget step switches retries off while a budget would be empty (1.2–5 s) and on again afterwards. Idempotency keys are not modelled; the duplicate charges are attempts of the same logical call that both completed. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A brief failure costs real requests

    The web app makes 200 payment calls a second through a load balancer to three Payments instances, each about two-thirds busy. Calls time out after 250 ms.

    One second in, Payments 2 crashes; it restarts and is back 1.5 s later. Calls that were inside it fail, and for about a second the balancer keeps sending every third call to it until its health checks notice. Each of those calls fails with "connection refused", although two healthy instances were one hop away.

    The failure is transient: a different attempt, a moment later, would have worked.

    Scene: The web app calls three Payments instances through a load balancer. Payments 2 crashes; until health checks eject it, calls sent to it fail.

    Key idea: Many failures are transient: a crashed instance, a dropped connection, a leader election. The same request a moment later succeeds.

  2. 2. Try again, somewhere else

    The web app now retries a failed call: up to 3 attempts in total, waiting a random 0–50 ms before the second and 0–100 ms before the third.

    Same crash, same second of blindness at the balancer. But a retry goes through the balancer again and lands on a healthy instance, so the user almost never sees the failure. The error rate during the crash falls from over 10% to about 1% (a few calls are unlucky three times in a row); the main trace is a bump in the retries tile.

    This is what retries are for: brief, random faults where another attempt has a good chance.

    Scene: With retries, calls that fail on the crashed instance are sent again through the balancer, reach a healthy instance and succeed. The error rate falls to about 1%.

    Key idea: Retries turn transient failures into slightly slower successes, as long as the next attempt has a real chance of working.

  3. 3. A slowdown and a burst, without retries

    Retries are off again for a moment. All three instances now run 25% slower (a busy database underneath, a heavy background job). Capacity drops from about 300 to about 225 calls a second for 200 offered: tight, but it fits.

    One second in, a burst arrives: 320 calls a second for one second (a push notification went out). Queues fill, waits pass 250 ms and calls time out; the timed-out ones still run to the end, so the instances fall further behind for a while.

    Then the burst is over and nothing amplifies the damage: the queues drain and within a few seconds calls succeed again.

    Scene: Payments runs 25% slower. A one-second burst causes timeouts; without retries the queues drain afterwards and calls succeed again within a few seconds.

    Key idea: A system near its limit absorbs a short burst with some errors, then recovers on its own once the burst ends.

  4. 4. Retries turn a burst into an outage

    Same slowdown, same one-second burst, but now the web app retries as before. During the burst, calls time out; each timeout sends another call into instances that are already full, while the timed-out attempt keeps running too. Every retry is pure extra load.

    The burst ends at 2 s, but the offered load does not come down: retries of retries keep it far above 200 calls a second, queues stay full and almost every call fails. The trigger is gone and the outage stays. This is a *metastable failure*: the system is stuck in a bad state that the retries themselves sustain.

    The Failure Lab’s Retry Storm scenario lets you fight one of these.

    Scene: With retries on, the same burst causes a retry storm: after the burst ends, offered load stays far above 200 calls per second and almost every call fails.

    Key idea: Under overload every retry is extra load on the part that is already failing. A short trigger plus retries can become an outage that outlives the trigger.

  5. 5. A retry budget caps the extra load

    A retry budget limits retries to a share of normal traffic, for example: retries may add at most 10% to the calls this client sends. While failures are rare the budget has room and retries work as before. When failures pile up, the budget runs dry and further failures are returned at once, not retried. When calls succeed again, it refills.

    *The simulator does not model the budget itself; this step approximates it by switching retries off at 1.2 s (budget drained by the burst) and on again at 5 s (refilled).* Same slowdown, same burst: the errors look like the run without retries, the system recovers, and retries are back for the next blip.

    Retry at one layer only, too. If the browser, the gateway and the service each try 3 times, one click can become 27 calls to Payments.

    Scene: With a retry budget, retries stop while it is empty during the burst. The system recovers like the run without retries, and retries resume once the budget refills.

    Key idea: Bound retries by a budget (a share of traffic), not just a per-call count, and retry at one layer only.

  6. 6. A timeout does not mean "it didn’t happen"

    Payments is healthy again, retries are on, and to make the effect easy to see the timeout is tight: 120 ms. Most calls finish in time; a few in the slow tail do not.

    Look at what happens to one of those: the web app gives up and retries, but the first attempt was not cancelled. Payments finishes it and the retry. The customer is charged twice. In the simulation this happens to one or two calls every second: two successful attempts of one logical call.

    Only retry operations that are idempotent: safe to run more than once. Reads usually are. For writes, send an idempotency key with every attempt (the same key on the retry), and let the server store the first result and return it for repeats instead of charging again.

    Scene: With a tight 120 ms timeout, a few slow calls time out and are retried while the first attempt still completes, so Payments processes those calls twice.

    Key idea: A timed-out call may still have succeeded. Retry writes only if the server de-duplicates them, for example with an idempotency key.

  7. 7. Retry rules that keep you safe

    Back to normal: 250 ms timeout, up to 3 attempts with random backoff, and a retry budget that has plenty of room because almost nothing fails.

    The rules: retry only transient failures (timeouts, connection errors, 503), never "invalid request". Retry only idempotent operations or ones carrying an idempotency key. Cap attempts and cap retries as a share of traffic. Wait between attempts with backoff and jitter (next lesson). Retry at one layer. And stop entirely when a circuit breaker says the dependency is failing.

    Scene: A healthy Payments tier with a 250 ms timeout and budgeted retries: every call succeeds and almost no retries are needed.

    Key idea: Retries are a tool for transient faults. Budget them, make them idempotent, spread them out, and stop when failure is not transient.