Lesson 1.7 · 7 of 7 · 6 min read · Reviewed 24 Nov 2026
Retries with exponential backoff and jitter
By the end, you can
- Decide which failures are worth retrying.
- Compute an exponential backoff schedule with jitter and a cap, and honour retry-after.
Model APIs fail in ordinary ways: you hit a rate limitRate limit: A cap on how many requests or tokens you can use in a period, such as per minute., the provider is briefly overloaded, a connection drops. Most of these fix themselves within seconds. A good retry policy turns them into a short delay instead of an error for the user.
Step 1: decide what is retryable
| Failure | Retry? | Why |
|---|---|---|
| 429 rate limited | Yes | Capacity frees up over time |
| 500, 502, 503, overload errors | Yes | Usually transient on the provider side |
| Timeout, connection reset | Yes, carefully | The request may or may not have been processed |
| 400 bad request, 413 too large | No | The same request fails again |
| 401, 403 | No | Fix the key or permissions |
Step 2: back off exponentially
Waiting the same short time between attempts hammers a service that is already struggling. Exponential backoffExponential backoff: Waiting longer after each failed retry, for example 1, 2, 4 then 8 seconds. doubles the wait each time:
delay(attempt) = min(cap, base * 2 ** attempt)
base = 1 s, cap = 30 s -> 1, 2, 4, 8, 16, 30, 30 ...
Stop after a fixed number of attempts (four or five is common) or a total time budget, then report the failure.
Step 3: add jitter
If a thousand clients all failed at the same moment, they all retry at 1 s, then all at 2 s, then all at 4 s. Each retry wave is a spike. JitterJitter: Randomness added to retry delays so clients do not all retry at the same instant. randomises the wait. The simplest effective version, often called full jitter, picks a random delay between zero and the backoff value:
import random
def backoff_delay(attempt: int, base: float = 1.0, cap: float = 30.0, rng=random) -> float:
return rng.uniform(0, min(cap, base * 2 ** attempt))
The average wait halves, and the retries spread out evenly instead of arriving together.
Step 4: honour retry-after
Many APIs send a retry-after header with a 429429 error: The HTTP status for too many requests: you hit a rate limit. or 503: the number of seconds to wait. Use it when it is there, as the minimum delay. It reflects the server’s actual state, which your formula can only guess.
A worked example
for attempt in range(5):
try:
return call_model()
except RetryableError as err:
if attempt == 4:
raise
wait = err.retry_after or backoff_delay(attempt)
time.sleep(wait)
Most model SDKs already retry a couple of times with backoff. Know your SDK’s default (often a max_retries setting) so you do not stack your own loop on top and multiply the attempts.
Retries and side effects
Retrying a model call is usually safe: at worst you pay for a second generation. Retrying a tool that sends an email or charges a card is not. For those, use an idempotency keyIdempotency key: A unique id sent with a write request so the server can ignore duplicate retries of the same request., a unique id sent with the request so the server can ignore duplicates, or check whether the first attempt succeeded before trying again.
Common mistakes
- Retrying 400s, which burns quota and hides the real bug.
- No cap, so one request can wait for minutes.
- Retrying at several layers (SDK, your code, a queue), turning 3 attempts into 27.
- Backoff without jitter in a large fleet of workers.
Key points
- Retry only transient failures: 429, 5xx, overload errors, timeouts and dropped connections. Never retry a 400 or 401 unchanged.
- Exponential backoff doubles the wait each attempt: 1, 2, 4, 8 seconds, up to a cap and a maximum number of attempts.
- Jitter makes each client wait a random part of that delay, so a crowd of clients does not retry in the same instant.
- If the server sends retry-after, wait at least that long. It knows more than your formula does.
Retry a flaky call with jitter
Retry only transient failures with full-jitter exponential backoff, honour retry-after, and see why jitter matters.
You will have: A with_retries function with a simulated clock, plus a comparison of retry timing for 1,000 clients with and without jitter.
Steps
- Write backoff_delay with full jitter: a random wait between 0 and min(cap, base x 2 to the power attempt).
- In with_retries, re-raise at once for status codes that are not retryable.
- Use retry_after when the error carries one; otherwise use the backoff delay.
- Add each wait to a simulated clock instead of sleeping, and print the total.
- Compare how many of 1,000 clients retry in the same 0.1 s with and without jitter.
Done when
- The flaky call succeeds on attempt 4 after two overload errors and a 429.
- The 400 error is not retried.
- Without jitter all 1,000 clients retry at once; with jitter far fewer share any 0.1 s window.
Open in the Playground No API key needed.
Starter code (Python)
import random
class APIError(Exception):
def __init__(self, status, retry_after=None):
super().__init__(f"HTTP {status}")
self.status, self.retry_after = status, retry_after
def flaky(script):
"""A fake API that fails in the order given by script, then succeeds."""
calls = iter(script)
def call():
step = next(calls, None)
if step is None:
return "ok"
raise APIError(*step)
return call
RETRYABLE = {429, 500, 502, 503, 529}
def backoff_delay(attempt, rng, base=1.0, cap=8.0):
# TODO: return a full-jitter delay: a random value between 0 and min(cap, base * 2 ** attempt)
return 1.0
def with_retries(call, rng, max_attempts=5):
# TODO: try call() up to max_attempts times
# TODO: re-raise at once if err.status is not in RETRYABLE
# TODO: wait err.retry_after if set, else backoff_delay(attempt, rng); add it to a simulated clock
return call()
rng = random.Random(7)
try:
print(with_retries(flaky([(529,), (503,), (429, 5)]), rng))
except APIError as err:
print("failed with", err)
Show a solution
import random
class APIError(Exception):
def __init__(self, status, retry_after=None):
super().__init__(f"HTTP {status}")
self.status, self.retry_after = status, retry_after
def flaky(script):
"""A fake API that fails in the order given by script, then succeeds."""
calls = iter(script)
def call():
step = next(calls, None)
if step is None:
return "ok"
raise APIError(*step)
return call
RETRYABLE = {429, 500, 502, 503, 529}
def backoff_delay(attempt, rng, base=1.0, cap=8.0):
return rng.uniform(0, min(cap, base * 2 ** attempt)) # full jitter
def with_retries(call, rng, max_attempts=5):
waited = 0.0 # a simulated clock: we add up the waits instead of sleeping
for attempt in range(max_attempts):
try:
result = call()
print(f" succeeded on attempt {attempt + 1}, waited {waited:.1f} s in total")
return result
except APIError as err:
if err.status not in RETRYABLE:
print(f" {err.status} not retried: fix the request")
raise
if attempt == max_attempts - 1:
print(" gave up after", max_attempts, "attempts")
raise
wait = err.retry_after if err.retry_after else backoff_delay(attempt, rng)
waited += wait
print(f" {err.status} on attempt {attempt + 1}: wait {wait:.2f} s" + (" (retry-after)" if err.retry_after else ""))
rng = random.Random(7)
print("overloaded, then rate limited with retry-after:")
with_retries(flaky([(529,), (503,), (429, 5)]), rng)
print("bad request:")
try:
with_retries(flaky([(400,)]), rng)
except APIError:
pass
# Why jitter: when do 1,000 clients send their first retry?
plain = [min(8.0, 1.0 * 2 ** 0) for _ in range(1000)]
jittered = [backoff_delay(0, rng) for _ in range(1000)]
print("without jitter, clients retrying in the same 0.1 s:", max(sum(1 for w in plain if abs(w - t / 10) < 0.05) for t in range(11)))
print("with jitter, at most", max(sum(1 for w in jittered if t / 10 <= w < (t + 1) / 10) for t in range(10)), "clients in any 0.1 s")
Finished the chapter? Take the chapter check.