Retries Done Right: Exponential Backoff, Jitter, and Retry Budgets
A retry loop can turn a brief outage into a long one. How exponential backoff and jitter spread retries out, why retries multiply across layers, and a tested Python helper with Retry-After support and a retry budget.
Retrying a failed request is the most natural reliability fix there is. A network blip, a deploy that briefly drops connections, a database failover: try again a moment later and the call usually succeeds. The same habit is also one of the most common ways a short incident becomes a long one. When thousands of clients retry at the same moments, the recovering service is hit by synchronized waves of traffic, and every layer that retries multiplies the load. This guide covers how to retry so that it helps rather than hurts: exponential backoff, jitter, deciding what is safe to retry, honoring Retry-After, and capping retries with a budget.
The short version
- Retry only failures that can plausibly succeed later, such as timeouts, 429, 502, 503 and 504, and only operations that are safe to repeat.
- Wait longer after each failure, usually doubling the delay up to a cap. That is exponential backoff.
- Randomize each delay. That is jitter, and without it clients that failed together retry together.
- Limit retries per call and across all calls, so retries cannot multiply load during an outage.
- Retry at one layer of the stack, not at every layer.
Why fixed-interval retries make outages worse
Imagine a service that falls over for a few seconds. Every client that was calling it sees an error at roughly the same instant. If each client waits exactly one second and tries again, every client returns at exactly the same instant one second later. The service, which might have recovered with normal load, instead receives a spike of all the original traffic plus all the retries at once. It fails again, and the cycle repeats. This is often called a retry storm or thundering herd, and it can keep a service down long after the original cause is gone.
Exponential backoff helps by slowing clients down: a typical schedule waits 100 ms, then 200 ms, then 400 ms, and so on, up to a maximum. That reduces how often each client tries, which gives the service room to recover. On its own, though, backoff does not break the synchronization. Clients that failed together still follow the same schedule and still arrive together, only less frequently.
Jitter: the part that actually spreads the load
Jitter adds randomness to each delay so that clients drift apart. In a widely cited 2015 post on the AWS Architecture Blog, Marc Brooker simulated contending clients and compared several variants. The two that come up most often are these:
- Full jitter: sleep a random time between zero and the exponential delay, so sleep = random(0, min(cap, base * 2^attempt)).
- Equal jitter: keep half of the exponential delay and randomize the other half, which avoids very short sleeps but spreads clients less.
His simulations found that every jittered approach beat plain exponential backoff, which did more work and took longer, and that full jitter did the least work of the variants tested. That is why full jitter is the common default. Not every system uses it: gRPC's built-in retry policy multiplies each backoff by a random factor between 0.8 and 1.2, a smaller plus or minus 20 percent jitter. What matters most is that some randomness is present.
Worked example: 1,000 clients after a blip
To make the difference concrete, the small simulation below has 1,000 clients fail at the same moment and each retry four times, with a 100 ms base delay that doubles each attempt. It then counts the busiest 10 ms window the service sees across the retry waves.
import random
from collections import Counter
def peak_per_10ms(strategy, clients=1000, attempts=5, base=0.1, cap=10.0, seed=7):
rng = random.Random(seed)
buckets = Counter()
for _ in range(clients):
t = 0.0
for a in range(attempts - 1):
ceiling = min(cap, base * 2 ** a)
if strategy == "none":
d = ceiling
elif strategy == "full":
d = rng.uniform(0, ceiling)
else: # "equal"
d = ceiling / 2 + rng.uniform(0, ceiling / 2)
t += d
buckets[int(t * 100)] += 1
return max(buckets.values()), sum(buckets.values())
for s in ("none", "equal", "full"):
peak, total = peak_per_10ms(s)
print(f"{s:6s} peak in any 10 ms: {peak:5d} total retries: {total}")
With no jitter, all 1,000 retries of each wave land in the same 10 ms window. With equal jitter, the busiest window drops to 216, and with full jitter to 157, roughly a sixfold reduction in peak load. The total number of retries is 4,000 in every case. Jitter does not reduce how much retry traffic there is; it only spreads it out. Reducing the amount takes the limits described next.
Decide what is safe to retry
Backoff answers when to retry. The more important question is whether to retry at all. Two checks come first.
- Can the error plausibly go away? Timeouts, connection resets, 408, 429, 502, 503 and 504 often do. A 400, 401, 403 or 404 for the same request will usually fail the same way again, so retrying only adds load. AWS's Builders' Library guidance makes the same split between client and server errors, with the caveat that eventual consistency can occasionally turn a client error into a later success.
- Is the operation safe to repeat? A read is. A payment, an order or an email send is not, unless the API is idempotent, for example by accepting an idempotency key so that a repeated request returns the original result instead of acting twice. When a request times out, the client cannot tell whether the server did the work, so a non-idempotent call should not be retried blindly.
Honor Retry-After
Sometimes the server knows exactly how long to wait. HTTP defines a Retry-After response header, commonly sent with 503 Service Unavailable and 429 Too Many Requests, whose value is either a number of seconds or an HTTP date. A client that receives it should wait at least that long instead of using its own shorter backoff. gRPC has an equivalent: a server can send the grpc-retry-pushback-ms trailer to tell the client how many milliseconds to wait, or a negative value to tell it not to retry at all.
Retries multiply across layers
Retry logic tends to appear everywhere: in the SDK, in a service client, in the service that calls that client, and in the frontend above it. Each layer seems reasonable alone. Together they multiply. AWS's Builders' Library article on timeouts and retries gives the example of a five-layer call stack where each layer tries three times: a failing database at the bottom could see 3 to the power of 5, or 243 times, its normal load. The guidance is to retry at a single point in the stack and let the other layers fail fast.
The second safeguard is a retry budget, a limit on retries across all calls rather than per call. A common design is a token bucket: successful calls slowly add tokens, each retry spends one, and when the bucket is empty failures are returned immediately instead of retried. During normal operation, the occasional failure is retried freely. During a real outage, when most calls fail, the bucket drains quickly and the client stops adding retry traffic. The AWS SDKs added this kind of local token bucket in 2016, and gRPC's retry throttling works the same way: each failure costs one token, each success returns a configurable fraction of one, and retries stop when the count falls to half of the maximum or lower.
A retry helper that does all of this
The helper below combines the pieces: a fixed set of retryable statuses, a skip for non-idempotent calls, full-jitter backoff, Retry-After in its seconds form, a per-call attempt limit and a shared token-bucket budget. The send function is injected so the logic can be tested without a network; in production it would wrap your HTTP client and map timeouts to a retryable status.
import random
import time
RETRYABLE = {408, 429, 500, 502, 503, 504}
class RetryBudget:
"""Token bucket shared by all calls to one dependency."""
def __init__(self, max_tokens=10.0, refill_per_success=0.1):
self.max_tokens = max_tokens
self.tokens = max_tokens
self.refill = refill_per_success
def on_success(self):
self.tokens = min(self.max_tokens, self.tokens + self.refill)
def try_spend(self):
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def full_jitter(attempt, base=0.1, cap=10.0):
return random.uniform(0, min(cap, base * 2 ** attempt))
def call_with_retries(send, budget, max_attempts=4, idempotent=True, sleep=time.sleep):
"""send() returns (status, headers). Returns the last (status, headers)."""
for attempt in range(max_attempts):
status, headers = send()
if status < 400:
budget.on_success()
return status, headers
last_try = attempt == max_attempts - 1
if not idempotent or status not in RETRYABLE or last_try:
return status, headers
if not budget.try_spend():
return status, headers # budget exhausted: fail fast
delay = full_jitter(attempt)
retry_after = headers.get("Retry-After", "")
if retry_after.isdigit(): # seconds form; HTTP-date form omitted here
delay = max(delay, float(retry_after))
sleep(delay)
return status, headers
if __name__ == "__main__":
# A dependency that fails twice with 503, then recovers.
responses = iter([(503, {}), (503, {"Retry-After": "1"}), (200, {})])
waits = []
result = call_with_retries(lambda: next(responses), RetryBudget(), sleep=waits.append)
print("result:", result[0])
print("waited:", [round(w, 3) for w in waits])
Running it prints a final status of 200 after two waits: a short random one from full jitter, then exactly one second because the second response carried Retry-After: 1. Passing a fake sleep function is also how to unit-test retry code without making the test suite slow.
Timeouts come first
A retry policy is only as good as the timeout in front of it. Without a timeout, a hung call never fails, so it is never retried, and the caller's threads or connections pile up. AWS's guidance is to pick an acceptable rate of false timeouts, say 0.1 percent, and set the timeout at the matching percentile of the dependency's latency, here p99.9. Also keep an overall deadline for the whole operation, including all retries, so that a user-facing request does not spend thirty seconds politely backing off.
Checklist
- Every remote call has a timeout, and the operation has an overall deadline.
- Only transient errors are retried, and only for idempotent operations or requests with an idempotency key.
- Delays grow exponentially up to a cap and include jitter.
- Retry-After and gRPC pushback override the client's own schedule.
- Attempts are capped per call, and a shared retry budget caps them across calls.
- Exactly one layer of the stack owns retries for a given dependency.
- Retries are visible in metrics, so a rising retry rate shows up before it becomes an outage.
Retries are easy to add and easy to get subtly wrong. The good version is not much more code than the naive loop: randomize the wait, respect what the server tells you, stop when the dependency is clearly down, and keep retries in one place. That turns retries from a source of retry storms into a quiet mechanism that absorbs the small failures every distributed system has.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter