Retries
medium 30 minA retry repeats a failed call in the hope that the problem was short.
See it run
Wait, randomise, repeat safely, and know when to stop.
Operations
One call, two retries
At most 5 attempts, base 1 second, with a random part.
Step 1 of 5
Attempt 1
| Attempt | Starts | Result | Then wait |
|---|---|---|---|
| 1 | 0.00 s | failed | |
The connection is refused. That is temporary, and nothing was processed.
Step 1: Attempt 1
for attempt in range(1, max_attempts + 1): try: return call() except Temporary: if attempt == max_attempts: raise sleep(wait(attempt))- Good for
- Short failures
- Costs
- Delay, extra load
- No retry
- the first glitch is an error
If 30% of attempts succeed, five independent attempts succeed in 83% of cases: 1 - 0.7^5.
In the real world
The same retries doing real jobs. Pick one and step through it.
A chat server restarts. Everybody notices in the same second.
Step 1 of 3
Connection lost
- New connections a second
- 0
In step
50,000 phones lose their connection at the same moment.
Step 1: Connection lost
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Retrying every error
majorA validation error fails the same way five times. The old defaults did this.
Wrongexcept Exception: retry()Rightexcept (ConnectionError, Temporary): retry()No key on a write
criticalThe first attempt may have worked.
Wrongpost("/payments", body)Rightpost("/payments", body, headers={"Idempotency-Key": order.key})Jitter lost at the cap
majorBeyond the cap every client waits exactly the same again.
Wrongmin(cap, delay + uniform(0, delay / 2))Rightuniform(0, min(cap, delay))Retries in every layer
criticalAttempts multiply, and an overload keeps itself alive.
Wronggateway: 4, orders: 4 # 16 callsRightgateway: 1, orders: 3, budget 10%
Interview tips
How to explain it
- Short failures: try again.
- Random and growing waits.
- One layer, a few attempts, a budget.
Memory trick: RETRY
- Retryable, Exponential.
- Time limit and maximum, Randomize.
- Yield: succeed or fail gracefully.
Ask before each retry
- Temporary?
- Safe?
- Time and budget left?
After the last attempt
- A page: fallback or honest error.
- A job: dead letter queue.
- Always: a log line and a count.