Sub topic 9
Timeouts, errors, and fallbacks
What this chapter assumes
You know basic Python and have called a hosted language model through an API. You have seen a rule-based router and a confidence cascade from earlier chapters, so you know that a router picks one model and a cascade tries the small model first. This chapter covers what happens when a call in either design does not return a usable answer.
Why routing adds failure modes
A single-model application has one dependency. A routed application has at least two, and each is a separate service with its own limits, outages, and latency. Routing also creates failures that did not exist before:
- The router picks a model that is down or rate limited, even though the other model is healthy.
- A cascade waits on the small model, then pays the large model's full latency on top.
- A cascade gets a slow or failed response from the large model after the small model already produced a low-confidence answer.
A fallback is a planned alternative that runs when the first choice fails. Fallbacks turn many of these failures into slower or slightly worse answers instead of error pages. Fallbacks do not fix everything. Some failures should be surfaced, and a careless fallback can make an outage worse. The rest of the chapter sorts out which is which.
Sorting failures into kinds
Not every error deserves the same response. The useful split is between failures that another attempt might fix and failures that no attempt will fix.
| Failure | Typical signal | Another model helps? | Suggested action |
|---|---|---|---|
| Timeout | No response within your limit | Often | Fall back |
| Rate limit | HTTP 429 | Often, since limits are per model or per account | Short wait, then fall back |
| Server error | HTTP 500, 502, 503 | Often | One retry, then fall back |
| Overloaded model | HTTP 503 or 529 with a capacity message | Often | Fall back |
| Bad request | HTTP 400, malformed input | No | Raise to the caller |
| Auth error | HTTP 401 or 403 | No | Raise and alert |
| Prompt too long for the model | Context length error | Only for a model with a larger window | Fall back to that model, or truncate |
| Unusable output | Invalid JSON, empty text | Sometimes | Retry once, then fall back |
Your client library will raise its own exception classes. The first job is to map them into two groups of your own: errors a fallback may fix, and errors it will not. The examples below use TimeoutError and a custom RetryableError for the first group and FatalError for the second.
The context length row deserves attention. The two tiers often have different context windows. A prompt that fits the large model may fail on the small one. Your router should check the prompt length against each model's limit before sending, so you do not discover the problem through an error.
The basic fallback
The simplest pattern wraps the primary call in a try block and calls the secondary on failure:
def call_with_fallback(prompt, primary, secondary):
try:
return primary(prompt)
except TimeoutError:
return secondary(prompt)This works, but it has three gaps that matter in production:
- It only catches
TimeoutError. Rate limits and server errors pass straight through to the user. - It does nothing to make
primarytime out. Many HTTP clients wait indefinitely by default, so theexceptbranch may never run. You must set a timeout on the client call itself. - It has no overall limit. If the secondary is also slow, the user waits for both.
The next sections address each gap.
Setting timeouts
Choose timeouts from measured latency, not from a round number. Take the latency of the successful calls for each model, look at a high percentile such as p95 or p99, and set the timeout a little above it. A timeout at the median fails half your healthy requests. A timeout of two minutes protects nobody.
Model latency depends on output length, because the model generates tokens one after another. A short classification and a long essay from the same model have very different normal latencies. If your request sizes vary a lot, set the timeout per request type, or use a streaming call and time out on the gap between chunks instead of on the total.
Use two limits together:
- A per-call timeout stops one slow call from consuming everything.
- A total deadline for the whole request caps the user's wait across all attempts.
Each attempt then gets the smaller of its own timeout and the time left in the deadline. A fallback that starts with one second left is not worth starting if the secondary model needs five seconds.
A fallback chain with a deadline
This example generalizes the basic fallback to an ordered list of models. It maps errors into retryable and fatal, and it respects a total deadline. The fake models at the bottom let you run it as written.
import time
class RetryableError(Exception):
"""Failure that another model might not share (429, 5xx, overload)."""
class FatalError(Exception):
"""Failure no model can fix (bad request, auth)."""
def call_with_fallback(prompt, chain, deadline_s=20.0, per_call_timeout_s=8.0):
start = time.monotonic()
last_error = None
for name, call in chain:
remaining = deadline_s - (time.monotonic() - start)
if remaining <= 0:
break
try:
text = call(prompt, timeout=min(per_call_timeout_s, remaining))
return text, name
except FatalError:
raise
except (TimeoutError, RetryableError) as exc:
last_error = exc
raise RuntimeError("all models failed or the deadline passed") from last_error
def small_model(prompt, timeout):
raise TimeoutError("small model too slow")
def large_model(prompt, timeout):
return "answer to: " + prompt
print(call_with_fallback("hello", [("small", small_model), ("large", large_model)]))Running it prints ('answer to: hello', 'large'). The function returns the name of the model that answered. Keep that habit, because the monitoring chapter relies on knowing which model served each request.
FatalError is re-raised immediately. Falling back on a malformed request would send the same bad request to every model and bill you for each attempt.
Retry or fall back?
A retry sends the same request to the same model again. A fallback sends it to a different one. Both have a place.
A single retry with a short, randomized delay is reasonable for rate limits and for transient 5xx errors. Many of these clear within a second. Retrying more than once or twice is rarely worth it, because each retry consumes deadline.
Fall back immediately when the failure is a timeout. A timeout already cost you the full timeout value. Waiting and retrying the same slow model doubles the damage.
Always add jitter, a small random amount, to retry delays. Without it, many clients that failed together retry together, and the burst can knock the model over again. This is a retry storm.
Which direction should a fallback go?
The tiers give you two natural directions, and they behave differently.
- Small fails, use large. Quality stays the same or improves. Cost and latency rise. This is the safe default when answers must be correct. It is also what a cascade does anyway on low confidence.
- Large fails, use small. Cost and latency drop, but quality may fall below what the task needs. This suits tasks where a plain answer beats no answer, such as a chat reply. It is a poor fit for tasks where a weak answer causes harm, such as generating code that will be run automatically.
A third option is a second provider hosting a model of the same tier. It gives similar quality and survives a provider outage, but it needs a second integration and a check that outputs have the same format. Prompts tuned for one model sometimes behave differently on another, so test the fallback path with your real prompts.
Fallbacks inside a cascade
A cascade already has an escalation step, so failures of the small model can reuse it: a failed small call is treated like a low-confidence answer. The harder case is when the large model fails after the small model has already answered with low confidence. You then have a draft answer in hand.
class RetryableError(Exception):
pass
def answer_with_fallback(prompt, call_small, call_large, threshold=0.8):
small_text = None
try:
small_text, confidence = call_small(prompt)
if confidence >= threshold:
return small_text, "small"
except (TimeoutError, RetryableError):
pass
try:
return call_large(prompt), "large"
except (TimeoutError, RetryableError):
if small_text is not None:
return small_text, "small_degraded"
raise
def small(prompt):
return "maybe 42", 0.5
def large(prompt):
raise TimeoutError("large model down")
print(answer_with_fallback("What is 6 times 7?", small, large))This prints ('maybe 42', 'small_degraded'). The distinct label small_degraded matters. The answer came from the small model like any other, but it did not clear the confidence bar. If you log it as plain small, your quality numbers will quietly look better than reality. Whether to return the degraded answer at all is a product decision. Some applications should show an error instead.
Latency and cost under failure
Failures change the numbers you computed in earlier chapters. In a cascade, the worst-case latency is the small model's timeout plus the large model's timeout. With a 5 second small timeout and a 15 second large timeout, a request can take 20 seconds. Choose the deadline with this sum in mind. A common choice is a short timeout for the small model, since it is meant to be fast, and a longer one for the large model.
Cost changes too. A timed-out call may still be billed for the tokens it generated, depending on the provider. A fallback after a timeout can therefore bill two models for one request. When the failure rate is high, your real cost per request is above the expected cost formula's estimate. Track actual spend, not just the formula.
Circuit breakers
If the small model is down, every request pays its timeout before falling back. At 5 seconds each, that is an outage for your latency even though every request succeeds in the end.
A circuit breaker prevents this. It counts recent failures for a model. When failures cross a limit, such as 5 failures in the last 10 calls, it opens: for a cooling period, such as 30 seconds, requests skip that model and go straight to the fallback. After the period, it lets a few test requests through. If they succeed, it closes and traffic resumes.
You can write a breaker yourself in a few dozen lines or use a library. Either way, keep one breaker per model, not one for the whole system. A failing large model should not stop traffic to the small one.
Pitfalls specific to fallbacks
- Untested fallback paths. Fallback code runs rarely, so bugs stay hidden until an outage. Inject failures in tests and in staging to exercise it.
- Silent fallbacks. If every request quietly falls back, you pay large-model prices and nobody notices. Count fallbacks and alert on the rate.
- Fallback overload. When the small model fails, all its traffic lands on the large model at once. That model may hit its own rate limit and fail too. Plan capacity for this, or shed load by rejecting some requests.
- Format mismatch. The fallback model may return a different structure. Validate outputs the same way regardless of which model produced them.
- Retrying fatal errors. Retrying a 400 or 401 just burns money and deadline.
Putting it together
A solid design for a routed application has these parts, in order:
- Check the prompt against each model's context limit before choosing.
- Pick the first model by rule, classifier, or cascade.
- Call it with a per-call timeout drawn from measured latency.
- On a retryable error, retry once with jitter if the deadline allows, or move to the next model.
- On a fatal error, stop and report it.
- Skip any model whose circuit breaker is open.
- If every model fails, return the best earlier draft if the product allows it, and label it degraded. Otherwise return a clear error.
- Record which model answered and every failure on the way.
The next chapter uses those records to monitor the system over time.
Exercise
A cascade uses a small model with a 4 second timeout and a large model with a 12 second timeout. The overall deadline is 10 seconds. The small model is down and every call times out. What is the worst-case wait for a user, and what are two changes that would reduce the wait without removing the large-model fallback?
Show answer
The small call burns 4 seconds. Only 6 seconds of the deadline remain, so the large call gets min(12, 6) = 6 seconds. If the large model needs more than 6 seconds, the user waits the full 10 seconds and still gets an error. Two changes help. First, add a circuit breaker on the small model, so after a few timeouts requests skip it and go straight to the large model, saving the 4 seconds. Second, lower the small model's timeout to just above its measured p99 latency, or raise the deadline so the large model has enough time. Setting the deadline above the sum of both timeouts (16 seconds) also removes the truncation, at the cost of a longer worst case.
Exercise
In the answer_with_fallback example, why does the function return the label "small_degraded" instead of "small" when the large model fails?
Show answer
The small answer did not meet the confidence threshold, so it is lower quality than a normal "small" answer. Labeling it separately keeps quality and cost metrics honest and lets you count how often the large model fails. If it were logged as "small", the share of confident small answers would look higher than it really is.