Sub topic 9
Timeouts, errors, and fallbacks
This chapter assumes you can write basic Python and have called a hosted language model through an API. It also assumes you know how routers and cascades work from earlier chapters. Here you will make a routed system survive failures, so that a slow or broken model call does not become an error shown to the user.
Why routing adds failure modes
A routed system depends on more than one model. Each call can fail in its own way:
- The call never returns, or returns too late.
- The provider returns an error such as a rate limit (HTTP 429) or a server error (5xx).
- The call succeeds but returns an empty or malformed answer.
A fallback is a second path that handles the request when the first path fails. Routing gives you a natural place to put one, because you already have more than one model available.
Set a timeout first
A fallback can only trigger if the failure is detected. A call that hangs for two minutes is a failure the user will notice long before your code does. Always set an explicit timeout on every model call. Choose it from your latency goal. For example, if you want 95% of responses within 5 seconds, a 4 second timeout on the primary call leaves room for a fallback.
Many client libraries accept a timeout argument. If yours does not, run the call in a thread and wait with a limit.
The basic fallback
The simplest pattern tries the primary model and switches to the secondary one on a timeout.
def call_with_fallback(prompt, primary, secondary):
try:
return primary(prompt)
except TimeoutError:
return secondary(prompt)Here primary and secondary are functions that take a prompt and return text. The except clause catches only TimeoutError. Any other exception passes through to the caller.
That narrow catch is deliberate. A bad API key or an invalid request will fail on the secondary model too, so retrying it there wastes time and hides a real bug.
Which errors deserve a fallback
Not every error is the same kind of problem. Sort them into two groups.
| Error | Likely cause | Fall back? |
|---|---|---|
| Timeout | Slow or overloaded model | Yes |
| 429 rate limit | Too many requests to this model | Yes, to a model with separate limits |
| 5xx server error | Provider problem | Yes |
| 400 invalid request | Bug in your request | No, fix the request |
| 401 or 403 | Bad credentials or permissions | No, fix configuration |
Errors in the first three rows are transient, meaning they may go away on their own. Errors in the last two rows are permanent, meaning the same request will fail again.
Choosing the secondary model
The direction of the fallback matters, because it changes cost and quality.
- Large to small. When the large model is down, the small model gives a lower-quality answer but keeps the feature working. This is often the right trade for chat and search, where an imperfect answer beats an error.
- Small to large. This keeps quality up but raises cost. It suits a cascade, where escalation is already the plan.
- Same tier, other provider. This keeps quality and cost close, but you must maintain prompts and tests for two providers.
Decide per feature. A support chatbot may accept a small-model answer. A contract analysis tool may prefer to tell the user "try again" rather than return a weaker answer.
A fuller version with retries
A single retry on the same model often fixes a brief glitch. This version retries once, then falls back, and records which path answered.
import time
TRANSIENT = (TimeoutError, ConnectionError)
def call_resilient(prompt, primary, secondary, retries=1, delay=0.5):
for attempt in range(retries + 1):
try:
return primary(prompt), "primary"
except TRANSIENT:
if attempt < retries:
time.sleep(delay)
try:
return secondary(prompt), "secondary"
except TRANSIENT:
return "Sorry, the service is busy. Please try again.", "failed"The function returns the answer together with a label. That label lets you count how often each path runs, which the monitoring chapter relies on.
The final return gives the user a clear message when both models fail. Failing gracefully still beats a stack trace.
Common mistakes
- No timeout. Without one, the fallback never runs.
- Retrying too long. Two retries with a 4 second timeout each add 12 seconds before the fallback starts. Keep the total time within your latency goal.
- Retry storms. If thousands of requests retry at once against a struggling provider, they make the outage worse. Add a short delay, and ideally random jitter.
- Silent fallbacks. If the fallback runs often and nobody sees it, quality quietly drops. Always log which path answered.
Exercise
Your cascade calls the small model first and escalates to the large model on low confidence. The large model starts returning HTTP 503 errors. Name one reasonable fallback behavior, and one error you should not retry on the other model.
Show answer
A reasonable fallback is to return the small model's answer even though its confidence was below the threshold, possibly flagged as lower confidence, instead of showing an error. An error you should not retry on another model is a 400 invalid request or a 401 authentication failure, because the same bad request or credentials will fail there too.