Lesson 6 of 8 · Real-World Use
Handling Errors and Retries
Make AI API calls reliable: errors to fix vs retry, exponential backoff with jitter, rate limits, timeouts, overload errors, fallback models and SDK behaviour.
- 6 min read
- Beginner
- Reviewed
- The errors AI APIs return and what each one means
- Which errors to retry and which to fix
- How exponential backoff with jitter works
- Timeouts, fallbacks and what SDKs do for you
Things go wrong
AI APIs are busy, shared services running huge models. Even with perfect code, some requests fail: the provider is overloaded, you send too many requests too quickly, a network connection drops. A reliable app expects this.
Two kinds of error
| Status | Meaning | What to do |
|---|---|---|
| 400 Bad request | Something in your request is invalid | Fix the request; retrying won't help |
| 401 / 403 | Key missing or invalid, or no permission | Fix the key or permissions |
| 404 | Unknown endpoint or model name | Fix the name |
| 413 | Request too large | Shorten the input |
| 408 Timeout | The request took too long | Retry |
| 429 Too many requests | Rate limit reached | Retry after waiting |
| 500 / 502 / 503 / 504 | Server-side problem | Retry after a short wait |
| 529 Overloaded | Used by some providers when busy | Retry after a wait |
The rule: 4xx means fix your request (except 408 and 429); 5xx means try again later.
Exponential backoff with jitter
When a request fails with a retryable error, wait and try again, and wait longer each time. If thousands of clients retried instantly, they would hammer an already overloaded server.
import random
RETRYABLE = [408, 429, 500, 502, 503, 504, 529]
# A pretend API that fails twice, then succeeds (a real one fails at random)
replies = [503, 429, 200]
def call_api(attempt):
status = replies[attempt]
return status, ("Here is your answer." if status == 200 else "error")
def call_with_retries(max_attempts=5, base_delay=1.0):
random.seed(1)
for attempt in range(max_attempts):
status, body = call_api(attempt)
if status == 200:
print(f"attempt {attempt + 1}: success -> {body}")
return body
if status not in RETRYABLE:
print(f"attempt {attempt + 1}: status {status}, not worth retrying")
return None
# Exponential backoff with jitter: about 1s, 2s, 4s, 8s... plus some randomness
delay = base_delay * 2 ** attempt + random.uniform(0, 0.5)
print(f"attempt {attempt + 1}: status {status}, waiting {delay:.2f}s before trying again")
# time.sleep(delay) <- a real program would wait here
print("giving up after", max_attempts, "attempts")
return None
call_with_retries()This pretend API fails with 503, then 429, then succeeds. Each wait roughly doubles, with a little randomness. A real program would call time.sleep(delay). If the response includes a retry-after header, wait at least that long instead.
Timeouts
Always set a timeout, so a stuck request doesn't hang your program forever. Choose it from the job: long answers from large or reasoning models can legitimately take a minute or more, so very short timeouts cause needless failures. Streaming helps here, because you can see progress as it happens.
Fallbacks
When retries run out, have a plan:
- Try another model, such as a smaller one from the same provider, or another provider with the same prompt.
- Degrade gracefully: show a friendly message, keep the user's input, offer to try again.
- Queue the work for later if it is not urgent.
Common mistakes
Decide what to do with each response status: celebrate, retry, or fix your request.
statuses = [200, 400, 401, 429, 503] retryable = [408, 429, 500, 502, 503, 504, 529] # For each status print one of: # "200: success" for 200 # "429: retry later" for anything in retryable # "400: fix the request" for everything else
Your app receives status 429 from an AI API. What should it do?
Summary
- 4xx errors (except 408 and 429) mean fix the request; 429 and 5xx mean retry later.
- Retry with exponential backoff plus jitter, respect retry-after, and cap the attempts.
- Set sensible timeouts; long answers can take a while.
- Plan fallbacks: another model, a friendly message or a queue.
- SDKs retry common failures already; configure them rather than stacking retry loops.
Next: counting tokens and keeping costs under control.
Finished reading? Tick it off to track your progress.