Sub topic 5
Retries with Exponential Backoff and Jitter
This chapter assumes you can write a service that calls other services over a network, you know how exceptions work, and you have already seen timeouts (the previous chapter). Here you will learn when a retry helps, how to space retries out, and how retries can make an outage worse.
Why retry at all
Many dependency failures are brief. A connection resets, a server restarts, or a load balancer shifts traffic. If you try the same call again a moment later, it often succeeds. A retry hides these short faults from the user, so it is the cheapest form of resilience.
A retry is not a cure for every failure. If the dependency is down for minutes, retrying only adds load and delay. The rest of this chapter is about telling those cases apart and limiting the damage when you guess wrong.
What is safe to retry
Retry only when both of these are true:
- The error is transient. Timeouts, connection errors, and HTTP 503 or 429 responses may pass. An HTTP 400 or 404 will fail the same way every time, so retrying wastes effort.
- The operation is idempotent. An idempotent operation has the same effect whether it runs once or several times. Reading a record is idempotent. Charging a card is not, unless you send an idempotency key that lets the server detect duplicates.
A timeout is a tricky case. The request may have reached the server and even succeeded, but the reply was lost. If the call is not idempotent, a retry can run it twice.
Exponential backoff
If you retry immediately, you hit a struggling service at the moment it is least able to cope. Backoff means waiting between attempts. Exponential backoff doubles the wait each time, so the delays with a base of 0.1 seconds are 0.1, 0.2, 0.4, 0.8, and so on. You also set a cap, a maximum delay, so the wait does not grow without limit.
Why you also need jitter
Suppose 1,000 clients all fail at the same instant and all use the same backoff. They all retry at 0.1 seconds, then all at 0.2 seconds. The dependency receives a synchronized wave of traffic every time it tries to recover. Jitter adds randomness to each delay so the retries spread out over time.
The "full jitter" approach picks a random delay between zero and the exponential limit. This code is from the topic's examples:
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)Read it step by step:
- The loop makes at most
attemptscalls in total. - Only
TimeoutErrorandConnectionErrorare retried. Any other exception, such as a bug in your code, propagates immediately. - On the last attempt the exception is re-raised, so the caller still learns about the failure.
base * 2 ** attemptis the exponential limit.min(cap, ...)applies the cap.random.uniform(0, limit)is the full jitter.
Retry storms
A retry storm happens when retries multiply the load on a dependency that is already overloaded. Suppose each request makes up to 3 attempts. When the dependency fails, your traffic to it becomes up to three times larger, which pushes it further down. If several layers each retry three times, the multiplier compounds: three layers of 3 attempts mean up to 27 calls for one user request.
Ways to limit this:
- Keep attempts low. Two or three is usual.
- Retry at one layer only. Pick the layer closest to the call and let the others pass errors upward.
- Use a retry budget. Allow retries only up to a fraction of normal traffic, for example 10 percent of requests.
- Respect the overall deadline. Retries plus waits must fit inside the time the user is willing to wait. If a page must answer in 2 seconds, three attempts with a 1-second timeout each do not fit.
- Stop when the dependency is clearly unhealthy. That is the job of the circuit breaker, covered in the next chapter.
Retries and fallbacks together
Retries come before the fallback. The sequence is: call with a timeout, retry a small number of times with jittered backoff, and only then serve the fallback (cached data, a default, or a simplified result). The retries are a short effort to get the real answer. The fallback is what the user sees when that effort fails.
You can combine the two functions from this tutorial by passing a call into call_with_retry and catching its final error:
def get_with_fallback(fetch, fallback):
try:
return call_with_retry(fetch)
except (TimeoutError, ConnectionError):
return fallback()Common errors
- Retrying non-idempotent writes without an idempotency key.
- Retrying on every exception, including programming errors and client errors.
- Using backoff without jitter.
- Retrying at several layers of the stack at once.
- Ignoring the total time budget, so the user waits longer than the timeout you designed.
Exercise
A checkout service calls a payment API with a 1-second timeout and retries 3 times with exponential backoff and jitter. The page must respond within 2 seconds. The payment API is overloaded. Name two problems with this setup and one fix for each.
Show answer
First, the time budget does not fit: 3 attempts of up to 1 second each plus waits can exceed 2 seconds. Fix it by reducing attempts or the per-call timeout so the worst case stays under 2 seconds. Second, retries add up to three times the load to an already overloaded API, and a payment call is not idempotent so a retry after a lost reply could charge twice. Fix it by sending an idempotency key with each payment request and by limiting retries with a retry budget or a circuit breaker.
Exercise
Why does full jitter use random.uniform(0, limit) instead of simply adding a small random amount to a fixed delay?
Show answer
Choosing a value anywhere between zero and the limit spreads clients across the whole interval, so their retries do not cluster. Adding a small random amount to a shared fixed delay leaves most clients bunched near the same moment.