Distributed patterns and operations
Timeouts and retries with jitter
Bound every remote call with a timeout and a deadline, retry only what is safe, and use backoff, jitter and retry budgets so that retries do not turn a blip into an outage.
The problem
A team runs a checkout service that calls an inventory service, which reads from a database. One afternoon a long-running query holds locks, and typical query time goes from 5 ms to 8 seconds for about a minute.
The inventory service’s HTTP and database clients have no timeouts. That is common, because many libraries wait forever unless told otherwise: Python’s requests and Go’s default http.Client both behave this way. So every inventory thread waits on the database, and every checkout thread waits on inventory. Within seconds both services have no free threads. Checkout stops serving everything, including pages that never touch inventory. The fault was one slow query. The outage was every caller waiting patiently.
The team adds a 1 second timeout and, now that failures are visible, a retry: three attempts, sent immediately. The next slow minute is worse. Every timed-out request is sent again twice, so the struggling database receives three times its normal traffic at the moment it can least handle it. When it recovers, the clients all retry in step and push it over again. That pattern is called a retry storm.
Timeouts and retries are the first tools anyone reaches for, and used carelessly they cause larger outages than the faults they were meant to hide. This lesson covers how to use them safely.
Every remote call needs a timeout
A local function call returns or throws. A remote call has a third outcome: nothing. The packet was lost, the peer is paused, or a load balancer dropped the connection without telling anyone. A timeout turns “unknown” into an error you can handle, and it limits how much of your service one slow dependency can occupy.
Set two values. The connection timeout covers establishing the connection and can be short, since connecting inside a data centre normally takes a few milliseconds at most. The request timeout covers waiting for the response.
Choose the request timeout from the dependency’s measured latency, not from a round number. A common starting point is a little above its p99.9 under normal load. If p99 is 80 ms and p99.9 is 200 ms, a 250 ms timeout cuts off fewer than 1 in 1,000 healthy requests and frees the thread within a quarter of a second when things go wrong.
- Too high and it protects nothing. At 500 requests per second, a 30 second timeout allows 15,000 requests to pile up in flight.
- Too low and you abort requests that were about to succeed, then pay for them again as retries.
Deadline propagation
Timeouts set hop by hop know nothing about each other. If the gateway gives up after 2 seconds but the inventory service allows its database 5 seconds, inventory works for 3 more seconds on a request nobody is waiting for.
The fix is a deadline. The edge sets a total budget, say 2 seconds. Each service passes the remaining time to the services it calls, checks it before starting expensive work, and stops when it reaches zero. gRPC supports this directly: the deadline travels in the grpc-timeout header, and a server can pass the remaining time on to the calls it makes. With plain HTTP you carry a header yourself and enforce it in each service. If you cannot propagate a deadline, at least make timeouts shrink as you go down the chain.
What is safe to retry
Ask two questions. Is the failure transient? Is it safe to perform the operation twice?
| Outcome | Retry? | Why |
|---|---|---|
| Connection refused or reset before the request was sent | Yes | The request was never executed |
503, or 429 with Retry-After |
Yes, after waiting | The server says the condition is temporary |
| Timeout, or connection lost mid-request | Only if idempotent | The work may have been done |
| 400, 401, 403, 404, 422 | No | The same request will fail the same way |
A timeout is ambiguous. The server may have charged the card and lost the reply. So idempotency is the precondition for retrying. In HTTP, GET, PUT and DELETE are defined as idempotent and POST is not. To make a POST safe, the client generates a unique idempotency key for the logical operation and sends it on every attempt. The server stores the key with the result and returns the stored result for a repeat. Idempotency and deduplication covers the server side.
Backoff and jitter
An immediate retry arrives while the dependency is still broken. Exponential backoff waits longer after each failure: 100 ms, 200 ms, 400 ms and so on, up to a cap such as 10 seconds. The longer a failure lasts, the less traffic each client sends.
Backoff alone leaves one problem. Clients that fail together compute the same waits, so they retry together.
Step 1 of 8
An inventory service can handle 2,000 requests per second and normally sees 500. One thousand clients each have a request in flight. Everything is healthy.
Read the steps as text
- An inventory service can handle 2,000 requests per second and normally sees 500. One thousand clients each have a request in flight. Everything is healthy.
- The database fails over, and the service fails every in-flight request at the same instant. All 1,000 clients see an error at the same moment. The failover completes in under a second.
- Every client runs the same policy, which is to wait 1 second, then 2, then 4. Identical waits mean all 1,000 retries arrive within the same few milliseconds. The service starts about 2 requests per millisecond and queues 200, so roughly 800 are rejected.
- The 800 rejected clients all wait 2 seconds and come back together at the 3 second mark. Exponential backoff moved the waves further apart, but each wave is still a spike. About 600 are rejected again.
- After the last retry about 400 clients give up and show an error to their users. The service was healthy and mostly idle the whole time. The average load was low, but it arrived in spikes that no queue could absorb.
- Now replay the same failure with full jitter. Each client waits a random time between zero and its backoff value, so the 1,000 first retries are spread evenly across one second.
- One thousand retries over one second is 1,000 requests per second on top of the normal 500. That is 1,500 against a capacity of 2,000, so every retry succeeds on its first attempt.
- Exponential backoff reduces how often each client retries. Jitter removes the synchronisation and turns a spike into a steady flow. Use both together, and cap the number of attempts.
Jitter adds randomness to the wait. Three variants are worth knowing. A 2015 AWS Architecture Blog article by Marc Brooker compared them in simulation.
full jitter: sleep = random(0, min(cap, base * 2^attempt))
equal jitter: half = min(cap, base * 2^attempt) / 2
sleep = half + random(0, half)
decorrelated jitter: sleep = min(cap, random(base, previous_sleep * 3))
The goal is to spread retries evenly through time. Full jitter uses the whole window from zero to the backoff value, so it gives the flattest arrival rate. Some clients will wait almost nothing, and that is fine: what protects the server is the aggregate rate, not any single client’s delay. Equal jitter keeps a guaranteed minimum wait but packs retries into half the window. Decorrelated jitter derives each wait from the previous one instead of from the attempt count. In that comparison every jittered variant beat plain backoff by a wide margin, full and decorrelated jitter performed about the same, and equal jitter trailed them. Full jitter is the usual default.
The same idea applies to anything periodic. Add jitter to cache expiry times, cron schedules and reconnect logic, or they will synchronise too. See cache stampedes.
Retry budgets and amplification
Capping attempts per request, usually at two or three, is necessary and not sufficient. If a dependency is down, every request uses all its attempts, so the dependency sees three times normal traffic. Layers make it worse.
Three ways to contain this, usually combined:
- Retry at one layer. Pick the layer that knows whether the operation is idempotent, often the one directly above the failing dependency. Other layers pass the failure through.
- Use a retry budget. Allow retries only as a fraction of ordinary requests. One implementation is a token bucket: each normal request adds 0.1 of a token and each retry spends one. Isolated failures still get retried, but during a full outage retries add about 10% load, not 200%. Google’s SRE book describes a 10% per-client budget. Finagle and Linkerd default to 20%.
- Let the server say “do not retry”. An overloaded server should reject early with a distinct signal, and clients should respect
Retry-After.
When failures persist, stop calling altogether. That is the job of a circuit breaker.
Hedged requests
A hedge is a retry for slowness, not failure. Send the request, and if no reply has arrived after roughly the p95 latency, send a second copy to a different replica. Use whichever answers first and cancel the other. Jeff Dean and Luiz André Barroso described the technique in “The Tail at Scale” (2013). Waiting until p95 limits the extra load to about 5% while cutting the long tail sharply.
Hedge only idempotent operations, typically reads, and put hedges under a budget. When the whole system is slow, unbounded hedging doubles the load.
When to choose it and when not to
Timeouts are not optional. Use them on every network call, including calls to databases, caches and queues.
Retries fit when failures are likely to be transient, the operation is idempotent and the deadline has time left. Do not retry:
- non-idempotent operations that have no idempotency key
- errors that say the request itself is wrong
- at every layer of the stack
- when the dependency is overloaded, because more attempts are more load
- when the user has already gone, because the deadline has passed
For work that does not need an immediate answer, a queue with redelivery and a dead letter queue is a better home for retries than a blocked request thread.
In the interview
Bring this up whenever you draw an arrow between two services, and always when the interviewer asks “what happens if this dependency is slow?”.
A strong answer takes about a minute. Every call has a timeout derived from the dependency’s tail latency, and a deadline set at the edge is propagated down. Retries apply only to transient errors on idempotent operations, with idempotency keys for writes. They use capped exponential backoff with full jitter, a small attempt limit, and a retry budget at a single layer so that retries cannot multiply. Then name the next line of defence: circuit breakers and load shedding for failures that last.
Key takeaways
- Every remote call needs a timeout, because a call that never answers holds a thread, a connection and memory until something else gives way.
- Pass a deadline down the call chain so that no service keeps working on a request its caller has already abandoned.
- Retry only transient failures, and only when the operation is idempotent. A timeout does not tell you whether the work was done.
- Exponential backoff lowers the retry rate. Jitter removes the synchronisation between clients. You need both.
- Per-request attempt limits multiply across layers. Retry at one layer and add a retry budget so retries stay a small share of traffic.
- Hedged requests cut tail latency for idempotent reads at the price of a few percent more load.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
Why does every remote call need a timeout?
A remote call can fail by never answering. Without a timeout the caller's thread and connection are held indefinitely, and one slow dependency can exhaust the caller.
What is deadline propagation?
The edge sets a total time budget and each service passes the remaining time downstream. Services stop work when the deadline has passed. gRPC carries it in the grpc-timeout header.
Which failures are safe to retry?
Transient ones (connection errors, 503, 429 after waiting), and only for idempotent operations. Timeouts are ambiguous, so non-idempotent calls need an idempotency key first.
What is full jitter?
Sleep for a random time between 0 and min(cap, base x 2^attempt). It spreads retries evenly over the whole backoff window, which gives the lowest peak load.
What is a retry budget?
A client-wide limit that allows retries only as a fraction of ordinary requests, for example 10 or 20 percent. It bounds the extra load during a full outage.
What is a hedged request?
Send a second copy of a slow idempotent request to another replica after roughly the p95 latency and take whichever answers first. It trims the tail for about 5 percent more load.