Sub topic 9
Timeouts, retries and exponential backoff
This chapter assumes you can send a chat request from Python with requests, read HTTP status codes, and have read the previous chapter on error codes and rate limits. Here you will make calls survive temporary failures without hammering the server or hiding real bugs.
Why calls fail temporarily
A request can fail for reasons that have nothing to do with your code: the network drops, the server is overloaded, or you hit a rate limit. Many of these failures go away if you wait and try again. Others never will. A good client tells them apart.
| Failure | Retry? | Reason |
|---|---|---|
| Connection error or timeout | Yes | The network or server may recover |
| 429 Too Many Requests | Yes | The limit resets after a short wait |
| 500, 502, 503, 504 | Yes | Server-side problems are often brief |
| 400, 401, 403, 404 | No | The request itself is wrong, so repeating it fails again |
Set a timeout on every call
Without a timeout, requests can wait forever for a stalled server. Pass a tuple: the first value limits connecting, the second limits waiting for data between bytes received.
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)Generation can take many seconds, so the read timeout should be much longer than the connect timeout.
Exponential backoff with jitter
If you retry immediately, you add load to a server that is already struggling. Exponential backoff waits longer after each failure: 1 second, 2, 4, 8, and so on, up to a cap. Jitter adds a random amount so that many clients do not all retry at the same instant.
A bounded retry function
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")Points to notice:
- Only connection errors, timeouts and the listed status codes are retried. Other 4xx errors go straight to
raise_for_status(). - The delay is
min(30, 2 ** attempt)plus up to one second of jitter, so it grows 1, 2, 4, 8, 16 seconds and never passes about 31. - If the server sends a numeric
Retry-Afterheader, the code waits at least that long. - The loop is bounded by
max_attempts, so a long outage ends in an error instead of an endless loop.
Common mistakes
- Retrying every error, including 401 or 400. This wastes calls and delays the real error message.
- Retrying with no cap or no attempt limit.
- Using no jitter, so all your workers retry in step.
- Forgetting that each retry can cost money if a timed-out request still completed on the server. Keep the attempt count low for expensive calls.
Exercise
A request returns HTTP 401 after an invalid key is used. Should call_with_retries retry it? Also, with max_attempts=5 and no Retry-After header, what are the base delays (before jitter) between the attempts?
Show answer
No. 401 is not in the retryable set, so raise_for_status() raises immediately, because repeating a request with a bad key fails the same way. The base delays are 1, 2, 4 and 8 seconds. There are four waits for five attempts, since no wait follows the last attempt. Each wait gets up to one extra second of random jitter.