The idea in one minute#
Retrying a failed request hides transient failures — a dropped packet, a restarting replica — and is one of the cheapest reliability wins there is. It is also one of the most common causes of large outages. When a service fails because it is overloaded, every client retrying multiplies the load on something that is already drowning.
Safe retries follow four rules: retry only retryable errors on idempotent operations; wait with exponential backoff and jitter so retries spread out instead of arriving in waves; cap attempts and stay inside the deadline; and limit retries with a retry budget (for example, retries may add at most 10% to the request rate) — and retry at one layer only.
An analogy#
A crowd at a locked door. If everyone keeps pushing at once every few seconds, the door never opens and people get crushed. If each person waits a random, growing amount of time before trying again, the doorman can let them through one by one.
A picture#
flowchart TB
subgraph AMP["Retry amplification: 3 attempts at each of 3 layers"]
direction LR
C["Client<br/>×3"] --> F["Front end<br/>×3"] --> B["Backend<br/>×3"] --> DB[("DB<br/>sees up to 27×")]
end
subgraph FIX["Safe retries"]
direction LR
R1["Retry only at<br/>one layer"] --> R2["Exponential backoff<br/>+ full jitter"] --> R3["Retry budget<br/>≤ 10% extra"] --> R4["Respect deadline<br/>and Retry-After"]
end
class C,F,B queue
class DB warn
class R1,R2,R3,R4 ioHow it really works#
What to retry#
| Retry | Do not retry |
|---|---|
| Connection refused / reset, before the request was sent | 4xx client errors (400, 401, 403, 404, 422) — the next attempt will fail too |
| 503 Service Unavailable, 502/504 from a proxy | 500 that may have changed state, unless the operation is idempotent |
429 Too Many Requests — after the Retry-After delay | Anything when the deadline has passed |
gRPC UNAVAILABLE, RESOURCE_EXHAUSTED (with backoff) | gRPC INVALID_ARGUMENT, PERMISSION_DENIED, FAILED_PRECONDITION |
| Timeouts — only for idempotent operations | Non-idempotent writes without an idempotency key |
Idempotency#
An operation is idempotent if doing it twice has the same effect as doing it once. GET,
PUT (set to a value) and DELETE are idempotent by design; POST /payments is not — a retry
after a timeout might charge twice, because the first attempt may have succeeded and only the
response was lost.
Make writes safe to retry with an idempotency key: the client generates a unique key per
logical operation and sends it with every attempt; the server stores the key with the result and
returns the stored result for repeats. Stripe’s API is the well-known example
(Idempotency-Key header).
Backoff and jitter#
- Exponential backoff: wait
base × 2^attempt, capped (e.g. 100 ms, 200 ms, 400 ms, … up to 10 s). Gives the dependency time to recover. - Jitter: randomise the wait. Without jitter, every client that failed at the same moment retries at the same moment — synchronised waves that keep knocking the service over.
AWS’s analysis compared variants; full jitter is simple and among the best:
sleep = random_between(0, min(cap, base × 2^attempt))| Strategy | Formula | Behaviour |
|---|---|---|
| None (immediate) | 0 | Hammering; worst |
| Exponential, no jitter | min(cap, base·2ⁿ) | Synchronised waves |
| Full jitter | rand(0, min(cap, base·2ⁿ)) | Spreads well; least total work in AWS’s tests |
| Equal jitter | half + rand(0, half) | Slightly more work than full |
| Decorrelated jitter | min(cap, rand(base, prev·3)) | Good, a little more complex |
Retry amplification#
If each of L layers makes up to A attempts, the bottom layer can see A^L times the load:
3 attempts at 3 layers is 27×, exactly when the bottom layer is struggling. Rules:
- Retry at one layer — usually the one closest to the user that knows the deadline, or the client library of the failing dependency — and have other layers fail fast.
- Signal “do not retry” upward: return a status that the layer above will not retry (e.g. gRPC
passes back
UNAVAILABLEfrom the edge only, or a custom header likex-no-retry).
Retry budgets#
A cap on attempts per request is not enough; when everything fails, every request uses its maximum. A retry budget caps retries as a share of traffic across the whole client:
allow a retry only if retries in the last 10 s < 0.1 × requests in the last 10 sWhen the dependency is healthy, almost every retry fits in the budget. When it is down, retries
add at most 10% load instead of 200%. Finagle, Envoy (retry_budget on a cluster’s circuit
breakers) and gRPC (retryThrottling with a token bucket) implement this.
Hedging#
A different tool for a different problem: for tail latency, send a second copy of a read-only request if the first has not answered by the p95, and use whichever returns first. Done carefully (only after p95, only for idempotent reads, with a budget), hedging cuts the tail for a few percent extra load. Done carelessly, it is an amplification bug.
A worked example#
A payments API restarts and 500 clients, each with a request in flight, see errors at the same moment. The API can serve 50 requests per 10 ms — but, like every real server, rejecting a request also costs it work (accepting the connection, parsing, deciding, responding). Here a rejection costs a quarter of a served request, so at 200 arrivals per tick it serves nobody.
- Immediate retries: all 500 clients retry every tick; the API spends its whole capacity rejecting them and serves no one. Every client exhausts its attempts. This is congestion collapse.
- Exponential, no jitter: the waves are further apart, but each is still all 500 clients at once, so each fails completely — the same outcome, spread over six seconds.
- Jitter: retries spread across each backoff interval, arrivals per tick fall to what the server can handle, and every client is served with less than half the calls.
Code#
// retries.go — compare retry strategies after a thundering herd, then show amplification and budgets.
package main
import (
"fmt"
"math"
"math/rand"
)
const (
clients = 500
capacity = 50.0 // work units per tick (10 ms): enough to serve 50 requests
rejectCost = 0.25 // even rejecting a request costs work: accept, parse, decide, respond
baseTicks = 1 // first backoff: 10 ms
capTicks = 200 // max backoff: 2 s
maxAttempts = 10
)
type strategy struct {
name string
delay func(r *rand.Rand, attempt int, prev int) int
}
func expo(attempt int) int {
return int(math.Min(capTicks, float64(baseTicks)*math.Pow(2, float64(attempt))))
}
func simulate(s strategy, budget float64) (calls, ticks, gaveUp, peak int) {
r := rand.New(rand.NewSource(1))
next := make(map[int][]int) // tick → clients sending then
attempts := make([]int, clients)
prev := make([]int, clients)
for c := 0; c < clients; c++ {
next[0] = append(next[0], c)
}
done := 0
firstTries, retries := 0, 0
for t := 0; done+gaveUp < clients; t++ {
batch := next[t]
delete(next, t)
r.Shuffle(len(batch), func(i, j int) { batch[i], batch[j] = batch[j], batch[i] })
if t > 0 && len(batch) > peak {
peak = len(batch)
}
// Every arrival costs rejectCost; what is left serves requests at (1 - rejectCost) each.
// Past a point, more arrivals mean FEWER served: congestion collapse.
served := int(math.Max(0, (capacity-rejectCost*float64(len(batch)))/(1-rejectCost)))
for i, c := range batch {
calls++
if i < served {
done++
continue
}
attempts[c]++
if attempts[c] >= maxAttempts {
gaveUp++
continue
}
// Retry budget: retries may be at most `budget` × first attempts.
if budget > 0 && float64(retries) >= budget*float64(firstTries+clients) {
gaveUp++
continue
}
retries++
d := s.delay(r, attempts[c], prev[c])
if d < 1 {
d = 1
}
prev[c] = d
next[t+d] = append(next[t+d], c)
}
ticks = t + 1
}
return
}
func main() {
strategies := []strategy{
{"immediate retry", func(*rand.Rand, int, int) int { return 1 }},
{"exponential, no jitter", func(_ *rand.Rand, a, _ int) int { return expo(a) }},
{"exponential + full jitter", func(r *rand.Rand, a, _ int) int { return r.Intn(expo(a) + 1) }},
{"exponential + equal jitter", func(r *rand.Rand, a, _ int) int { h := expo(a) / 2; return h + r.Intn(h+1) }},
{"decorrelated jitter", func(r *rand.Rand, _ int, p int) int {
if p < baseTicks {
p = baseTicks
}
return int(math.Min(capTicks, float64(baseTicks+r.Intn(3*p))))
}},
}
fmt.Printf("%d clients fail at once; the server can serve %.0f per 10 ms tick, but every request\n", clients, capacity)
fmt.Printf("it rejects costs %.0f%% of a served one; up to %d attempts per client\n\n", rejectCost*100, maxAttempts)
fmt.Printf("%-28s %7s %9s %8s %16s\n", "strategy", "calls", "drain", "gave up", "peak after t=0")
for _, s := range strategies {
calls, ticks, gaveUp, peak := simulate(s, 0)
fmt.Printf("%-28s %7d %7d ms %8d %16d\n", s.name, calls, ticks*10, gaveUp, peak)
}
fmt.Println("\nRetry amplification: worst-case load at the bottom layer")
for _, layers := range []int{1, 2, 3, 4} {
for _, attempts := range []int{2, 3, 5} {
fmt.Printf(" %d layers × %d attempts = %4.0f×", layers, attempts, math.Pow(float64(attempts), float64(layers)))
}
fmt.Println()
}
fmt.Println("\nThe dependency is completely DOWN: extra load from retries, per original request")
const maxA = 3
fmt.Printf(" %d attempts, no budget: +%d%% load (every request uses every attempt)\n", maxA, 100*(maxA-1))
fmt.Printf(" %d attempts, 10%% budget: +10%% load (retries capped at a tenth of requests)\n", maxA)
_, _, gaveUp, _ := simulate(strategies[0], 0.1)
fmt.Printf(" the herd above, immediate retry with a 10%% budget: %d of %d clients give up quickly\n", gaveUp, clients)
fmt.Println(" instead of hammering — the server recovers, and those clients' callers can fall back.")
}In the first table, the two unjittered strategies serve nobody: synchronised retries keep the server in collapse until every client gives up. All three jittered strategies serve everyone. (Equal and decorrelated jitter drain a little faster than full jitter in this run; AWS found full jitter does the least total work over many runs. Any jitter is vastly better than none.) The last lines are the reason for budgets: when the dependency is completely down, a retry budget turns +200% load into +10%.
Remember this#
- Retry only retryable errors, and only idempotent operations (or use idempotency keys).
- Exponential backoff with full jitter; cap attempts; stay inside the deadline; honour
Retry-After. Aattempts atLlayers is up toA^Lload — retry at one layer only.- Use a retry budget (≈10%) so retries cannot multiply load during an outage.
- Hedging is for tail latency, with a budget, for idempotent reads only.
Try it#
- Run
retries.go. Halvecapacity. Which strategy degrades most? - Implement an idempotency-key store in Go: a map from key to stored response, with an expiry.
- Find every layer that retries in a request path you know. How many attempts can the bottom layer see?
Check yourself#
- Why does exponential backoff without jitter still cause outages?
- A
POST /paymentstimed out. Is it safe to retry? What makes it safe? - What does a retry budget protect against that a max-attempts limit does not?
- Why retry at one layer only?