Sub topic 14
Fallback models, cached answers, and graceful degradation
This chapter assumes you can write Python, you know how HTTP status codes work, and you have called an LLM API before. It also assumes you have read the chapters on retries and circuit breakers. Here you decide what the application does when retries are exhausted or the circuit breaker is open.
Why a fallback path matters
A retry loop and a circuit breaker stop wasted calls. They do not give the user an answer. A fallback path is the code that runs when the primary call cannot succeed. Graceful degradation means the application keeps working at reduced quality instead of returning an error page.
Common fallback options
Each option trades answer quality for availability.
| Fallback | Benefit | Cost |
|---|---|---|
| Secondary model from the same provider | Same API, same credentials | May share the same outage or rate limit |
| Model from another provider | Independent failure domain | Different prompt behavior and output format |
| Cached answer | Fast, free, no network call | May be stale or answer a different question |
| Static message | Always available | No useful content |
Order the options from best quality to lowest quality. Try each one only when the one before it fails.
A fallback chain in code
The function below tries a list of callables in order. Each callable takes a prompt and returns text or raises an exception. The last resort is a fixed message.
import logging
logger = logging.getLogger("llm.fallback")
STATIC_MESSAGE = "The assistant is temporarily unavailable. Please try again soon."
def answer_with_fallbacks(prompt, providers, cache):
"""Try each (name, call) pair in order, then the cache, then a static message.
Returns a tuple of (text, source) so callers can tell how the answer was made.
"""
for name, call in providers:
try:
text = call(prompt)
except Exception as exc:
logger.warning("provider %s failed: %s", name, exc)
continue
cache[prompt] = text
return text, name
cached = cache.get(prompt)
if cached is not None:
return cached, "cache"
return STATIC_MESSAGE, "static"
def flaky_primary(prompt):
raise TimeoutError("primary timed out")
def backup(prompt):
return f"Backup answer to: {prompt}"
cache = {}
providers = [("primary", flaky_primary), ("backup", backup)]
print(answer_with_fallbacks("What is a token bucket?", providers, cache))
print(answer_with_fallbacks("Unseen question", [("primary", flaky_primary)], cache))The first call returns the backup answer. The second call has no working provider and no cached entry, so it returns the static message.
Design rules
- Return the source. The caller should know whether the text came from the primary model, a backup, the cache, or the static message. Show a notice to the user for cached or static results.
- Treat prompts as different across models. A prompt tuned for one model can behave differently on another. Test the backup model with your real prompts and check that structured output still parses.
- Cache only what is safe to reuse. Exact-match caches work for repeated questions. Do not serve cached answers for prompts that include personal data, or that depend on the current time or on live data.
- Set a maximum age. A stale answer is acceptable during an outage. It is not acceptable for hours after the service recovers. Store a timestamp and drop old entries.
- Keep fallbacks inside the deadline. Each extra provider adds latency. Share one overall deadline across the whole chain, as described in the timeouts chapter.
Degrading features, not only answers
Degradation can also mean doing less. You can shorten the prompt, skip optional steps such as summarization, or disable a feature that depends on the LLM and show the rest of the page. Choose these reductions ahead of time so the behavior is predictable.
Exercise
Your function returns a cached answer when the primary and backup models both fail. Name two pieces of information you should attach to that answer before showing it to the user, and explain why.
Show answer
Attach the source (for example "cache") and the age of the entry. The source lets the interface tell the user the answer may be out of date. The age lets the application refuse entries older than a set maximum and lets you log how often stale answers are served.