Sub topic 7
Fallback strategies: cache, defaults, simplified features, alternatives
This chapter assumes you have read the earlier chapters on timeouts, retries, and circuit breakers. You should be comfortable with exceptions in Python and with the idea of a dependency that is slow, failing, or only partly available.
Timeouts, retries, and circuit breakers all answer the same question: when should we stop waiting on a dependency? A fallback answers the next question: what do we return instead? Without a planned answer, the caller still gets an error, just a faster one.
What a fallback is
A fallback is a prepared alternative response that a service returns when the preferred path fails or is skipped. The preferred path might be a call to a recommendation service, a payment provider, or a database replica. The fallback is the behavior you decided on in advance, while things were calm.
Good fallbacks share three properties:
- They are cheaper and more reliable than the primary path. A fallback that calls another fragile service only moves the problem.
- They are honest. The response is less complete or less fresh, and the system knows it.
- They are decided per feature. There is no single fallback that suits every dependency.
The four common strategies are cached data, default values, simplified features, and alternative providers. They differ in how much of the original value they keep and in how much they risk being wrong.
| Strategy | What the user gets | Main risk | Typical fit |
|---|---|---|---|
| Cached data | The last known good answer | Stale or wrong data | Read-heavy, slowly changing data |
| Default value | A generic, safe answer | Not personalized or useful | Optional enhancements |
| Simplified feature | A cheaper version of the feature | Lower quality, extra code to maintain | Search, ranking, pricing display |
| Alternative provider | The same answer from another source | Different behavior, extra cost | Payments, email, maps, SMS |
How fallbacks fit into the call path
A fallback is triggered by a failure signal. That signal can be an exception, a timeout, or an open circuit breaker that refuses to make the call at all. The order of the layers matters.
Two points follow from this diagram. First, retries come before the fallback, because a transient error is often cheaper to repair than to work around. Second, the total time spent before the fallback runs is the timeout multiplied by the number of attempts, plus the backoff delays. If your caller has a one-second budget, a fallback that starts after three seconds is useless. Budget the whole sequence, not each call.
Strategy 1: cached data
Serving cached data means returning the last good answer when a fresh one is not available. This is the most common fallback because it preserves the real shape and meaning of the response.
The earlier code sample shows the pattern. It calls the dependency with a short timeout, stores each success with a timestamp, and on failure returns the stored value.
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"}Notice that the function stores a timestamp but never uses it on the fallback path. That is the first weakness to fix when you use this pattern for real.
Stale data policy
Stale data is data older than the system would normally accept. Decide in advance how stale is too stale, for each kind of data.
- A product catalog entry that is two hours old is usually fine.
- A recommendation list that is a day old is probably fine.
- An account balance that is ten minutes old may be dangerous to show as current.
- A feature flag or permission that is stale can be a security problem. Granting access from a cache after it was revoked is a failure, not a degradation.
A simple rule is to give each cache entry a "serve-stale-until" limit that is longer than its normal time to live (TTL). Within the normal TTL, you serve the cache without calling the dependency. After it, you try the dependency. If the call fails and the entry is still within the stale limit, you serve it. Beyond the stale limit, you fall through to a default or an error.
import time
_cache = {}
def get_with_stale_limit(key, fetch, ttl=60.0, max_stale=3600.0, timeout=0.5):
now = time.monotonic()
entry = _cache.get(key)
if entry is not None and now - entry["stored_at"] < ttl:
return {"value": entry["value"], "degraded": False, "source": "cache"}
try:
value = fetch(key, timeout=timeout)
except (TimeoutError, ConnectionError):
if entry is not None and now - entry["stored_at"] < max_stale:
age = now - entry["stored_at"]
return {"value": entry["value"], "degraded": True,
"source": "stale-cache", "age_seconds": round(age)}
raise
_cache[key] = {"value": value, "stored_at": now}
return {"value": value, "degraded": False, "source": "live"}Cache pitfalls
- A cold cache gives no protection. After a restart or a deploy, the cache is empty, and an outage at that moment has no fallback. Warm important entries at startup, or use a shared cache that survives restarts.
- Per-process caches diverge. Each instance of the service holds different entries, so users see different answers depending on which instance they reach.
- Unbounded caches leak memory. The sample above never evicts anything. Use a bounded cache, such as an LRU (least recently used) cache, in production.
- Never cache errors as results. If a failed call returns an empty list and you store it, you have turned a brief outage into a long one.
- Cache keys must include everything that changes the answer. Locale, user, and permission level are common omissions.
Strategy 2: default values
A default value is a fixed, safe response that needs no live data. In the sample above, the final branch returns an empty list. For a "recommended for you" panel, an empty list may mean the panel disappears, which is acceptable.
Defaults can be richer than empty:
- A "popular items" list computed once an hour and shipped with the service.
- A generic avatar when the profile image service is down.
- A conservative default such as "no discount applied" or "shipping estimate unavailable".
The key question is whether the default is safe when it is wrong. Showing a generic avatar is harmless. Defaulting a fraud check to "approved" is not. When a default hides a failure that has consequences, prefer to fail the operation clearly or to defer it for later, not to guess.
Strategy 3: simplified features
A simplified feature is a cheaper, lower-quality version of the real feature that runs without the failing dependency. It keeps the user's goal alive while dropping the sophisticated part.
Examples:
- Personalized search ranking is down, so results are sorted by popularity or by plain text match.
- A real-time shipping calculator fails, so the checkout shows a flat rate and confirms the exact cost later.
- A machine-learning image tagger is unavailable, so the upload succeeds and tagging happens afterward from a queue.
- A live inventory count is unavailable, so the page shows "in stock" or "limited stock" without a number.
The last two examples show a related technique: defer the work. The service accepts the request, records it, and completes the expensive part later. This works when the user does not need the result immediately and the operation can be repeated safely.
Simplified features cost more than the other strategies, because they are extra code that must be kept correct. They are also the code path used least often, so they rot quietly. Keep them small, and test them as described in the fault-injection chapter.
Writing a simplified path
The function below tries a ranked search first. If the ranking service fails, it runs a plain keyword match over local data.
def search_products(query, ranker, catalog):
"""Rank results with a remote service, or fall back to keyword match."""
matches = [p for p in catalog if query.lower() in p["name"].lower()]
try:
order = ranker(query, [p["id"] for p in matches], timeout=0.3)
position = {pid: i for i, pid in enumerate(order)}
matches.sort(key=lambda p: position.get(p["id"], len(position)))
return {"results": matches, "degraded": False}
except (TimeoutError, ConnectionError):
matches.sort(key=lambda p: p["name"])
return {"results": matches, "degraded": True, "source": "keyword-only"}The cheap work, filtering, happens before the remote call. That makes the fallback nearly free, because the data it needs is already in hand.
Strategy 4: alternative providers
An alternative provider is a second source that can do the same job. Payment gateways, email delivery, SMS, geocoding, and object storage are common cases, because there are interchangeable vendors or regions.
def send_with_failover(message, providers):
"""Try each provider in order and return the first success."""
last_error = None
for name, send in providers:
try:
send(message, timeout=1.0)
return {"sent_by": name, "degraded": name != providers[0][0]}
except (TimeoutError, ConnectionError) as exc:
last_error = exc
raise RuntimeError("all providers failed") from last_errorAlternative providers are powerful and also the easiest strategy to get wrong:
- Behavior differs. Two payment providers may use different error codes, retry rules, and fee structures. Hide them behind one interface and test both.
- Duplicates. If the first provider timed out but actually completed the work, the second provider repeats it. A customer is charged twice or receives two emails. Use idempotency keys, which are unique identifiers that let a provider recognize and ignore a repeated request, wherever the operation changes state.
- Cost and limits. The backup may be more expensive or have lower quotas. A primary outage can send all traffic to a backup that cannot take it.
- Untested standby. A provider that carries no traffic may have expired credentials or stale configuration. Send a small share of real traffic through it, or run regular checks.
- Shared failure. Two providers that both run in one cloud region, or that both use one DNS service, can fail together.
Choosing a strategy
Start from the feature, not the technology. Ask these questions in order:
- Does the feature need fresh data to be correct? If yes, caching is dangerous, and you should consider failing clearly or deferring the work.
- Can a stale or generic answer cause harm? If yes, choose a safe default such as "deny", or hold the operation for review.
- Is there a cheaper way to deliver most of the value? If yes, build a simplified feature.
- Is there an interchangeable second source, and is the operation safe to repeat? If yes, consider an alternative provider.
Strategies also stack. A common order is live call, then cache, then a default. A payment flow might use primary provider, then secondary provider, then "pending, we will confirm by email".
Fallbacks and the other layers
Fallbacks interact with the mechanisms from earlier chapters.
- Circuit breaker. When the circuit is open, the fallback is the only path, so it must handle the full load. Cheap, local fallbacks survive this. A fallback that calls another remote service may fail under that load.
- Retries. Do not retry inside the fallback in a way that multiplies traffic. A fallback should normally try once, or not call out at all.
- Timeouts. Give the fallback its own small budget. A cache lookup that hangs is as bad as the original failure.
- Return shape. A fallback should return the same structure as the primary path, with extra fields that mark it as degraded. Callers that must handle two different shapes will break in unexpected places.
Marking degraded responses
Every sample in this chapter returns a degraded flag and a source field. This is deliberate. Without it, the service can serve stale or approximate data for hours and nobody notices. The flag lets callers adapt, lets the user interface show a notice such as "Showing saved results", and gives you a metric to count. The later chapter on visibility covers this in detail. For now, treat the marker as a required part of any fallback, not an extra.
Common mistakes
- Writing the fallback but never running it, so the first real test is a production outage.
- Catching every exception, including programming errors such as a
KeyError, and hiding bugs behind a quiet fallback. Catch the specific failures that mean "dependency unavailable". - Using a fallback for a critical dependency where the right behavior is to fail clearly. A wrong answer is sometimes worse than no answer.
- Letting the fallback look like normal behavior, with no flag, log, or metric.
- Forgetting to recover. Once the dependency returns, the service must go back to live data and not keep serving the cache.
Exercise
A checkout service calls a tax-calculation service. It is down for ten minutes. You consider three fallbacks: (a) reuse the tax amount from the customer's last order, (b) apply a flat 0% tax, (c) apply the standard tax rate for the customer's region and mark the order "tax to be confirmed". Which would you choose, and what two safeguards would you add?
Show answer
Choose (c). Option (a) is wrong because the last order may have had different items or a different address. Option (b) fails unsafely, since it under-charges tax and creates legal and accounting errors. Option (c) is a simplified feature with a defensible approximation. Safeguards: mark the order and the response as degraded so finance can reconcile later, and record the order so that tax is recalculated and corrected, or the customer is notified, once the tax service recovers. A metric on the number of orders placed with estimated tax would also help.
Exercise
Your cache-based fallback returns the stored value on any failure and stores new values on success. During an incident, users see data that is three days old, and nobody noticed for hours. Name two code changes that would have limited the damage.
Show answer
First, add a maximum stale age so that entries older than the limit are not served, and the function falls through to a default or an explicit error. Second, expose the degraded state: return a degraded flag and the age of the data, emit a metric or log line each time the stale cache is served, and alert when the rate stays high.