Timeouts, retries, backoff & idempotency
Make operations safe to retry and avoid retry storms.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
Networks fail, so clients need timeouts and retries. Retries are only safe when operations are idempotent, and they must back off with jitter so a struggling service is not flattened by a retry storm.
Explained simply
When one computer calls another over a network, many things can go wrong: the message gets lost, the other side is busy, or the reply never comes back. A timeout is a rule that says: if no answer comes within this time, stop waiting. Without one, a program can wait forever.
Many failures are temporary, so trying again often works. That is a retry. But retries have two dangers. First, if the request did succeed and only the reply was lost, trying again can do the action twice, like charging a card twice. Second, if a service is struggling, a flood of retries can knock it over completely.
The fixes are simple ideas. Make actions idempotent, which means doing them twice has the same effect as doing them once. Wait longer after each failed try, called exponential backoff. Add a little randomness to the wait, called jitter, so thousands of clients don't all retry at the same moment.
Done well, retries turn small hiccups into invisible delays. Done badly, they turn a small hiccup into a full outage. The difference is in the details: how long to wait, what to retry, how many times, and at which layer.
Press Play on a diagram to walk through it one step at a time.
- 1Send request
Include an idempotency key
- 2Timeout or 5xx
Treat as retryable failure
- 3Compute backoff
base x 2^attempt, capped
- 4Add jitter
Random delay spreads clients apart
- 5Retry or give up
Stop after max attempts or budget
- Back to step 1
- Client to Payments API: POST /charge key=abc1POST /charge key=abc
- Payments API to Key store: Save key=abc with result2Save key=abc with result
- Payments API to Client: Response lost (timeout)3Response lost (timeout)
- Client to Payments API: Retry POST key=abc4Retry POST key=abc
- Payments API to Key store: Key exists, fetch stored result5Key exists, fetch stored result
- Payments API to Client: Return original result, no new charge6Return original result, no new charge
- GET and HEAD reads
- PUT that sets a full value
- DELETE by ID
- Conditional update with a version
- POST that creates a payment
- Increment a counter
- Send an email or SMS
- Append to a list
In depth
Choosing timeout values
There are usually two timeouts. The connect timeout covers opening the connection and should be short, often under a second inside a data centre. The request (or read) timeout covers waiting for the answer and should be based on the dependency's real latency: a common starting point is a bit above its p99 or p99.9 latency, so normal slow requests finish but stuck ones are cut off.
Timeouts must shrink as you go deeper. If the user's request has a 2 second budget, the gateway cannot give a backend 3 seconds. Pass a deadline down the chain instead of fixed values: gRPC does this natively, sending the remaining time with each call so every service knows when the caller will give up. Work for a caller that already gave up is wasted, so check the deadline before starting expensive steps.
- 1Browser
Gives up after 5 s
- 2API gateway
Deadline 4 s
- 3Order service
Remaining 3.5 s; calls two backends
- 4Inventory service
Timeout 800 ms, one retry allowed
- 5Database query
Statement timeout 500 ms
What to retry and what not to
Retry only errors that might succeed next time. Good candidates: connection failures and resets, timeouts, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout, and 429 Too Many Requests. For 429 and 503, honour the Retry-After header if the server sends one. 500 Internal Server Error is a judgement call: retry only if the operation is idempotent.
Never retry errors that will fail again the same way: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 409 Conflict and 422 Unprocessable Content. Retrying them only adds load.
Also limit total attempts (3 to 5 is common) and total time. A retry policy that can run for minutes behind a user's click is worse than a fast, clear error.
- Retry: timeouts, resets, 429, 502, 503, 504
- Maybe: 500, only for idempotent calls
- Never: 400, 401, 403, 404, 409, 422
Backoff and jitter variants
Exponential backoff doubles the wait each time: 100 ms, 200 ms, 400 ms, capped at some maximum. On its own, it keeps clients in sync: if a thousand clients failed at the same moment, they all retry at the same moments. Jitter breaks that pattern.
AWS's well-known analysis compares three variants. Full jitter: sleep a random time between 0 and the capped backoff, which spreads retries most and does the least total work. Equal jitter: keep half the backoff and randomise the other half, which guarantees some minimum wait. Decorrelated jitter: each sleep is random between the base and three times the previous sleep, capped, which also spreads well.
In practice, full jitter with a cap is a solid default. AWS SDKs, gRPC retry policies and libraries like Python's tenacity already implement backoff with jitter, so prefer them over hand-written loops.
Idempotency keys in depth
Some operations are naturally idempotent: setting a value (PUT), deleting by ID, or a conditional update like UPDATE ... WHERE version = 7. Others, like creating a payment, are not, so you add an idempotency key: a unique ID the client generates (a UUID) and sends with the request, for example in an Idempotency-Key header.
The server stores the key before doing the work, with a state of in progress, then saves the final response. A repeat with the same key gets the saved response instead of a second charge. Edge cases matter. A repeat that arrives while the first is still running should get a conflict (Stripe returns 409) rather than run in parallel. A repeat with the same key but a different body is a client bug and should be rejected. Keys expire after a window, for example 24 hours, so storage does not grow forever.
- 1Request with key
Idempotency-Key: 7f3c...
- 2Insert key if new
Unique constraint; state = in progress
- 3Key exists?
Done: return saved response; running: 409
- 4Do the work once
Charge card, create order
- 5Save response
State = done, expires in 24 h
Stopping retry storms
Retries multiply. If a page calls service A, which calls B, which calls C, and every layer tries 3 times, one failure at C can produce 3 x 3 x 3 = 27 calls. When C is overloaded, this is exactly the wrong moment to send it 27 times more traffic.
Rules that prevent storms: retry at one layer only, usually the one closest to the failure or the client edge. Use a retry budget: allow retries to add at most about 10% extra traffic, and stop retrying when the budget is used up. AWS SDKs do something similar in standard retry mode with a retry token bucket. Combine retries with a circuit breaker, so when a dependency is clearly down, callers stop trying for a while. Finally, servers should shed load with a fast 503 or 429 plus Retry-After, which tells well-behaved clients exactly when to come back.
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Set sensible timeouts~30m
- 2Retry with exponential backoff and jitter~30m
- 3Make APIs idempotent with keys~30m
- 4Avoid retry storms~30m
Key points
- Always set timeouts; a call without one can hang forever.
- Retry only transient errors like timeouts, 503 and 429, never 400.
- Exponential backoff with jitter prevents synchronized retry waves.
- Retrying at every layer multiplies traffic; retry at one layer only.
- Idempotency keys make non-idempotent writes like payments safe to retry.
Key terms
Tap a card to flip it. 0/5 known
Examples
def call_with_retry(fn, max_attempts=5, base=0.1, cap=5.0):
for attempt in range(max_attempts):
try:
return fn(timeout=2.0)
except (Timeout, ServiceUnavailable):
if attempt == max_attempts - 1:
raise
delay = min(cap, base * 2 ** attempt)
time.sleep(random.uniform(0, delay)) # full jitterCapped exponential backoff with full jitter.
Retries with tenacity in Python
A service calls a partner API that sometimes returns 503. Step 1: set a short connect timeout and a read timeout based on the partner's p99. Step 2: retry only on timeouts, connection errors and retryable status codes. Step 3: use exponential backoff with random jitter, capped at 10 seconds, and stop after 4 attempts. Step 4: send an idempotency key so a retried POST cannot create a duplicate. The same key is reused on every attempt because it is created once outside the retried function.
import uuid, requests
from tenacity import retry, stop_after_attempt, wait_random_exponential, retry_if_exception_type
class Retryable(Exception): pass
@retry(retry=retry_if_exception_type((Retryable, requests.ConnectionError, requests.Timeout)),
wait=wait_random_exponential(multiplier=0.2, max=10), stop=stop_after_attempt(4))
def create_payment(body, key):
r = requests.post("https://api.example.com/payments", json=body,
headers={"Idempotency-Key": key}, timeout=(1, 3))
if r.status_code in (429, 502, 503, 504):
raise Retryable(r.status_code)
r.raise_for_status()
return r.json()
create_payment({"amount": 1299}, str(uuid.uuid4()))Storing idempotency keys in PostgreSQL
Step 1: create a table with the key as primary key. Step 2: at the start of the request, try to insert the key; ON CONFLICT DO NOTHING tells you whether it was new. Step 3: if the insert returned nothing, the key exists: read its status and either return the stored response or a 409 if still processing. Step 4: after the work, store the response. Step 5: a nightly job deletes keys older than 24 hours.
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
request_hash text NOT NULL,
status text NOT NULL DEFAULT 'processing',
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO idempotency_keys (key, request_hash)
VALUES ('7f3c9a1e', 'sha256-of-body')
ON CONFLICT (key) DO NOTHING
RETURNING key; -- no row returned means: seen beforeQuick reference
- Always set both a connect timeout and a request timeout
- Request timeout: a little above the dependency's p99 latency, and below the caller's deadline
- Retry 429, 502, 503, 504, resets and timeouts; never 400, 401, 403, 404, 422
- Honour Retry-After on 429 and 503 responses
- Full jitter: sleep = random(0, min(cap, base x 2^attempt))
- 3 retries at 3 layers = up to 27 calls; retry at one layer only
- Retry budget: retries may add at most about 10% to normal traffic
- Idempotency key: client-generated UUID, stored with the response, expires after about 24 h
Common mistakes
- Retrying non-idempotent POSTs without a key, causing duplicates.
- Nested retries: 3 retries in 3 layers means up to 27 calls.
- Timeouts longer than the caller's own timeout.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
With base = 100 ms, cap = 2 s and no jitter, list the backoff before each of 6 retries. Then say the range of the 4th wait with full jitter.
- Exercise 2medium
Write a Python function retry_call(fn, attempts=4, base=0.1, cap=5) that retries only on TimeoutError and ConnectionError, uses full jitter, and re-raises after the last attempt.
- Exercise 3hard
Design a retry budget: clients may retry only while retries stay under 10% of successful requests. Write the core logic as pseudocode.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How many times should I retry?
- Usually 2 to 4 attempts in total is enough to ride out brief hiccups. More attempts rarely help and add load and delay when a service is really down.
- Is POST ever idempotent?
- Not by default, but you can make it so with an idempotency key or a unique client-supplied ID, so the server recognises and ignores repeats.
- What is the difference between a timeout and a deadline?
- A timeout is a duration for one call, like 500 ms. A deadline is an absolute point in time for the whole request, passed down so every service knows how much time is left.