Sub topic 2
Exponential Backoff for LLM API Retries
Assume you know basic Python, exceptions, async/await, HTTP status codes, and how to call an LLM API. This chapter focuses on temporary failures, not invalid requests or incorrect prompts.
Exponential backoff
Exponential backoff increases the wait after each failed attempt. A common schedule is:
delay = min(cap, base × 2^(attempt - 1))
For example, with a base of 0.5 seconds, the delays are 0.5, 1, 2, 4, and 8 seconds. The cap prevents one retry from sleeping for an unreasonable time.
Adding jitter
If many clients fail together, they may all retry at the same moments. This creates another traffic spike. Jitter adds randomness to each delay. Full jitter chooses a random value between zero and the exponential limit.
import random
def retry_delay(attempt, retry_after=None, base=0.5, cap=30.0):
ceiling = min(cap, base * (2 ** (attempt - 1)))
delay = random.uniform(0, ceiling)
if retry_after is not None:
delay = max(delay, min(retry_after, cap))
return delay
for attempt in range(1, 5):
print(f"attempt {attempt}: wait {retry_delay(attempt):.2f}s")
print(f"server-directed wait: {retry_delay(2, retry_after=5):.2f}s")The random values make clients spread their retries over time.
Respecting `Retry-After`
A server may return HTTP 429 or 503 with a Retry-After header. The header tells the client how long to wait, usually in seconds. Treat it as a lower bound. The example above waits for the larger of the jittered delay and the server's value.
A malformed or extremely large value should be validated and capped. A production client should also support the header's HTTP-date form.
Retry limits and budgets
Retries need two boundaries:
- A maximum attempt count limits repeated calls.
- A retry budget limits total time or retry work for one operation.
An overall deadline is safer than unlimited sleeping. If the deadline expires, return an error or use a fallback.
When is a retry safe?
A retry is safe when repeating the request does not create an unwanted side effect. Reading a completion is usually safe. Creating a purchase, sending an email, or writing a record may not be safe if the server accepted the first request but the response was lost.
Use an idempotency key when the provider supports one. The server can recognize repeated attempts as the same operation. For streaming responses, a failure after partial output may require restarting or presenting the partial result, not blindly repeating the side effect.
Exercise
Why should a retry use both jitter and a maximum attempt count?
Show answer
Jitter separates clients in time, while the attempt limit prevents an endless retry loop.