Errors, retries, rate limits & timeouts
Wrap model calls with backoff, timeouts and graceful fallbacks.
By Invicly Tech, , in AI Engineering with Python. About 10 minutes to read.
In short
Model APIs fail in ordinary ways: timeouts, rate limits and temporary server errors. Production code adds timeouts, retries with exponential backoff and a fallback so one slow call does not break the app.
Explained simply
Calling a model is a network call to a busy service. Sometimes it is slow, sometimes the provider says you are sending too much, and sometimes its servers have a bad minute. None of this is rare. If your code assumes every call works, your app will break in front of users.
A timeout is the longest you are willing to wait. Without one, a stuck call can hang a user's request forever. With one, you give up after, say, 30 seconds and can try something else.
A retry tries the same call again after a short wait. Waiting a bit longer after each failure (1 second, then 2, then 4) is called exponential backoff. Adding a small random amount, called jitter, stops thousands of clients from retrying at the exact same moment.
Only some errors are worth retrying. A busy server or a rate limit will likely pass. A bad request or a wrong API key will fail the same way every time. When retries run out, a fallback (a backup model or a friendly message) keeps the app useful.
Press Play on a diagram to walk through it one step at a time.
- Step 1Call with timeout
Never wait forever
- Step 2Classify error
Retry 429 and 5xx; not 400 or 401
- Step 3Backoff with jitter
Wait 1s, 2s, 4s plus randomness
- Step 4Fallback
Another model or a friendly message
- Your app to LLM API: Request1Request
- LLM API to Your app: 429 with Retry-After: 22429 with Retry-After: 2
- 3Wait 2 secondsYour app to Your app: Wait 2 seconds
- Your app to LLM API: Same request again4Same request again
- LLM API to Your app: 200 OK with the reply5200 OK with the reply
In depth
Sort errors before you retry
HTTP status codes tell you what kind of failure you have. 400 means the request itself is wrong, for example an invalid parameter or a prompt longer than the context window. 401 and 403 mean the key is wrong or lacks permission. 404 often means a model name that does not exist. These will fail every time, so fix the request instead of retrying.
429 means you hit a rate limit, and 500, 502, 503 and 504 are server-side problems. Network errors and timeouts belong here too. Some providers also return a special overloaded error when demand is high. These are transient: they usually succeed if you wait and try again.
Official SDKs raise different exception classes for these cases, such as a rate limit error, a connection error and a timeout error. Catch the specific classes, not every exception.
- Retry with backoff
- Timeout or connection error
- 429 rate limited
- 500, 502, 503, 504
- Provider overloaded
- Do not retry: fix it
- 400 bad request
- 401 or 403 key or permission
- 404 unknown model
- Prompt too long for context
- Handle separately
- Refusal or content filter
- Reply cut off by token limit
Timeouts that match the work
There are two kinds of timeout. A connect timeout limits how long you wait to reach the server, and a few seconds is plenty. A read timeout limits how long you wait for data. A long non-streaming answer can legitimately take a minute or more, so set it from your real p99 latency, not a guess.
Official SDKs often have generous default timeouts (several minutes) and a couple of automatic retries. Set both yourself, per client or per request.
Also set a total deadline for the whole user request. If the user will only wait 20 seconds, then three attempts of 30 seconds each is meaningless. With streaming, you can use a short time-to-first-token limit and a longer idle limit between chunks: if no chunk arrives for 20 seconds, the stream is probably stuck.
- Connect timeout: a few seconds
- Read timeout: based on measured p99
- Total deadline: what the user will wait
- Streaming: idle timeout between chunks
Rate limits and backoff in practice
Providers limit requests per minute and tokens per minute, often separately for input and output tokens, per model and per organisation. Many responses include headers showing how much quota is left, and a 429 may include a Retry-After header saying how many seconds to wait. If it is present, obey it.
Otherwise, use exponential backoff with jitter. A common formula is: wait a random time between 0 and min(cap, base x 2 to the power of attempt). Cap the number of attempts (3 to 5) and the total time.
Watch for stacked retries. If the SDK retries twice and your wrapper retries five times, one call can become 15 requests. Pick one layer to own retries, and set the other to zero.
Better still, avoid 429s: limit concurrency with a semaphore, spread batch jobs over time, and use the provider's batch API for work that can wait.
Fallbacks and circuit breakers
A fallback is what you do when the main path fails. Options include a second model from the same provider, a model from another provider, a cached answer for common questions, or a clear message: the assistant is busy, please try again in a minute. A fallback model needs its own eval run, because the same prompt can behave differently on another model.
If the main provider is having an outage, retrying every request just adds load and makes users wait. A circuit breaker tracks recent failures. When they pass a threshold, it opens: calls skip the main provider and go straight to the fallback. After a cool-down it lets one test call through; if that works, it closes and traffic returns.
Log every retry, fallback and breaker change with a reason. A sudden rise in fallbacks is often your first sign of a provider problem.
- 1Closed
Calls go to the main model; failures are counted
- 2Open
Too many failures: use the fallback at once
- 3Half-open
After a cool-down, let one test call through
- 4Back to closed
Test call works: normal traffic resumes
- Back to step 1
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Add timeouts to model calls~30m
- 2Retry with exponential backoff~30m
- 3Handle rate limit errors~30m
- 4Add a fallback model~30m
Key points
- Retry only transient errors like timeouts, 429 and 5xx responses.
- Respect a Retry-After header when the provider sends one.
- Add random jitter so many clients do not retry at the same moment.
- Cap total attempts and total time so users are not left waiting.
Key terms
Tap a card to flip it. 0/5 known
Examples
import random, time
class TransientError(Exception): ...
def with_retries(call, attempts: int = 4):
for i in range(attempts):
try:
return call()
except TransientError:
if i == attempts - 1:
raise
delay = (2 ** i) + random.uniform(0, 0.5)
time.sleep(delay)
# Many SDKs have built-in retry and timeout options; use those first.Exponential backoff with jitter for transient errors only.
Retries with tenacity
You want backoff without writing the loop yourself. Step 1: install tenacity. Step 2: map your SDK's transient errors (timeouts, 429, 5xx) to one exception type, or list the SDK's own classes. Step 3: decorate the call: retry only that type, wait a random exponential time capped at 30 seconds, stop after 5 attempts, and re-raise the last error. Step 4: set the SDK's own max retries to 0 so retries do not stack.
# pip install tenacity
from tenacity import (retry, retry_if_exception_type,
stop_after_attempt, wait_random_exponential)
class TransientError(Exception):
"""Raised for timeouts, 429 and 5xx responses."""
@retry(retry=retry_if_exception_type(TransientError),
wait=wait_random_exponential(multiplier=1, max=30),
stop=stop_after_attempt(5),
reraise=True)
def call_model(prompt: str) -> str:
... # SDK call (with its own retries off); raise TransientError when neededA deadline with a fallback model
Users will wait about 6 seconds. Step 1: give the main model 3 seconds with asyncio.timeout. Step 2: if it times out or the connection fails, give a smaller, faster model 3 seconds. Step 3: if that also fails, return a friendly message instead of an error page. In this simulation the main model takes 10 seconds, so the backup answers.
import asyncio
async def primary(q: str) -> str:
await asyncio.sleep(10); return "big model answer" # too slow today
async def backup(q: str) -> str:
await asyncio.sleep(0.5); return "small model answer"
async def answer(q: str) -> str:
for model in (primary, backup):
try:
async with asyncio.timeout(3):
return await model(q)
except (TimeoutError, ConnectionError):
continue
return "The assistant is busy. Please try again in a minute."
print(asyncio.run(answer("hi"))) # small model answerQuick reference
- Retry: timeouts, connection errors, 429, 500, 502, 503, 504
- Do not retry: 400, 401, 403, 404 or prompt-too-long errors
- Obey Retry-After when a 429 includes it
- Backoff with full jitter: sleep random(0, min(cap, base * 2^attempt))
- Let one layer own retries: SDK retries x wrapper retries multiply
- Set a total deadline per user request, not just per attempt
- Run your evals on the fallback model before you rely on it
Common mistakes
- Retrying invalid requests that will fail every time.
- Retrying instantly in a tight loop and making rate limiting worse.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a function is_retryable(status: int) that returns True for 408, 429 and 5xx codes, and False otherwise. Test it with 200, 400, 401, 429, 500 and 503.
- Exercise 2medium
Write backoff_delays(attempts, base=1, cap=20) that returns the list of sleep times using full jitter, and a retry loop that obeys a Retry-After value when one is given.
- Exercise 3hard
Implement a simple circuit breaker class with failure_threshold and cool_down_s. It should open after N failures in a row, use the fallback while open, and allow one test call after the cool-down.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is a good timeout for LLM calls?
- Measure your own latencies and set it a little above your p99, often 30 to 120 seconds for non-streaming calls. Streaming calls can use a short first-token limit plus an idle limit between chunks.
- How do I avoid 429 rate limit errors?
- Limit concurrency with a semaphore, spread batch work over time, use the provider's batch API for jobs that can wait, and ask for higher limits once your usage grows.
- Is it safe to retry an LLM call?
- A plain text generation call has no side effects apart from cost, so retrying is safe. Be careful with flows where a tool call already changed something, such as sending an email.