Sub topic 5
Retries with Exponential Backoff and Jitter
This chapter assumes you know how to call a remote service from code and handle its exceptions. It also assumes you have read the chapter on timeouts, because retries only make sense once each attempt has a bounded cost.
Why retries help and why they hurt
Many failures between services are transient. A connection is reset, a load balancer drops one request during a deploy, or a database fails over and answers again two seconds later. If the caller tries once more, the user never sees the problem. A retry turns a short, random failure into a slightly slower success.
Retries also add load. When a dependency is slow because it is overloaded, every retry adds work to a service that is already struggling. If thousands of clients all retry on the same schedule, the retries can keep the dependency down after the original problem is gone. This pattern is called a retry storm.
Retry design is therefore two decisions. The first is when a retry is worth attempting. The second is how to keep retries from becoming the main source of load.
Deciding what to retry
Not every failure deserves another attempt. Sort errors into three groups before writing any retry code.
| Error type | Examples | Retry? |
|---|---|---|
| Transient, likely to clear | Connection reset, timeout, HTTP 503, HTTP 429 with a wait hint | Yes, with backoff |
| Permanent, caused by the request | HTTP 400, 401, 403, 404, validation errors | No. The same request fails the same way. |
| Ambiguous outcome | Timeout after a payment request was sent | Only if the operation is idempotent |
An operation is idempotent if running it twice has the same effect as running it once. Reading a record is idempotent. Setting a field to a fixed value usually is. "Charge the card" is not. When a timeout occurs, you do not know whether the server did the work and the response was lost, or never received the request. Retrying a non-idempotent call can charge a customer twice.
There are two common ways to make writes safe to retry:
- Send an idempotency key, a unique identifier the client generates once per logical operation. The server stores the result under that key and returns it again if the same key arrives a second time.
- Design the operation as a "set to this value" instead of "add this amount".
The code in this chapter catches only TimeoutError and ConnectionError. This is deliberate. A catch-all except Exception would retry programming bugs and validation failures, which wastes time and hides defects.
Exponential backoff
If a retry happens immediately, it usually meets the same condition that caused the first failure. Waiting before the next attempt gives the dependency time to recover. Exponential backoff increases the wait after each failure, usually by doubling it.
With a base delay of 0.1 seconds and a cap of 2 seconds, the upper bound of the wait grows like this:
| Failed attempts so far | Formula `base * 2 ** n` | Upper bound after cap |
|---|---|---|
| 1 | 0.1 | 0.1 s |
| 2 | 0.2 | 0.2 s |
| 3 | 0.4 | 0.4 s |
| 4 | 0.8 | 0.8 s |
| 5 | 1.6 | 1.6 s |
| 6 | 3.2 | 2.0 s |
The cap matters. Without it, a long run of failures produces waits of minutes, and your own request has long since been abandoned by the user or by an upstream timeout. Choose the cap from the latency your caller can tolerate, not from what feels polite to the dependency.
Doubling is a convention, not a law. A factor of 1.5 or 3 behaves the same way. What matters is that the interval grows and is bounded.
Why backoff alone is not enough: jitter
Suppose a dependency fails at 12:00:00 and 5,000 clients all see the error. With plain exponential backoff, every client retries at exactly 12:00:00.1, then 12:00:00.3, then 12:00:00.7. The retries arrive in synchronized waves. Each wave hits the recovering service with the full client population at once, and the waves are as damaging as the original spike.
Jitter adds randomness to the delay so that clients spread out. The retry load is then smeared across the interval instead of arriving in spikes.
There are several common variants.
| Strategy | Delay formula | Behavior |
|---|---|---|
| No jitter | `min(cap, base * 2**n)` | Synchronized waves |
| Full jitter | `random(0, min(cap, base * 2**n))` | Widest spread, lowest total load |
| Equal jitter | `d/2 + random(0, d/2)` where `d = min(cap, base * 2**n)` | Guarantees a minimum wait, less spread |
| Decorrelated jitter | `min(cap, random(base, previous * 3))` | Each delay depends on the last one |
Full jitter is a good default. Its main cost is that a delay can be very close to zero, so one client may retry almost immediately. That is acceptable because the other clients are spread across the whole interval. If you need a guaranteed minimum pause, use equal jitter.
A working implementation
This is the retry function used throughout the tutorial. It uses full jitter, caps the delay, and re-raises the last error so the caller can decide what to do next, for example by using a fallback.
import random
import time
def call_with_retry(fn, attempts=3, base=0.1, cap=2.0):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(delay)Three details are worth noting:
attemptscounts total tries, not retries.attempts=3means one initial call and at most two retries.- The function does not sleep after the final failure. It raises immediately, which keeps the failure path fast.
- Exceptions not in the
excepttuple propagate at once, with no retry.
You can run the function against a simulated flaky dependency to see it work:
import random
import time
def call_with_retry(fn, attempts=3, base=0.1, cap=2.0):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(delay)
calls = {"count": 0}
def flaky():
calls["count"] += 1
if calls["count"] < 3:
raise ConnectionError("connection reset")
return "ok"
start = time.monotonic()
result = call_with_retry(flaky, attempts=4)
elapsed = time.monotonic() - start
print(result, "after", calls["count"], "calls in", round(elapsed, 2), "seconds")The function fails twice and succeeds on the third call. Elapsed time is random but never exceeds 0.1 + 0.2 = 0.3 seconds of waiting, plus the calls themselves.
Retries must fit inside a deadline
Each attempt costs up to one timeout. Three attempts with a 0.5-second timeout and backoff in between can take over 1.5 seconds. If the caller of your service gives up after 1 second, every attempt after that point is wasted work, and the dependency does it for no one.
The fix is a deadline: an absolute time by which the whole operation must finish. Before sleeping, check whether the delay would pass the deadline, and stop if so.
import random
import time
def call_with_retry(fn, attempts=3, base=0.1, cap=2.0, deadline=None):
for attempt in range(attempts):
try:
return fn()
except (TimeoutError, ConnectionError):
if attempt == attempts - 1:
raise
delay = random.uniform(0, min(cap, base * 2 ** attempt))
if deadline is not None and time.monotonic() + delay >= deadline:
raise
time.sleep(delay)Callers pass deadline=time.monotonic() + 1.0 to say "this must be done within one second". Use time.monotonic() and not time.time(). The wall clock can jump when the system clock is adjusted, which would make the deadline unreliable.
Retry amplification across layers
Retries multiply when services call each other in a chain. Suppose service A calls B, B calls C, and C calls a database. If each layer makes up to 3 attempts, one failing database call can produce 3 × 3 × 3 = 27 database calls from a single user request. The database receives its worst traffic at exactly the moment it is least able to handle it.
Two practices limit this:
- Retry at one layer only, usually the layer closest to the user or the one that knows the operation is idempotent. Lower layers fail fast and report the error.
- Use a retry budget. This is a limit on retries as a fraction of total traffic, for example "retries may add at most 10% to the request rate". When the budget runs out, failed calls are not retried and the error goes straight to the fallback.
Here is a minimal budget. Each normal request adds a fraction of a token, and each retry spends a whole token.
class RetryBudget:
def __init__(self, ratio=0.1, max_tokens=10.0):
self.ratio = ratio
self.max_tokens = max_tokens
self.tokens = max_tokens
def record_request(self):
self.tokens = min(self.max_tokens, self.tokens + self.ratio)
def try_spend(self):
if self.tokens >= 1.0:
self.tokens -= 1.0
return True
return FalseWith ratio=0.1, roughly one retry is allowed for every ten requests in steady state. During a full outage, the stored tokens drain after about ten retries, and from then on the service stops adding retry load. Like the circuit breaker sketch in this tutorial, this class is not thread-safe. In a real service, protect the counter with a lock or use an atomic primitive.
Respecting server hints
Some responses tell you when to retry. HTTP 429 (Too Many Requests) and 503 (Service Unavailable) may include a Retry-After header with a number of seconds or a date. If the server provides one, wait at least that long. Your own backoff calculation is a guess, and the server's hint is better information. Take the larger of the two values, and still apply the cap and your deadline.
How retries fit with the other patterns
Retries, timeouts, circuit breakers, and fallbacks each handle a different part of the problem:
- A timeout bounds how long one attempt can take. Retries without timeouts can hang indefinitely.
- A retry handles short blips. It is the wrong tool for a dependency that is down for minutes.
- A circuit breaker handles the sustained case. After repeated failures it stops calls entirely, so retries are not attempted against a dependency known to be down. Put the breaker check inside or around the retry loop so an open breaker ends the retries at once.
- A fallback is what the caller does after the retries are exhausted. The final
raiseincall_with_retryis the signal that tells the caller to switch to cached data or a default.
def get_with_fallback(fetch, fallback):
try:
return call_with_retry(fetch, attempts=3)
except (TimeoutError, ConnectionError):
return fallback()Common errors
- Retrying without jitter. The code looks correct in a test with one client and fails in production with thousands.
- Retrying non-idempotent operations. Duplicate charges, duplicate emails, and double-counted events come from this.
- Retrying permanent errors. A 404 or a validation failure will never succeed, and retrying only delays the error.
- No cap and no attempt limit. Retrying forever turns a failure into a hang.
- Retries at every layer. The multiplication described above can take down a dependency that was only slightly slow.
- Ignoring the deadline. The work finishes after nobody is waiting for it.
- Sleeping on the final failure. This adds delay before an error that is going to happen anyway.
- Hiding retries from observability. If retries succeed silently, you will not notice that the dependency is failing 30% of the time until it fails 100%. Count retries and log the final failure. A later chapter covers this in detail.
Exercises
Exercise
A service calls a dependency with callwithretry(attempts=5, base=0.2, cap=1.0) using full jitter. What is the largest possible total time spent sleeping if all five attempts fail, ignoring the time the calls themselves take?
Show answer
The function sleeps after attempts 1 to 4 (indexes 0 to 3) and raises without sleeping after the fifth. The upper bounds are min(1.0, 0.2) = 0.2, min(1.0, 0.4) = 0.4, min(1.0, 0.8) = 0.8, and min(1.0, 1.6) = 1.0. The total is 0.2 + 0.4 + 0.8 + 1.0 = 2.4 seconds. Because full jitter picks a random value up to each bound, the expected sleep is about half of that, or 1.2 seconds.
Exercise
Service A retries up to 3 times against service B, and B retries up to 3 times against a database. The database is failing. How many database calls can one request to A cause, and what is one change that reduces this number?
Show answer
Up to 3 × 3 = 9 database calls, because each of A's attempts can trigger up to 3 attempts from B. Retrying at only one layer (for example in A, with B failing fast) reduces this to 3. A retry budget at each layer is another valid answer, because it caps retries as a share of traffic during an outage.