Resilience Patterns · Resilient Data and Dependencies

Caching for Resilience

Serve stale data instead of errors when origins fail.

Create a free account to save this page, take notes and track your progress. Sign in

Caches can do more than speed things up: with stale-if-error and stale-while-revalidate, CDNs and application caches keep serving the last good response when the origin fails. Keep a longer "stale TTL" alongside the fresh TTL, coalesce refreshes, and prevent cold-cache stampedes after restarts by warming critical keys. Beware: if the system can't run without the cache, the cache is now a critical dependency that needs its own redundancy.

Resilient caching techniques

Directive / technique Effect
Cache-Control: stale-if-error=86400 Serve stale up to 1 day when origin errors
stale-while-revalidate=60 Serve stale while refreshing in background
Soft TTL + hard TTL in app cache Refresh after soft TTL; serve stale until hard TTL on failure
Request coalescing One origin fetch per key during misses
Cache warming Avoid cold-start stampedes

Python (soft/hard TTL)

async def get_with_stale(key: str, load, soft_ttl=60, hard_ttl=3600):
    entry = await cache.get(key)                      # {"value":..., "fetched_at":...}
    fresh = entry and time.time() - entry["fetched_at"] < soft_ttl
    if fresh:
        return entry["value"]
    try:
        value = await load()
        await cache.set(key, {"value": value, "fetched_at": time.time()}, ex=hard_ttl)
        return value
    except DependencyError:
        if entry:                                     # origin down: serve stale
            metrics.increment("cache.stale_served")
            return entry["value"]
        raise

Common pitfalls

  • Systems that can't start without a warm cache.
  • Serving stale data for correctness-critical values (balances, stock at checkout).
  • No metric for stale responses.

Key points

  • stale-if-error / soft+hard TTLs
  • Coalesce and warm
  • Know which data may be stale

Further reading: RFC 5861: stale-while-revalidate and stale-if-error

Practice questions

What does stale-if-error do?

Answer

It allows caches to serve a stale cached response for a specified time when the origin returns an error or is unreachable.

Why can a cache become a critical dependency?

Answer

If origin capacity can't handle traffic without the cache's hit ratio, losing or cold-starting the cache overloads the origin, so the cache needs redundancy and warming.

Open in the app to mark lessons complete, take notes and track your progress.

Was this page helpful?