Sub topic 10
Retries, backoff, jitter, and retry budgets
Retries are the client-side half of overload handling. A server that sheds load with a 429 or 503 is asking the caller to respond sensibly. A client that retries immediately and without limit turns that rejection into more load. This chapter covers how to retry safely.
It assumes you have read the earlier chapters on load shedding and client signals. You should also be comfortable with HTTP status codes and short Python async examples.
Why retries are dangerous during overload
A retry is a new request. When a service is slow because it is saturated, every timeout or rejection can produce another request. The extra requests arrive when the service has the least capacity to absorb them.
Suppose a service handles 1,000 requests per second and 30% of calls fail. If each client retries failed calls up to 3 times, the offered load rises from 1,000 to roughly 1,000 × (1 + 0.3 + 0.3² + 0.3³) ≈ 1,417 requests per second. More failures then follow, which produce more retries. This feedback loop is a retry storm. Even after the original trigger is gone, the extra load can keep the service down. Operators call that state a metastable failure.
Retries still matter. Many failures are brief: a dropped connection, a restarting instance, a momentary spike. The goal is to retry in a way that helps with brief failures and backs off when the failure is sustained.
Deciding what to retry
Retry only when all three of these hold:
- The failure is probably transient. Connection resets, timeouts, 429, 503, and 504 qualify. A 400, 401, 403, or 404 will fail the same way every time.
- The operation is safe to repeat. GET and PUT are idempotent by definition. A POST that charges a card is not, unless you attach an idempotency key so the server can detect duplicates.
- The caller still has time. If the deadline has passed, nobody is waiting for the answer, and a retry wastes capacity.
A timeout is ambiguous. The server may have finished the work and the response was lost. That is another reason idempotency matters.
Exponential backoff
Backoff means waiting before each retry, with the wait growing after every failure. With exponential backoff the wait doubles: 0.1 s, 0.2 s, 0.4 s, 0.8 s, and so on, up to a cap. The cap keeps a long outage from producing waits of minutes.
Backoff alone has a flaw. If 1,000 clients fail at the same instant, they all wait 0.1 s and retry together, then all wait 0.2 s and retry together again. The load arrives in synchronized waves.
Jitter
Jitter adds randomness to the delay so that clients spread out. The "full jitter" variant picks a uniformly random delay between zero and the current backoff ceiling:
import random
def backoff_delay(attempt: int, base: float = 0.1, cap: float = 10.0) -> float:
"""Exponential backoff with full jitter; attempt starts at 0."""
return random.uniform(0, min(cap, base * 2 ** attempt))With full jitter, the retries from a burst of simultaneous failures are spread across the whole window instead of landing at one instant. The average delay is half the ceiling, so clients also recover somewhat faster than with fixed exponential backoff.
| Strategy | Delay for attempt n | Synchronized clients? | Typical use |
|---|---|---|---|
| Immediate retry | 0 | Yes, fully | Almost never appropriate |
| Fixed delay | constant | Yes | Simple scripts with one client |
| Exponential | min(cap, base × 2ⁿ) | Yes | Better, but waves persist |
| Full jitter | random(0, min(cap, base × 2ⁿ)) | No | Default for services |
Honoring Retry-After
If the server sends Retry-After, it is telling you something your local formula cannot know. Use the larger of the server's hint and your own jittered delay. Ignoring the header and retrying sooner defeats the shedding the server just performed. A server that sheds should also add a little jitter to the value it sends. Otherwise, every client given Retry-After: 1 returns at the same moment.
Retry budgets
Backoff and jitter limit how fast each client retries. They do not limit how much retry traffic the whole system generates. A retry budget caps retries as a fraction of normal traffic. For example, "retries may add at most 10% to the request rate."
A common implementation is a token pool. Every original request adds a small fraction of a token. Every retry spends one whole token. When the pool is empty, the client does not retry and returns the error to its caller. During healthy operation the pool is full, so occasional failures are retried. During a broad failure, the pool drains and retries stop, which caps amplification at about 1.1× instead of 4×.
The following program combines backoff, jitter, Retry-After, a deadline, and a budget. It runs as shown.
import asyncio
import random
import time
class Overloaded(Exception):
def __init__(self, retry_after: float = 0.0) -> None:
super().__init__("overloaded")
self.retry_after = retry_after
def backoff_delay(attempt: int, base: float = 0.1, cap: float = 10.0) -> float:
return random.uniform(0, min(cap, base * 2 ** attempt))
class RetryBudget:
def __init__(self, ratio: float = 0.1, max_tokens: float = 10.0) -> None:
self.ratio = ratio # tokens earned per original request
self.max_tokens = max_tokens
self.tokens = max_tokens
def record_request(self) -> None:
self.tokens = min(self.max_tokens, self.tokens + self.ratio)
def try_spend(self) -> bool:
if self.tokens >= 1.0:
self.tokens -= 1.0
return True
return False
async def call_with_retries(op, budget: RetryBudget,
max_attempts: int = 4, timeout: float = 5.0):
deadline = time.monotonic() + timeout
budget.record_request()
for attempt in range(max_attempts):
try:
return await op()
except Overloaded as exc:
if attempt == max_attempts - 1:
raise
delay = max(exc.retry_after, backoff_delay(attempt))
if time.monotonic() + delay >= deadline:
raise # the caller would no longer be waiting
if not budget.try_spend():
raise # budget exhausted: fail fast
await asyncio.sleep(delay)
async def main() -> None:
failures_left = 2
async def flaky() -> str:
nonlocal failures_left
if failures_left > 0:
failures_left -= 1
raise Overloaded(retry_after=0.05)
return "ok"
budget = RetryBudget()
print(await call_with_retries(flaky, budget))
print(f"budget tokens left: {budget.tokens:.1f}")
asyncio.run(main())The program prints ok after two shed attempts, then budget tokens left: 8.1: the pool starts at 10, gains 0.1 for the request, and loses 2 for the retries.
The budget starts full so that a freshly started client can retry its first failures. Teams often start it smaller or add a minimum retry rate so that very low-traffic clients can still retry occasionally. Keep one budget per downstream dependency, not one per process. Otherwise, a failing dependency can drain the tokens that healthy calls need.
Retries across layers
Amplification multiplies across a call chain. If a gateway, a service, and a database client each make 3 attempts, one user request can produce 3 × 3 × 3 = 27 database calls when the database is down.
The usual guidance is to retry at one layer only, normally the one closest to the failing call, and have the layers above it pass errors through. If several layers must retry, give the outer layers fewer attempts or rely on budgets. A deadline passed down the chain also helps. Each layer sees how much time remains and stops retrying when the caller has already given up.
A callout summarizes the key rule.
Common errors
- Retrying without a cap on attempts or time. The loop keeps running after the user has gone away. Always bound both.
- Backoff without jitter. Clients stay synchronized, and load arrives in waves.
- Retrying non-idempotent operations. This causes duplicate charges, duplicate messages, or double writes.
- Retrying on every error. Client errors such as 400 or 404 will not succeed on a second attempt.
- Resetting the delay too early. If a client resets its attempt counter after each partial success, it can return to aggressive retries while the service is still struggling.
- Hiding retries from metrics. Count original requests and retries separately. A rising retry ratio is an early warning of overload.
Choosing settings
There are no universal values, but these defaults are reasonable starting points for a service-to-service call:
- Allow 2 or 3 total attempts, not unlimited retries.
- Use full jitter with a base near 50 to 100 ms and a cap of a few seconds.
- Set a retry budget of about 10% of request volume.
- Set an overall deadline shorter than the caller's own timeout, and stop when it is reached.
- Prefer the server's
Retry-Afterwhen it is present.
Then test them. A load test that pushes beyond capacity, covered in a later chapter, shows whether your retry settings damp the overload or amplify it.
Exercise
A gateway makes up to 3 attempts per call to a service, and the service makes up to 3 attempts per call to a database. The database is completely down. How many database calls does one gateway request cause, and which two changes would most reduce this number?
Show answer
Up to 3 × 3 = 9 database calls per gateway request. Two effective changes: retry at only one layer (for example, only the service, giving 3 calls), and add a retry budget so that retries stop once they exceed about 10% of normal traffic. Passing a deadline down the chain, so that layers stop when the caller has given up, also helps.
Exercise
Why does full jitter help more than plain exponential backoff when 1,000 clients fail at the same moment?
Show answer
With plain exponential backoff, all clients compute the same delay, so they retry at the same instant each round and send synchronized waves. Full jitter picks a random delay between 0 and the ceiling, which spreads the retries across the window and lowers the peak load on the recovering service.