Sub topic 6
Adding jitter to avoid synchronized retries
This chapter assumes you can read the exponential backoff loop from the previous chapter, know what HTTP 429 and 5xx responses mean, and are comfortable with Python's random module. Here you will see why backoff alone can still overload a recovering service, how jitter fixes that, and which jitter formula to choose.
The problem: backoff keeps clients in lockstep
Exponential backoff spaces out the retries of one client. It does nothing about the timing between clients. Suppose a provider returns 503 for ten seconds and 1,000 of your workers fail in the same second. With plain backoff (base * 2 ** (attempt - 1)), every worker computes the same delay: 0.5 s, then 1 s, then 2 s, and so on. All 1,000 workers retry at the same instant, fail together if the service is still struggling, and then retry together again.
This pattern is called a thundering herd. Each wave of retries is as large as the original burst, so the service sees repeating spikes instead of a gradual return of traffic. The same thing happens with rate limits. If a shared quota is exhausted, a synchronized wave of retries consumes the new quota window in one burst and triggers fresh 429 responses.
Jitter means adding randomness to each delay. Clients that failed together then retry at different moments, so the load spreads out over time.
Full jitter
Full jitter picks the delay uniformly between zero and the exponential ceiling:
ceiling = min(cap, base * 2 ** (attempt - 1))
delay = random.uniform(0, ceiling)This is the formula used in the retry loop from the topic's earlier example. It spreads retries across the whole window, and the average delay is half the ceiling. It is the usual default because it gives the lowest peak load on the server.
The cost is that a delay can be very short. A client may draw 0.01 s on attempt 4, even though the ceiling is 4 s. For a transient network blip that is fine. For an overloaded service it is still acceptable, because the other clients are spread out.
Other variants
Two other formulas are common.
- Equal jitter keeps half the ceiling as a guaranteed minimum and randomizes the other half:
ceiling / 2 + random.uniform(0, ceiling / 2). Every retry waits at least half the ceiling. Retries are spread less widely than with full jitter, so peaks are higher. - Decorrelated jitter bases each delay on the previous one instead of on the attempt number:
sleep = min(cap, random.uniform(base, sleep * 3)). Each client follows its own random path, so clients drift apart over time. It needs state carried between attempts.
| Strategy | Delay for attempt n | Minimum wait | Spread between clients | State needed |
|---|---|---|---|---|
| None | `ceiling` | Full ceiling | None | Attempt number |
| Full | `uniform(0, ceiling)` | 0 | Widest | Attempt number |
| Equal | `ceiling/2 + uniform(0, ceiling/2)` | Half ceiling | Medium | Attempt number |
| Decorrelated | `uniform(base, prev * 3)` | `base` | Wide | Previous delay |
Measuring the effect
You can see the difference without calling any API. The script below simulates 1,000 clients that all fail at time zero and retry four times. It counts how many retries land in each 0.1 second bucket and reports the busiest bucket.
import random
from collections import Counter
def delay_none(attempt, base=0.5, cap=30.0):
return min(cap, base * 2 ** (attempt - 1))
def delay_full(attempt, base=0.5, cap=30.0):
return random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
def delay_equal(attempt, base=0.5, cap=30.0):
ceiling = min(cap, base * 2 ** (attempt - 1))
return ceiling / 2 + random.uniform(0, ceiling / 2)
def peak_load(delay_fn, clients=1000, attempts=4, bucket=0.1):
"""Return the largest number of retries that land in one time bucket."""
counts = Counter()
for _ in range(clients):
t = 0.0
for attempt in range(1, attempts + 1):
t += delay_fn(attempt)
counts[int(t / bucket)] += 1
return max(counts.values())
random.seed(7)
for name, fn in [("none", delay_none), ("equal", delay_equal), ("full", delay_full)]:
print(f"{name:>5}: busiest 0.1 s bucket = {peak_load(fn)} retries")With no jitter, the busiest bucket holds all 1,000 retries, because every client computes identical delays. With full or equal jitter, the peak is a small fraction of that. The exact numbers depend on the seed, but the ordering is stable: none is worst, equal is better, and full is usually best.
Decorrelated jitter in code
The decorrelated variant needs the previous delay, so a small generator is a natural fit.
import random
import time
def decorrelated_delays(base=0.5, cap=30.0):
"""Yield an endless sequence of decorrelated-jitter delays."""
sleep = base
while True:
sleep = min(cap, random.uniform(base, sleep * 3))
yield sleep
delays = decorrelated_delays()
for attempt in range(1, 6):
delay = next(delays)
print(f"attempt {attempt}: would sleep {delay:.2f}s")
# time.sleep(delay) would go here in a real retry loopUse the generator once per request, not once per process. A shared generator would couple the delays of unrelated requests.
Jitter and Retry-After together
When a response includes Retry-After, the server is telling you the earliest useful time to try again. Jitter must not shorten that wait. The earlier retry loop handles this by taking the larger of the two values:
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if retry_after is not None:
delay = max(delay, min(retry_after, cap))There is a subtle problem here. If 1,000 clients all receive Retry-After: 5, then max(delay, 5) turns into exactly 5 for most of them, and you have rebuilt the synchronized spike. When the header is present and many clients may share it, add a small random amount on top of the server's value:
def delay_with_retry_after(jittered, retry_after, spread=1.0, cap=30.0):
"""Never wait less than Retry-After, and spread clients that share it."""
if retry_after is None:
return jittered
return min(cap, retry_after + random.uniform(0, spread))Choose spread relative to the header value. A spread of 1 s on a 5 s hint is reasonable. A spread of 1 s on a 60 s hint does little.
Common mistakes
- Jittering a fixed delay by a tiny amount. Adding
random.uniform(0, 0.01)to a 2 s delay leaves clients bunched within 10 ms of each other. The random range should be proportional to the delay, not a token amount. - Applying the cap after adding jitter. If you compute
ceiling + randomand then cap it, many clients hit the cap and again retry at the same time. Cap the ceiling first, then draw the random value. - Sharing one seeded generator across tests and production. Seeding
randommakes every process draw the same sequence. Seed only inside tests, and let production use the default system seeding. - Reseeding per request. Code such as
random.seed(int(time.time()))makes all requests started in the same second produce identical delays. Never reseed in the retry path. - Forgetting that the first attempt is not jittered. If a scheduled job fires 1,000 requests at exactly 09:00:00, the first attempts are already synchronized. Jitter the start times too, for example with a random 0 to 30 s offset before a batch begins.
Testing jittered code
Random delays make tests flaky unless you control them. Pass the random function as a parameter so a test can replace it:
import random
def full_jitter(attempt, base=0.5, cap=30.0, rng=random.uniform):
return rng(0, min(cap, base * 2 ** (attempt - 1)))
def test_full_jitter_bounds():
# A fake rng that returns the upper bound shows the ceiling.
assert full_jitter(4, rng=lambda lo, hi: hi) == 4.0
# A fake rng that returns the lower bound shows the floor.
assert full_jitter(4, rng=lambda lo, hi: lo) == 0
# The cap limits the ceiling for large attempt numbers.
assert full_jitter(20, cap=30.0, rng=lambda lo, hi: hi) == 30.0
test_full_jitter_bounds()
print("ok")Testing the bounds, not exact values, keeps the tests stable. A later chapter covers simulating failures end to end.
Choosing a strategy
- Start with full jitter. It is simple and gives the best spread for most LLM workloads.
- Use equal jitter when a minimum wait matters, such as a provider that rejects very rapid retries.
- Use decorrelated jitter when you want clients to diverge over long retry sequences and can keep per-request state.
- Always keep the cap and the attempt limit. Jitter changes when retries happen, not how many happen.
Exercise
A client uses base=0.5, cap=30, and full jitter. What range can the delay take before attempt 4, and what is its average? What would the range be with equal jitter?
Show answer
The ceiling is min(30, 0.5 2 * 3) = 4 s. With full jitter the delay is uniform from 0 to 4 s, so the average is 2 s. With equal jitter the delay is uniform from 2 to 4 s, with an average of 3 s.
Exercise
One thousand workers all receive a 429 with Retry-After: 10. The retry code uses delay = max(jittered_delay, retry_after). Why might this still produce a spike, and how do you fix it?
Show answer
Early in the retry sequence the jittered delay is usually below 10 s, so max returns exactly 10 for almost every worker, and they all retry at the same moment. Fix it by adding random spread on top of the header value, for example retry_after + random.uniform(0, spread), so the wait is never shorter than the server's hint but is no longer identical.