Sub topic 14
Fallback models, cached answers, and graceful degradation
This chapter assumes you can write the retry loop from the earlier chapters and know what a circuit breaker does. Retries and breakers decide when to stop calling a failing service. This chapter covers what your application does next. A well-designed system gives the user something useful, says honestly that it is degraded, and recovers on its own when the provider does.
Why degrade instead of fail
Some failures last longer than any sensible retry budget. Examples are a regional outage, an exhausted quota, or a model that the provider has retired. If your only response is to raise an exception, the user sees an error page. A degraded answer is often better. A smaller model's answer, yesterday's cached answer, or a plain message with a next step all beat an error.
Degradation has a cost. The answer may be lower quality, out of date, or missing features. So the design question is which degraded outcomes your product can accept, and how the caller learns that one happened.
The degradation ladder
Order the options from best to worst and try them in that order.
| Tier | Source | Typical quality | Main risk |
|---|---|---|---|
| 1 | Primary model | Full | None |
| 2 | Fallback model (smaller, or on another provider) | Reduced | Different behavior, format, or cost |
| 3 | Cached answer for the same request | Good but possibly stale | Outdated content |
| 4 | Static message or reduced feature | Minimal | User gets no generated content |
The tiers fit together as follows.
Fallback models
A fallback model is a second model you call when the first is unavailable. Two common choices exist.
- A smaller model from the same provider. It is easy to set up and uses the same SDK and prompt format. It often shares the provider's outage, though. Separate rate limits per model can still help with 429 errors.
- A model from a different provider. It survives a provider-wide outage. It costs more to maintain because request formats, tool-calling conventions, and error types all differ.
Check these points before you rely on a fallback.
- Prompt compatibility. A prompt tuned for one model can behave differently on another. Test the fallback with your real prompts, not only a hello-world call.
- Context window. A fallback with a smaller window can reject long inputs with a 400. Check the input size before you choose it.
- Feature parity. Structured output, tool calling, and image input are not available everywhere. Validate the fallback's output with the same schema checks you use for the primary.
- Data and cost policy. Sending user data to a second provider may need legal or security approval. A fallback can also cost more per token than the primary, so set a spending alert on it.
Decide which errors trigger a fallback. Move to the fallback after retries are exhausted, or when a circuit breaker is open. Do not fall back on 401 or 403, because those mean your credentials or permissions are wrong. A fallback may hide the bug, and it will likely fail the same way. A 400 for an oversized input is a special case. You can reduce the input, or choose a model with a larger window, but do not blindly resend the same request.
Fallbacks also share your overall deadline. If the primary and its retries have used 25 of your 30 seconds, the fallback gets five seconds, not a fresh budget. Pass the remaining time into each tier.
Cached answers
A cache can serve two different purposes, and they behave differently.
- Cache first (an optimization). You check the cache before calling the model. A hit saves cost and latency. It suits repeated, deterministic requests such as classification of common inputs.
- Cache on error (a fallback). You call the model, and only if it fails do you serve a stored answer, even an expired one. This pattern is often called stale-if-error. It suits questions whose answers change slowly, such as documentation lookups or product descriptions.
Build the cache key from everything that changes the answer: the normalized prompt, the system prompt or template version, and parameters such as temperature. If you leave out the template version, a prompt change can serve answers written for the old prompt.
Some content should never be served from a shared cache. Do not reuse answers that contain one user's personal data for another user. Include the user or tenant ID in the key, or skip caching entirely. Answers that depend on live data, such as stock prices or order status, are also bad candidates, because a stale answer can be wrong in a harmful way.
Exact-match caches are predictable. Semantic caches, which match similar prompts using embeddings, can return an answer to a slightly different question. Use them only where an approximate answer is acceptable, and test the similarity threshold.
Putting it together
The following example is self-contained and runs as shown. The providers are stubs that you would replace with real SDK calls. It tries each provider in order, stores successes in the cache, then tries the cache, then returns a static message. Each result records its source and whether it is degraded.
import hashlib
import time
from dataclasses import dataclass
class LLMUnavailable(Exception):
"""Raised by a provider call after its own retries are used up."""
@dataclass
class Answer:
text: str
source: str # "primary", "fallback", "cache", or "static"
degraded: bool
class AnswerCache:
def __init__(self):
self.items = {}
@staticmethod
def key(prompt: str, template_version: str = "v1") -> str:
return hashlib.sha256(f"{template_version}\n{prompt}".encode()).hexdigest()
def put(self, key: str, text: str) -> None:
self.items[key] = (text, time.monotonic())
def get(self, key: str, max_age: float | None = None):
entry = self.items.get(key)
if entry is None:
return None
text, stored = entry
if max_age is not None and time.monotonic() - stored > max_age:
return None
return text
def answer(prompt, providers, cache, static_message, stale_max_age=86400.0):
key = cache.key(prompt)
primary_name = providers[0][0]
for name, call in providers:
try:
text = call(prompt)
except LLMUnavailable as exc:
print(f" {name} failed: {exc}")
continue
cache.put(key, text)
return Answer(text, name, degraded=(name != primary_name))
cached = cache.get(key, max_age=stale_max_age)
if cached is not None:
return Answer(cached, "cache", degraded=True)
return Answer(static_message, "static", degraded=True)
def flaky_primary(prompt):
raise LLMUnavailable("503 after 5 attempts")
def small_model(prompt):
return f"[small model] answer to: {prompt}"
cache = AnswerCache()
both = [("primary", flaky_primary), ("fallback", small_model)]
message = "The assistant is unavailable right now. Please try again in a few minutes."
runs = [
("1", "What is a token?", both),
("2", "What is a token?", both[:1]), # the fallback is down
("3", "What is a context window?", both[:1]), # nothing cached
]
for label, prompt, chain in runs:
result = answer(prompt, chain, cache, message)
print(label, result.source, f"degraded={result.degraded}:", result.text)Run 1 fails on the primary and succeeds on the fallback. Run 2 finds no working provider, so it serves the answer cached by run 1. Run 3 has no cached answer, so it returns the static message.
In production, wrap each provider call in the retry logic from the earlier chapters. Put the circuit breaker in front of each provider so an open breaker skips straight to the next tier without waiting.
Telling the caller what happened
A degraded answer that looks like a normal one hides a problem. Return the source and the degraded flag, as Answer does, and let the layers above decide what to do.
- In a user interface, show a short notice such as "Showing a saved answer from earlier" for cached results.
- For an API you expose, add a response field or header that names the source.
- For automated pipelines, consider failing the step instead of continuing on a fallback. A batch job that grades documents should not silently switch to a weaker grader.
Log the tier on every request and count how often each tier is used. A rising fallback rate is an early warning of a provider problem. It can also reveal that the primary has been failing for days and nobody noticed because users still got answers.
Recovery and common mistakes
Recovery should need no manual step. The circuit breaker's probe calls will find the primary healthy again, and traffic returns to tier 1.
Watch for these mistakes.
- Falling back on permanent errors. A 401 or a malformed request fails on any provider. Fix the cause.
- Untested fallbacks. A fallback that has never run in production often fails the first time it is needed. Send a small share of traffic through it, or run a scheduled check.
- Overloading the fallback. When the primary fails, all traffic moves to the fallback at once. Check its rate limits, and throttle on the client as covered earlier.
- Serving stale answers without a limit. Set a maximum age for the stale-if-error path.
- A fallback that cannot fail safely. The last tier must not call an external service. A static message works whatever else is down.
Exercise
Your primary model returns 503 errors for two minutes. Your fallback is a model from another provider with a 16,000-token context window, and your primary accepts 128,000 tokens. A user submits a 40,000-token document. What should the application do, and which tier should answer?
Show answer
Do not send the document to the fallback, because it would be rejected with a 400 error that no retry can fix. Check the input size before choosing a tier. Skip the fallback for this request and go to the next tier. Return a cached answer if one exists for this exact document and template version, or a static message explaining that the service is temporarily unavailable. Log the skipped fallback and the reason so the gap in coverage is visible.
Exercise
A support chatbot caches answers by a hash of the user's question only. After you edit the system prompt, users start receiving old-style answers during an outage. What went wrong, and how do you fix it?
Show answer
The cache key leaves out the system prompt or template version, so answers produced under the old prompt are still served. Include a template version, or a hash of the system prompt, in the key. If answers contain user-specific data, also include the user or tenant ID. After the change, old entries stop matching and expire.