Timeouts, retries, backoff and jitter
Choose timeouts from measured latency, pass deadlines down the chain, retry only failures that are temporary and safe to repeat, spread retries with backoff and jitter, and cap them with a retry budget.
Contentsand lesson path
On this page
- Why it matters
- Timeouts and deadlines
- Which failures are worth a retry
- Backoff and jitter
- Retry budgets and where to retry
- Check your understanding
- Apply it
- Review prompt
Lessons of Resilience Patterns
- How cascading failures happen Concept · 20 min
- Timeouts, retries, backoff and jitter Concept · 20 min
- Idempotency keys for safe retries Worked example · 25 min
- Circuit breakers, bulkheads and load shedding Concept · 20 min
- Injecting latency and failures into a call chain Lab · 30 min
- Resilience check Knowledge check · 8 questions
What you will learn
- Set timeouts and retry policies (exponential backoff, jitter, retry budgets) that do not amplify an outage.
01. Why it matters
A timeout decides how long a caller is willing to hold resources while it waits for one answer. A retry decides how much extra load the caller adds when the answer does not come. In lesson 1 you saw both go wrong: callers without timeouts filled their pools, and retries turned a ten-second slowdown into an outage that did not end.
The API error handling lesson showed the client code in FastAPI and httpx. This lesson is about choosing the numbers and the policy: timeouts, deadlines, which failures to retry, backoff with jitter, and retry budgets. Retrying writes safely also needs idempotency keys, the subject of lesson 3.
02. Timeouts and deadlines
Start from the dependency's measured latency, not from a round number. The Amazon Builders' Library describes one method: choose an acceptable rate of false timeouts, such as 0.1%, and set the timeout near the matching latency percentile of the dependency, here p99.9, with some padding. A timeout far below that turns healthy calls into retries; one far above it holds a worker on calls that will probably fail anyway. Measure latency where the caller sees it, network included, and recheck it as traffic changes.
A per-call timeout is not enough on its own, because one user request often passes through several services. A deadline is the time by which the whole request must finish. It is set once, at the edge, from what the user or the API contract can tolerate, and each service passes the remaining time to the next one. This is called deadline propagation. gRPC converts the deadline into a timeout at each hop, subtracting the time already used; Java and Go propagate it by default, while C++ needs it switched on. Over plain HTTP you can send the remaining milliseconds in a header, as the lab does with X-Deadline-Ms.
Two rules follow. A caller never waits past its own deadline, so each attempt's timeout is the smaller of the per-try timeout and the time left. And a server checks the time left before it starts expensive work, because work for a caller that has already given up is pure waste.
Here is a worked budget, with its assumptions. The edge gives a product request 1,000 ms. Authentication and routing use about 150 ms, which leaves roughly 850 ms for the catalog call. The catalog's p99.9 is 250 ms, so a per-try timeout of 300 ms fits. Two tries and a short backoff need about 650 ms in the worst case, which fits in 850 ms; a third try would not. So the policy is one retry, not three, and the reason is arithmetic, not habit.
03. Which failures are worth a retry
Send a retry only when two things are true: the failure is likely to be temporary, and repeating the operation is safe.
Temporary failures include connection errors, timeouts, 503 Service Unavailable, and 429 Too Many Requests once you have waited as long as its Retry-After header asks. Failures that will simply happen again include 400 and 422 (the request itself is wrong), 401 and 403 (credentials) and 404. Retrying those adds load and changes nothing. Some services return an explicit overloaded, do not retry signal; the Google SRE book recommends that callers respect it.
Safety depends on the operation and on when the failure happened:
- Reads, and writes that set a value instead of changing it, such as a
PUTthat replaces a resource or aDELETE, are idempotent in HTTP (RFC 9110, section 9.2.2): doing them twice leaves the same state as doing them once. - A write that creates or adds something, such as a payment or an add one item call, is not idempotent. If the request may have reached the server, a timeout tells you nothing about whether it ran. Retry it only with an idempotency key that the server honours.
- If the failure happened before the request was sent, the server never saw it, so even a non-idempotent call can be resent. A failed DNS lookup, refused connection or failed TLS handshake proves this, since the request normally goes out only after all three. The exception is TLS 1.3 or QUIC early data (0-RTT), a request sent inside the handshake, but RFC 8470 forbids clients to send unsafe methods such as POST that way. Later failures, such as a reset or a proxy error, leave the outcome unknown.
An immediate retry is not always wrong: one quick retry can hide a lost packet while the system is healthy. The danger is many immediate retries during overload.
04. Backoff and jitter
Exponential backoff makes each wait longer than the last: wait base × 2^n before retry n, up to a cap. The longer a dependency struggles, the more room it gets. On its own, though, backoff keeps clients in step. If a thousand clients fail at the same instant, they all wait the same 100 ms, then the same 200 ms, and arrive together every time. Jitter adds randomness to break that alignment. Common variants are full jitter, a random wait between zero and the backoff; equal jitter, half the backoff plus a random half; and the plus or minus 20% that gRPC applies to its backoff.
The simulation below lets 1,000 clients fail together at time zero, against a service that is down for one second and can then answer 150 calls in each 100 ms slot. Each client makes at most 8 attempts. It uses a fixed random seed, so you get the same numbers every run.
"""1,000 clients fail together; compare when and how hard their retries arrive."""
import heapq
import random
CLIENTS = 1000
BUCKET_MS = 100 # the server is judged in 100 ms slots
CAPACITY = 150 # calls it can answer in one slot once it is back
DOWN_UNTIL_MS = 1000 # it is down for the first second
BASE_MS, CAP_MS = 100, 3200
MAX_ATTEMPTS = 8 # first try plus 7 retries, then the client gives up
def backoff(strategy: str, retry: int, rng: random.Random) -> float:
ceiling = min(CAP_MS, BASE_MS * 2 ** retry) # 100, 200, 400 ... 3200
if strategy == "none":
return ceiling
if strategy == "full":
return rng.uniform(0, ceiling)
return ceiling / 2 + rng.uniform(0, ceiling / 2) # "equal" jitter
def run(strategy: str) -> None:
rng = random.Random(42) # fixed seed: same output each run
events = [(0.0, c, 1) for c in range(CLIENTS)] # (time ms, client, attempt)
heapq.heapify(events)
down_calls = up_calls = gave_up = last_ok = 0
peak = 0 # busiest slot after recovery
while events:
slot = int(events[0][0] // BUCKET_MS)
batch = []
while events and int(events[0][0] // BUCKET_MS) == slot:
batch.append(heapq.heappop(events))
up = slot * BUCKET_MS >= DOWN_UNTIL_MS
if up:
up_calls += len(batch)
peak = max(peak, len(batch))
else:
down_calls += len(batch)
for i, (t, client, attempt) in enumerate(batch):
if up and i < CAPACITY: # earliest arrivals are served
last_ok = max(last_ok, t)
elif attempt == MAX_ATTEMPTS:
gave_up += 1
else:
delay = backoff(strategy, attempt - 1, rng)
heapq.heappush(events, (t + delay, client, attempt + 1))
print(f"{strategy:>6} {down_calls:11} {up_calls:9} {peak:10} {gave_up:8} "
f"{last_ok:11.0f}")
print("jitter calls_down calls_up peak/slot gave_up last_ok_ms")
for name in ("none", "equal", "full"):
run(name)python3 jitter_sim.pyjitter calls_down calls_up peak/slot gave_up last_ok_ms
none 4000 3100 1000 400 9500
equal 4196 1258 266 0 2872
full 5007 1000 141 0 4072Without jitter, every retry lands in the same slot: 1,000 calls into a slot that can serve 150, again and again, until 400 clients run out of attempts. Both jittered versions serve everyone. Full jitter keeps every slot after recovery under capacity, so each client's first try after the outage succeeds; it pays with more calls during the outage, because some random waits are close to zero. In this model equal jitter finishes first. Marc Brooker's 2015 simulation on the AWS Architecture Blog, which modelled clients contending for optimistic writes to one database rather than an outage, ranked full jitter above equal jitter. The order between jitter styles depends on the workload; the gap between no jitter and any jitter was large in every variation of this model we tried.
The extra calls during the outage carry a warning: jitter decides when retries happen, not how many. Attempt caps and retry budgets decide how many.
05. Retry budgets and where to retry
Retries multiply across layers. If the edge, the catalog and a database driver each make up to two attempts, one user request can become eight database queries. The Google SRE book and the Amazon Builders' Library give the same advice: retry at one layer, usually the one that knows best whether a retry can succeed, and let the other layers fail fast.
A retry budget limits retries by recent success, not per request. gRPC's retry throttling is a clear example. Each client keeps a token count that starts at a maximum. Every failure removes one token, every success adds a fraction of one, and retries are allowed only while the count is above half the maximum. When the dependency is down, the budget empties after a few failures, and from then on each request makes one attempt instead of three. AWS SDKs use a similar token bucket.
The policy below combines the pieces: a per-try timeout capped by the deadline, full-jitter backoff, retries only for temporary errors, and a shared budget. A fake clock and a scripted dependency make the trace repeatable.
"""A retry policy with a deadline, a retry budget and error classes (fake clock)."""
import random
RETRYABLE = {"timeout", "503", "refused"} # 400, 404, 409, 422: retrying cannot help
class Clock: # a fake clock, so the demo prints the same trace on every run
def __init__(self) -> None:
self.now = 0.0
def sleep(self, seconds: float) -> None:
self.now += seconds
class RetryBudget:
"""Like gRPC retry throttling: no retries while tokens <= half of the maximum."""
def __init__(self, max_tokens: float = 10, ratio: float = 0.1) -> None:
self.max, self.ratio, self.tokens = max_tokens, ratio, max_tokens
def record(self, ok: bool) -> None:
delta = self.ratio if ok else -1
self.tokens = min(self.max, max(0.0, self.tokens + delta))
def allows_retry(self) -> bool:
return self.tokens > self.max / 2
def call(script, clock, budget, rng, deadline, log=print,
per_try=0.3, attempts=3, base=0.05):
"""`script` lists what the dependency does: (result, seconds it takes)."""
n = 0
while True:
n += 1
timeout = min(per_try, deadline - clock.now) # never wait past the deadline
result, takes = script[min(n, len(script)) - 1]
if takes > timeout:
result, takes = "timeout", timeout
clock.sleep(takes)
budget.record(result == "ok")
ms, limit = clock.now * 1000, timeout * 1000
log(f" t={ms:3.0f} ms try {n}, timeout {limit:3.0f} ms: {result}")
if result == "ok" or result not in RETRYABLE:
return result, n
wait = rng.uniform(0, base * 2 ** (n - 1)) # full jitter
if n == attempts or not budget.allows_retry():
return f"give up ({result})", n
if clock.now + wait + 0.01 >= deadline: # no time left for a useful try
return "give up (deadline)", n
clock.sleep(wait)
rng = random.Random(7)
cases = {
"transient 503": [("503", 0.02), ("ok", 0.04)],
"slow dependency, 500 ms left": [("ok", 2.0)],
"bad request": [("422", 0.01)],
}
for name, script in cases.items():
print(name)
print(" ->", call(script, Clock(), RetryBudget(), rng, deadline=0.5)[0])
print("dependency down: 6 requests share one budget")
budget = RetryBudget()
for i in range(6):
before = budget.tokens
result, n = call([("503", 0.01)], Clock(), budget, rng, 0.5, log=lambda s: None)
print(f" request {i + 1}: {n} tries, tokens {before:.1f} -> {budget.tokens:.1f}")python3 retry_policy.pytransient 503
t= 20 ms try 1, timeout 300 ms: 503
t= 76 ms try 2, timeout 300 ms: ok
-> ok
slow dependency, 500 ms left
t=300 ms try 1, timeout 300 ms: timeout
t=500 ms try 2, timeout 192 ms: timeout
-> give up (deadline)
bad request
t= 10 ms try 1, timeout 300 ms: 422
-> 422
dependency down: 6 requests share one budget
request 1: 3 tries, tokens 10.0 -> 7.0
request 2: 2 tries, tokens 7.0 -> 5.0
request 3: 1 tries, tokens 5.0 -> 4.0
request 4: 1 tries, tokens 4.0 -> 3.0
request 5: 1 tries, tokens 3.0 -> 2.0
request 6: 1 tries, tokens 2.0 -> 1.0One jittered retry hides the brief fault. In the second case only 500 ms remain, so the second try gets the 192 ms that are left, not a fresh 300 ms, and the policy then stops instead of running past the deadline. The 422 is not retried. Against a dead dependency, the first two requests may retry; from the third on, each makes a single attempt, so the outage costs about one call per request instead of three.
06. Check your understanding
07. Apply it
For the practice project's three-service chain, write the retry policy down before you code it:
- The deadline at the edge, and how much time each hop passes on.
- For each outbound call, the per-try timeout and the percentile it comes from. If you have no measurements yet, say so and plan to measure.
- The status codes and errors you retry, and the single layer that retries.
- The backoff (base, cap, jitter style), the maximum number of attempts, and the retry budget.
Then run the lab: step 10 counts exactly how many calls reach the failing service with and without a budget, so you can check your expectations.
08. Review prompt
Without looking back, explain how you would choose a per-try timeout for a dependency and how it relates to the deadline of the whole request. List three failures worth retrying and three that are not, and name the failures that prove a request never reached the server. Finally, explain what jitter changes and what it does not, and how a retry budget behaves during a full outage.
References
- Timeouts, retries, and backoff with jitter (Amazon Builders' Library)
- Exponential Backoff And Jitter (AWS Architecture Blog)
- Deadlines (gRPC documentation)
- A6: gRPC Retry Design, including retry throttling
- RFC 9110: HTTP Semantics, section 9.2.2 Idempotent Methods
- Addressing Cascading Failures (Google SRE Book)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.