Sub topic 7
Fallback strategies: cache, defaults, simplified features, alternatives
This chapter assumes you know how timeouts, retries, and circuit breakers work. Those tools detect that a dependency is failing. A fallback decides what the caller does next. This chapter covers four common fallbacks and how to choose between them.
What a fallback is
A fallback is a planned alternative result that a function returns when its normal call fails. The caller still gets a usable answer, but a weaker one. Each fallback trades some correctness, freshness, or quality for availability.
You choose a fallback per feature, based on the critical-versus-optional classification you made earlier. A critical dependency often has no safe fallback, and failing clearly is the right behavior.
The four strategies
| Strategy | What the user gets | Main risk |
|---|---|---|
| Cached data | The last known good result | Stale or outdated data |
| Default value | A generic, safe answer | Not personalized or accurate |
| Simplified feature | A cheaper version of the feature | Lower quality, extra code to maintain |
| Alternative provider | The same answer from another source | Cost, inconsistency, shared failure |
Cached data
Serve the last successful response when the live call fails. The following example is from the earlier code. It saves each success and falls back to it on failure.
import time
_cache = {}
def get_recommendations(user_id, fetch, timeout=0.5):
"""Return recommendations, falling back to cached or default data."""
try:
items = fetch(user_id, timeout=timeout)
_cache[user_id] = (items, time.monotonic())
return {"items": items, "degraded": False}
except (TimeoutError, ConnectionError):
if user_id in _cache:
items, _ = _cache[user_id]
return {"items": items, "degraded": True, "source": "cache"}
return {"items": [], "degraded": True, "source": "default"}The function stores a timestamp but never checks it. In production, decide the maximum age you will serve. Product recommendations can be hours old. Account balances or stock levels usually cannot.
Default values
When no cache exists, return a safe constant. The function above returns an empty list. Other good defaults are a popular-items list, a generic greeting, or "feature unavailable". A default must be harmless when wrong. A default of "no fraud detected" is dangerous. A default of "no recommendations" is not.
Simplified features
Replace an expensive feature with a cheaper one. Search can fall back from ranked, personalized results to a plain database LIKE query. A checkout page can skip live shipping estimates and show a flat rate. This is more work than a cache because you maintain two code paths, so reserve it for features users value highly.
Alternative providers
Try a second source for the same data. This works well for payments, maps, email, and other commodity services.
def get_price(sku, providers, timeout=0.5):
"""Try each (name, fetch) provider in order and report which one answered."""
primary = providers[0][0]
for name, fetch in providers:
try:
price = fetch(sku, timeout=timeout)
return {"price": price, "source": name, "degraded": name != primary}
except (TimeoutError, ConnectionError):
continue
raise LookupError(f"no provider could price {sku}")The function raises an error when every provider fails. That is intentional. If no fallback is safe, surfacing the failure is better than inventing a price.
Choosing a strategy
You can chain fallbacks. A common order is live call, then cache, then default. Put the highest-quality option first and the safest last.
Common errors
- Fallbacks that share the failure. A cache stored in the same database that just failed is no fallback. An alternative provider hosted in the same region and network path may fail together with the primary.
- Untested fallbacks. A fallback that has never run in production often fails the first time it is needed. A later chapter covers fault injection.
- Silent degradation. If callers cannot tell that a result is a fallback, nobody notices the problem and users may trust bad data. Both examples above include a
degradedflag and asourcefield for this reason. - Slow fallbacks. A fallback that makes its own long network call defeats the purpose. Keep fallbacks fast, local, and simple.
- Caching errors. Store only successful responses. Never cache a failure and serve it as data.
Exercise
A checkout service calls a tax-calculation service. It times out. A teammate proposes falling back to a cached tax rate from the last successful call for any customer. Should you accept this? What would you check first?
Show answer
Not without checking. Tax is arguably critical because a wrong amount creates legal and billing errors. Check whether the cache is keyed by location and product type, how old the entry can be, and whether the rate is allowed to be approximate. If not, fail clearly or retry with an alternative tax provider. If the cache is acceptable, set a maximum age and mark the order as using an estimated rate so it can be corrected later.