Sub topic 8
Bounding retries with attempt limits and budgets
This chapter assumes you can write Python functions and handle exceptions. It also assumes you know HTTP status codes and have called an LLM API before. Earlier chapters covered which errors are retryable, backoff, jitter, and Retry-After. Here you will put a ceiling on all of that.
Why retries need a ceiling
A retry loop with no limit can turn a short outage into a long one. Each caller keeps waiting and sending requests, and the failing service gets more load while it is trying to recover. Two limits prevent this:
- An attempt limit caps how many times one call is tried.
- A retry budget caps how much retrying the whole application does.
Attempt limits
An attempt limit counts the first try plus every retry. With max_attempts=5, a call makes at most one initial request and four retries. When the last attempt fails, the code must raise the error. It must not sleep again or return a made-up value.
The post_with_retries function from the earlier example does this. It re-raises a TransportError on the last attempt. It also calls raise_for_status() when the final response is still a failure.
A good limit is small. Three to five attempts covers most brief faults. If a request still fails after that, waiting longer rarely helps, and the caller is better off getting an error it can act on.
Limits on time as well as count
An attempt count alone does not bound the total wait. Five attempts with a 30-second timeout and a 30-second backoff cap could take several minutes. Add a deadline for the whole operation as well.
import time
def remaining(deadline: float) -> float:
"""Seconds left before the deadline, never negative."""
return max(0.0, deadline - time.monotonic())
deadline = time.monotonic() + 45.0 # whole operation, including retries
# Before each attempt and before each sleep, check the budget of time.
delay = 12.0
if remaining(deadline) <= delay:
print("Not enough time left for another attempt, so stop and raise.")
else:
print("Sleep, then try again.")Use time.monotonic() for deadlines. It does not jump when the system clock changes. Before sleeping, compare the delay with the time left. If the delay would pass the deadline, stop now instead of sleeping and then failing.
Retry budgets
Attempt limits apply to one call. They do not protect you when many calls fail together. If 100 requests per second each retry four times, a failing service sees up to 500 requests per second. A retry budget limits retries as a share of total traffic, for example "retries may be at most 10% of requests".
The class below allows one retry for every ten first attempts.
class RetryBudget:
"""Allow retries only up to `ratio` of the first attempts seen."""
def __init__(self, ratio: float = 0.1, minimum: int = 3):
self.ratio = ratio
self.minimum = minimum # lets a quiet service still retry a little
self.requests = 0
self.retries = 0
def record_request(self) -> None:
self.requests += 1
def can_retry(self) -> bool:
return self.retries < self.minimum + self.requests * self.ratio
def record_retry(self) -> None:
self.retries += 1
budget = RetryBudget(ratio=0.1)
for _ in range(20):
budget.record_request()
allowed = 0
while budget.can_retry():
budget.record_retry()
allowed += 1
print("retries allowed:", allowed)This prints retries allowed: 5. That is the minimum of 3 plus 10% of 20 requests. In a real service you would count over a sliding window, such as the last minute, so old traffic does not inflate the budget forever. Check budget.can_retry() before each retry. If it returns False, raise the error at once.
Common mistakes
- Counting only retries and forgetting the first attempt, so the real number of requests is one higher than intended.
- Setting an attempt limit but no deadline, so a user waits minutes for an error.
- Retrying at several layers. An SDK that retries 5 times inside your loop of 5 makes up to 25 requests per call.
Exercise
A service handles 200 first-attempt requests in a minute. A RetryBudget with ratio=0.1 and minimum=3 has been used for all of them. How many retries does it allow in that minute, and what should the caller do when can_retry() returns False?
Show answer
It allows 3 + 200 × 0.1 = 23 retries. When can_retry() returns False, the caller should stop retrying and raise the error immediately, without sleeping.