Sub topic 9
Timeouts, retries and exponential backoff
This chapter assumes you can send a chat request from Python with requests, that you know HTTP status codes, and that you have read the previous chapter on error codes and rate limits. Here you will make calls survive transient failures without hammering the provider or repeating work that already succeeded.
Why failures are normal
A call to a hosted model crosses your network, the provider's load balancers, and a queue for scarce GPU capacity. Some failures are temporary and disappear if you try again a moment later. Others are permanent and will fail identically every time.
- Temporary: a dropped connection, a timeout, a
429rate limit response, a500,502,503or504server response. - Permanent:
400(bad request),401(bad key),403(no access),404(wrong model or path), and422(invalid parameters).
A retry policy is the rule that separates the two groups. Retrying a permanent error wastes time and quota. Giving up on a temporary error makes your application flaky.
Timeouts
A timeout is the longest time your program waits before it abandons an operation. Without one, requests waits forever, and a single stalled connection can freeze a worker thread indefinitely.
requests accepts either one number or a pair (connect, read):
- The connect timeout limits how long to wait while opening the TCP connection.
- The read timeout limits how long to wait between bytes from the server. It is not a limit on the total request time.
import os
import requests
resp = requests.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"},
json={
"model": os.environ["LLM_MODEL"],
"messages": [{"role": "user", "content": "Say hello."}],
},
timeout=(5, 60),
)
print(resp.status_code)Choose the connect timeout short, usually 3 to 10 seconds, because a healthy server accepts connections quickly. Choose the read timeout long enough for the model to finish. For a non-streamed response, the server sends nothing until generation is complete, so a long answer from a large model can take tens of seconds. If you set max_tokens high, raise the read timeout to match.
With streaming, bytes arrive continuously, so the read timeout acts as a stall detector. A value of 30 seconds then means "no data for 30 seconds", which is a useful signal that the stream is dead.
Deciding what to retry
Retry only when all of these hold:
- The failure is probably temporary.
- A repeat is safe, meaning it will not cause harm if the first attempt actually succeeded.
- You have not exceeded your attempt or time budget.
| Outcome | Retry? | Reason |
|---|---|---|
| Connection error | Yes | Network glitch or server restart |
| Timeout | Yes, with care | The server may still have processed the request |
| 429 | Yes | Rate limit; capacity returns after a wait |
| 500, 502, 503, 504 | Yes | Provider-side or gateway problem |
| 400, 422 | No | Your payload is wrong; repeating it changes nothing |
| 401, 403 | No | Fix the key or permissions |
| 404 | No | Wrong URL or model name |
A subtle case is a 429 caused by exhausted billing quota rather than a short-term rate limit. Some providers use the same status code for both. Look at the error body: if it says you exceeded your quota or have no credit, retrying will never help, so stop.
Exponential backoff
Backoff means waiting between attempts. Exponential backoff doubles the wait after each failure: 1 second, 2, 4, 8, and so on. Early retries are quick, which suits brief glitches. Later retries give an overloaded server room to recover.
Two refinements matter in practice.
- A cap limits the maximum delay, for example 30 seconds. Without one, the sixth or seventh wait becomes impractical.
- Jitter adds randomness to each delay. If 500 clients fail at the same moment and all wait exactly 2 seconds, they all return at the same moment and overload the server again. Randomness spreads them out.
The delay for attempt n, counting from 0, is:
delay = min(cap, base * 2 ** n) + random(0, 1)Many providers also send a Retry-After header with a 429 or 503. It tells you how many seconds to wait. When present, it is better information than your own guess, so use the larger of the two values. The header can also contain an HTTP date instead of a number, so parse it defensively.
A working retry helper
This function implements the policy above. It retries connection errors, timeouts, 429 and 5xx responses, and it raises other client errors immediately.
import os
import random
import time
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
RETRYABLE = {429, 500, 502, 503, 504}
def call_with_retries(payload, max_attempts=5):
for attempt in range(max_attempts):
resp = None
try:
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=(5, 60))
except (requests.ConnectionError, requests.Timeout):
pass
if resp is not None and resp.status_code not in RETRYABLE:
resp.raise_for_status()
return resp.json()
if attempt == max_attempts - 1:
break
delay = min(30, 2 ** attempt) + random.random()
if resp is not None:
try:
delay = max(delay, float(resp.headers["Retry-After"]))
except (KeyError, ValueError):
pass
time.sleep(delay)
raise RuntimeError("LLM request failed after retries")
if __name__ == "__main__":
result = call_with_retries(
{
"model": os.environ["LLM_MODEL"],
"messages": [{"role": "user", "content": "Say hello."}],
}
)
print(result["choices"][0]["message"]["content"])Walk through the control flow:
- On a connection error or timeout,
respstaysNone, so the code skips the success branch and goes to the wait. - On a non-retryable status,
raise_for_status()either returns (for 2xx) or raisesHTTPErrorimmediately. The caller sees the real problem without delay. - On the last attempt, the loop breaks before sleeping, so you never wait after the final failure.
Retry-Aftercan only lengthen the wait. A non-numeric value raisesValueError, which the code ignores.
With max_attempts=5 the waits are about 1, 2, 4 and 8 seconds, plus jitter. Total waiting is roughly 15 seconds, plus up to 60 seconds per attempt in read timeouts. That is the worst case, so check it against what your caller can tolerate.
Idempotency and duplicate work
An operation is idempotent if doing it twice has the same effect as doing it once. A plain chat completion has no side effects in your system, so repeating it is safe. The cost is money: if a timeout fires after the provider already generated the answer, you pay for tokens twice.
The risk grows when the response triggers actions. If your code sends an email or charges a card based on model output, a retry can repeat that action. Keep the side effect outside the retry loop, and run it once, after you hold a validated response. If your provider supports an idempotency key header, use it for requests with side effects. Check the provider's documentation, because support varies.
Edge cases and common errors
- Retrying inside nested layers. If your SDK retries 3 times and your own wrapper retries 5 times, one failure can cause 15 calls. Use one layer. Official SDKs often retry by default, so read their settings before adding your own loop.
- Retrying without a budget. A fixed attempt count is not enough for user-facing code. Add an overall deadline, for example 90 seconds, and stop when it passes.
- Retrying on
400after a context overflow. A request that exceeds the context window fails the same way every time. Shorten the input instead. - Ignoring partial streams. If a stream breaks halfway, a retry restarts generation from the beginning. Discard the partial text or handle it explicitly, since the second answer may differ.
- Synchronized clients. Without jitter, a batch job with many workers creates retry waves. Always add jitter.
- Retrying a rate limit too eagerly. Each retry that hits
429can count toward your limit. RespectRetry-Afterand lower your concurrency, not just your pace on one worker. - Silent retries. Log each retry with the attempt number, status and delay. Never log the API key or full prompts that contain private data.
Exercises
Exercise
A request returns HTTP 400 with the message "maximum context length exceeded". Should your retry helper try again, and what should you do instead?
Show answer
No. A 400 is a permanent client error, and the same payload will fail every time. Reduce the input, for example by trimming or summarizing older messages or lowering max_tokens, then send a new request.
Exercise
Ten workers each fail at the same moment and use delays of exactly 1, 2, 4 and 8 seconds. What problem does this cause, and how do you fix it?
Show answer
All ten workers retry at the same instants, so the server sees synchronized bursts that can overload it again. Add jitter, a random amount to each delay, so the retries spread out over time.
Exercise
Your helper uses timeout=(5, 60), max_attempts=5 and a maximum computed delay of 31 seconds. Roughly what is the worst-case time before it raises an error, if every attempt times out and no Retry-After header is sent?
Show answer
Five attempts can each take up to about 65 seconds if the connection is slow to open and then the read times out, but a pure read timeout is about 60 seconds, so use roughly 5 x 60 = 300 seconds of waiting on the network. Add four backoff waits of about 1, 2, 4 and 8 seconds plus jitter, about 15 to 19 seconds. The worst case is therefore a little over 5 minutes, which is why a total deadline is also useful.