Deadlines, retries and fallbacks for model calls
Handle slow and failing model providers with deadlines, bounded retries with jitter and honest fallbacks.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 13 minutes to read.
In short
Model providers are slow sometimes and fail sometimes. A resilient gateway gives each request a deadline, sorts errors into retryable and permanent, retries only the retryable ones a few times with exponential backoff and jitter, and then either falls back honestly or fails with a clear error. It records usage and latency for every attempt so you can see what is happening.
Think of it like this: Like calling a busy shop: you wait a fixed time, try again after a pause that grows each time, and after a few tries you go to another shop or tell the customer it is closed.
Explained simply
Model providers are busy, shared services. Sometimes they answer in one second, sometimes in thirty, and sometimes they return an error. If our service simply waits forever or crashes on the first error, users see a spinning wheel or a broken page.
The first defence is a deadline: the longest we are willing to wait for an answer, retries included. When time is up, we stop and tell the user clearly. A deadline also frees the connection and the worker for other users.
The second defence is retrying, but carefully. Some errors are temporary, such as the provider being overloaded. Others are permanent, such as a bad request or a wrong API key; trying again cannot fix those. We retry only the temporary ones, a few times, waiting a little longer each time.
The third defence is a fallback: a planned alternative such as a smaller model, a cached answer or an honest message saying the service is busy. Whatever we choose, we tell the user when the answer is degraded, and we record every attempt so we can see how often it happens.
Press Play on a diagram to walk through it one step at a time.
- 1Start the deadline
For example 20 s for the whole call
- 2Attempt
Per-attempt timeout inside the deadline
- 3Classify the outcome
Success, retryable or permanent
- 4Back off with jitter
Only if retryable and time is left
- 5Fall back or fail
Labelled fallback or a clear 503 or 504
- Retry with backoff
- 429 rate limited (honour Retry-After)
- 500, 502, 503, 504
- Connect or read timeout
- Connection reset
- Do not retry
- 400 bad request
- 401 or 403 credentials
- 404 unknown model
- 422 or content too long
- API to Gateway: generate(request), deadline 20 s1generate(request), deadline 20 s
- Gateway to Provider: Attempt 12Attempt 1
- Provider to Gateway: 429, Retry-After: 23429, Retry-After: 2
- Gateway to Provider: Attempt 2 after 2 s4Attempt 2 after 2 s
- Provider to Gateway: 200 with answer and usage5200 with answer and usage
- Gateway to API: Result, attempts=2, latency=3.4 s6Result, attempts=2, latency=3.4 s
In depth
Deadlines and timeouts
There are two kinds of limit. A per-attempt timeout covers one HTTP call. HTTPX has a default timeout of 5 seconds for each phase, which is far too short for long model answers, so set it on purpose, for example httpx.Timeout(30.0, connect=5.0). An overall deadline covers the whole operation, retries and backoff included. In Python 3.11 and later, wrap the operation in async with asyncio.timeout(seconds), which cancels whatever is running when time runs out and raises TimeoutError.
Derive the deadline from what the user is willing to wait and from upstream limits. If your proxy closes idle connections after 60 seconds, a 90-second deadline is meaningless. Before each retry, check the time left: if the backoff plus a realistic attempt does not fit, stop now. Map an expired deadline to 504 Gateway Timeout with a stable error code.
- Per-attempt timeout: httpx.Timeout on the shared client
- Overall deadline: asyncio.timeout around the whole call
- Check remaining time before each retry
- Expired deadline maps to 504 with a stable code
Classifying errors
Turn every provider failure into your own ProviderError with a status and a kind. 429 means too many requests: retry after the time the provider gives in Retry-After, if any. 500, 502, 503 and 504 and network errors such as connection resets and read timeouts are usually temporary. 400 and 422 mean the request itself is wrong, for example too many tokens, and 401 or 403 mean a credential problem: retrying cannot help, so fail fast and alert, because a bad key affects every user.
Some providers return 429 for two different reasons: a short-term rate limit and a spent monthly quota or billing limit. Read the error body; retrying a spent quota just wastes time. Also treat output that fails validation as a separate kind, handled by the validation step rather than the transport retry loop.
- 429 rate limit, 5xx, timeouts
- Retry with backoff and jitter
- Honour Retry-After
- Give up at the attempt cap or deadline
- 400, 404, 422, context too long
- No retry; return a clear 4xx or 502
- Fix the request or the prompt
- Log the request shape, not its content
- 401, 403, spent quota
- No retry; alert the team
- Return 503 to users
- Often affects every request
Backoff with jitter
Exponential backoff doubles the wait after each failure: 0.5 seconds, then 1, then 2, up to a cap such as 8. Jitter adds randomness. With full jitter, each wait is a random value between zero and the current exponential limit. Without jitter, a thousand clients that failed at the same moment retry at the same moment and knock the provider over again.
Keep the number of attempts small, two or three in total, and apply retries in one layer only. Many SDKs retry by default; if your gateway also retries, set the SDK's retries to zero so a single failure does not multiply. A retry budget limits retries across the whole service, for example no more than 10 percent extra calls, and a circuit breaker stops calling a provider for a short pause after many failures in a row.
Fallbacks that stay honest
A fallback is a business decision as much as a technical one. Options include a second provider or a smaller model, a cached answer for the same question and document version, a retrieval-only reply that lists the most relevant passages without a generated summary, or a clear error asking the user to try again. Each changes quality differently. A smaller model may cite less accurately; a cached answer may be older.
Whatever you choose, put a degraded flag and the fallback reason in the result, show a short note in the UI, and record it in logs and metrics. Never fall back from a model that was approved for a tenant's data to one that was not, for example from a provider with a no-retention agreement to one without. For streamed answers, decide before the first token: once text has reached the user, do not switch models or retry silently.
- 1Primary model
Within the deadline
- 2Secondary approved model
Marked degraded
- 3Cached answer
Same docs version only
- 4Sources only
Show passages, no summary
- 5Clear error
503 with retry advice
Tracking usage and latency
Record one entry per attempt, not just per request: provider, model, prompt version, attempt number, status or error kind, latency in milliseconds, input and output tokens and whether a fallback was used. Add the request ID so you can join it with API logs and traces. From these you get the numbers that matter: p50 and p95 latency, error rate by kind, retries per request and tokens per tenant, which drives cost.
Also measure time to first token for streamed calls, since users notice it most. Never log the prompt or answer text by default; it may hold personal or confidential data. Store token counts in PostgreSQL with each assistant message so cost per tenant can be reported later.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Set a deadline per request~35m
- 2Classify 429, 4xx and 5xx errors~35m
- 3Retry with backoff and jitter~35m
- 4Decide when to fall back~35m
- 5Track usage and latency~35m
Key points
- One overall deadline per request beats many independent timeouts that add up.
- Retry only errors that a later attempt could fix, and cap the attempts, usually at 2 or 3.
- Use exponential backoff with random jitter so clients do not retry in lockstep.
- A fallback changes answer quality; label it in the result and in logs.
- Record attempts, status, latency and tokens for every call, including failures.
Key terms
Tap a card to flip it. 0/6 known
Examples
import asyncio, random
RETRYABLE = {429, 500, 502, 503, 504}
async def call_with_retries(send, attempts=3, deadline_s=20.0):
async with asyncio.timeout(deadline_s): # Python 3.11+
for i in range(attempts):
try:
return await send()
except ProviderError as e:
if e.status not in RETRYABLE or i == attempts - 1:
raise
cap = min(8.0, 0.5 * 2 ** i)
await asyncio.sleep(e.retry_after or random.uniform(0, cap))Bounded retries, full jitter and one overall deadline.
Drill: a slow provider hits the deadline
Prerequisites: the API running with the fake provider. Step 1: set the fake's delay to 30 seconds and the gateway deadline to 5 seconds. Step 2: call POST /ask. Evidence: the response arrives after about 5 seconds with status 504 and error code model_timeout, and the log shows one attempt with kind timeout. Step 3: set the delay back to 0 and repeat; you get 200. Rollback: restore the default settings. No paid provider is involved.
FAKE_MODEL_DELAY_S=30 MODEL_DEADLINE_S=5 uvicorn app.main:app --port 8000 &
time curl -s -X POST localhost:8000/ask \
-H 'Content-Type: application/json' -d '{"question": "What is our refund policy?"}'
# expect after ~5 s: {"error": {"code": "model_timeout", ...}}
kill %1Turning a provider error into a decision
Step 1: catch HTTPX exceptions and non-2xx responses in the adapter. Step 2: convert them to ProviderError with a kind. Step 3: the retry loop retries only transient kinds and honours retry_after. Step 4: the route maps the final error kind to an HTTP status: timeout to 504, transient after retries to 503, permanent to 502, configuration to 503 with an alert. Test each branch by making the fake raise that status.
def classify(exc: Exception) -> ProviderError:
if isinstance(exc, httpx.TimeoutException):
return ProviderError(kind="transient", status=None)
if isinstance(exc, httpx.HTTPStatusError):
s = exc.response.status_code
ra = exc.response.headers.get("Retry-After")
retry_after = float(ra) if ra and ra.isdigit() else None
if s == 429 or s >= 500:
return ProviderError(kind="transient", status=s, retry_after=retry_after)
if s in (401, 403):
return ProviderError(kind="config", status=s)
return ProviderError(kind="permanent", status=s)
return ProviderError(kind="transient", status=None)Quick reference
- Retry: 429, 500, 502, 503, 504, timeouts, resets. Do not retry: 400, 401, 403, 404, 422
- 2 to 3 attempts total; retries in one layer only; turn SDK retries off
- Full jitter: wait random.uniform(0, min(cap, base x 2^attempt)) seconds
- async with asyncio.timeout(s): overall deadline (Python 3.11+)
- HTTPX default timeout is 5 s; set httpx.Timeout(30.0, connect=5.0) for model calls
- Mark fallback answers as degraded and say why
- Log per attempt: model, status, latency, tokens, request ID; never prompt text
Common mistakes
- Retrying 400 or 401 errors, which can never succeed and only waste time and quota.
- Retrying a streamed answer after tokens have already reached the user, which duplicates text.
- Stacking retries in the SDK, the gateway and the client, so one failure becomes dozens of calls.
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 backoff(attempt) that returns a full-jitter delay with base 0.5 seconds and cap 8 seconds.
- Exercise 2medium
Extend the retry loop so it never sleeps past the overall deadline: if the planned wait plus a minimum attempt time does not fit, raise immediately.
- Exercise 3hard
Design a simple circuit breaker for the gateway: after 5 consecutive transient failures, reject calls for 30 seconds, then allow one trial call.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How long should a model call deadline be?
- It depends on the answer length and what users accept. For an interactive answer, 20 to 60 seconds overall is common; with streaming, also watch time to first token, which should be a few seconds.
- Can I use a retry library such as tenacity?
- Yes. It handles backoff, jitter and stop conditions well. Keep the classification of retryable errors in your own code and make sure the SDK is not retrying as well.
- Should the browser retry too?
- Avoid automatic browser retries for model calls, because they multiply load. Show a clear error with a Try again button instead, and let the server-side gateway own retries.