Sub topic 8
Bounding Retries with Attempt Limits and Budgets
This chapter assumes you can write the exponential backoff and jitter loop from earlier chapters. It also assumes you know how timeouts and the Retry-After header work. Backoff controls how long you wait between retries. It does not control how many retries you make. This chapter covers the controls that do: attempt limits, deadlines, and retry budgets.
Why unbounded retries are dangerous
A retry loop with no ceiling turns a short outage into a long one. Suppose a provider returns 503 for two minutes. If every client keeps retrying, the provider receives more traffic exactly when it is least able to serve it. Your own users also wait much longer for an error that could have been reported in seconds.
Three limits work together, and each one catches a different failure:
| Limit | What it caps | Failure it prevents |
|---|---|---|
| Attempt limit | Tries for one request | One request retrying forever |
| Deadline | Total wall-clock time for one request | A user waiting minutes for an error |
| Retry budget | Retries as a share of all traffic | Many requests all retrying during an outage |
An attempt limit and a deadline protect a single call. A retry budget protects the whole process.
Attempt limits
An attempt limit is the maximum number of tries, counting the first one. max_attempts=5 means one initial call and at most four retries. State it that way in code comments, because "max retries" is ambiguous. Some libraries count only retries, so max_retries=5 allows six calls.
Typical values for interactive LLM calls are 3 to 5 attempts. More attempts rarely help. If four spaced-out tries have failed, the problem is probably not a brief blip. Background jobs can tolerate more attempts because nobody is waiting on them, but they still need a ceiling.
The exponential ceiling also needs a cap. With base=0.5, the ceiling reaches 32 seconds by the seventh attempt. Cap each delay (for example at 8 or 30 seconds) so one wait stays reasonable.
Deadlines
An attempt limit does not bound time. Five attempts with a 30-second timeout each, plus backoff, can take over three minutes. A deadline bounds the total time instead. Choose it from what the caller can tolerate, such as 20 seconds for a chat reply.
A deadline-aware retry function checks the clock before it sleeps. If the next wait would cross the deadline, it raises the last error immediately instead of sleeping and then failing anyway.
import random
import time
class TransientError(Exception):
"""A failure that may succeed if tried again."""
def call_with_deadline(fn, max_attempts=5, deadline_s=20.0, base=0.5, cap=8.0):
start = time.monotonic()
for attempt in range(1, max_attempts + 1):
try:
return fn()
except TransientError:
if attempt == max_attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if time.monotonic() - start + delay >= deadline_s:
raise # no time left for another try
time.sleep(delay)
calls = {"n": 0}
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise TransientError("503")
return "ok"
print(call_with_deadline(flaky), "after", calls["n"], "calls")This prints ok after 3 calls after a short pause. Note that it uses time.monotonic(), not time.time(). The wall clock can jump when the system clock is adjusted, which would break the deadline arithmetic.
The same deadline should also limit each attempt's timeout. If 18 of 20 seconds have passed, a new request with a 30-second timeout can overrun the deadline. Pass the smaller of the normal timeout and the time remaining to the HTTP client.
Retry-After and the deadline
When a response carries Retry-After, compare it with the time remaining. If the server asks you to wait 45 seconds and only 10 seconds remain, sleeping is pointless. Fail fast and let the caller choose a fallback or tell the user. Sleeping the full time and then failing wastes both the user's time and a connection.
Retry budgets
Per-request limits are not enough when many requests fail together. Imagine 200 requests per second, each allowed 4 attempts. During an outage, every request retries up to 3 times, so the provider sees up to 800 requests per second instead of 200. That is 4 times the normal load, sent at a service that is already struggling. This is called retry amplification.
A retry budget caps retries as a fraction of total traffic. A common design is a token counter:
- Each new request adds a small amount, such as 0.1 tokens, up to a maximum.
- Each retry costs 1 token.
- When the counter is below 1, retries are refused and the error is surfaced immediately.
With a ratio of 0.1, retries can add about 10% extra load in the long run. Short bursts of failures can use stored tokens, but a sustained outage drains the counter and retries stop.
import random
import threading
import time
class TransientError(Exception):
pass
class RetryBudget:
def __init__(self, ratio=0.1, max_tokens=10.0):
self.ratio = ratio
self.max_tokens = max_tokens
self.tokens = max_tokens
self._lock = threading.Lock()
def record_request(self):
with self._lock:
self.tokens = min(self.max_tokens, self.tokens + self.ratio)
def try_spend(self):
with self._lock:
if self.tokens >= 1.0:
self.tokens -= 1.0
return True
return False
def call_with_limits(fn, budget, max_attempts=4, deadline_s=20.0,
base=0.5, cap=8.0, sleep=time.sleep):
start = time.monotonic()
budget.record_request()
for attempt in range(1, max_attempts + 1):
try:
return fn()
except TransientError:
if attempt == max_attempts:
raise
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if time.monotonic() - start + delay >= deadline_s:
raise
if not budget.try_spend():
raise # budget exhausted: surface the error now
sleep(delay)
calls = {"n": 0}
def always_fails():
calls["n"] += 1
raise TransientError("503")
budget = RetryBudget()
for _ in range(100):
try:
call_with_limits(always_fails, budget, sleep=lambda s: None)
except TransientError:
pass
print("total calls:", calls["n"])The demo replaces sleep with a no-op so it finishes instantly. Without a budget, 100 failing requests with 4 attempts each would make 400 calls. With the budget, the program prints roughly 120. That is 100 first attempts plus about 20 retries funded by the starting tokens and the 0.1 deposited per request.
Check the deadline before spending a token. A retry that the deadline would reject should not consume budget.
Where the budget lives
The budget must be shared by every request it is meant to protect. A budget created inside each call protects nothing. Usually you keep one per provider client, or one per provider and model, in the process. If you run many processes, each has its own budget. That is acceptable, because each process then limits its own share of the extra load.
Retries across layers multiply
Retries nest. Your code may call a function with its own loop, which calls an SDK that also retries, which sits behind a gateway that retries as well.
If three layers each allow 4 attempts, one user request can produce 4 × 4 × 4 = 64 calls to the provider. The rule is to retry in one layer only. If you use an SDK's built-in retries, set your own loop to a single attempt. If you write your own loop, set the SDK's max_retries to 0. Then place the budget and deadline at that one layer.
Choosing values
Start from the caller's patience and work backward.
- Set the deadline from the user experience, such as 20 seconds for a chat reply or several minutes for a batch job.
- Set the per-attempt timeout so that at least two or three attempts fit inside the deadline.
- Set
max_attemptsto 3 to 5, and cap each delay so a single wait is a fraction of the deadline. - Set the budget ratio to 0.1 as a starting point. Raise it only if you see healthy traffic being refused retries.
Common mistakes
- Counting retries instead of attempts, so the real number of calls is off by one.
- Using an attempt limit with no deadline, so latency has no ceiling.
- Creating a new budget for every request.
- Sleeping through a
Retry-Afterthat exceeds the remaining deadline. - Leaving SDK retries on while also running your own loop.
- Retrying inside a deadline without shrinking the per-attempt timeout.
Exercise
An application calls a helper that retries up to 4 attempts. The helper uses an SDK client that also retries up to 4 attempts, and a gateway in front of the provider retries up to 4 attempts as well. In the worst case, how many calls reach the provider for one user request, and what two changes would reduce that number?
Show answer
Worst case is 4 × 4 × 4 = 64 calls to the provider, which is 63 retries. Reduce it by retrying in only one layer (for example set the SDK's max_retries to 0 and disable gateway retries, keeping the application loop), and by adding a deadline and a shared retry budget at that one layer so retries stop when time or budget runs out.
Exercise
A retry budget starts with 10 tokens, adds 0.1 per new request, and spends 1 per retry. During an outage, 50 requests arrive and every attempt fails. Ignoring the 0.1 deposits, how many retries can the initial tokens fund, and what happens to requests after that?
Show answer
The initial 10 tokens fund 10 retries. After that, try_spend returns False, so each failing request raises its error right after its first failure instead of retrying. Only the small 0.1 deposits fund an occasional extra retry (one per ten new requests).