Stampedes and stale values¶
Prevent thundering herds on cache misses and serve warm responses without blocking callers on slow recomputations.
In-process single-flight (always on)¶
get_or_set and @ns.cached coalesce concurrent misses for the same key within a process into a single loader execution. If the store cannot be read, or the cache is disabled, every caller runs the loader itself. @ns.response and ResponseCacheMiddleware are not single-flight: see Response caching and stampedes.
The loader runs in a detached task so one caller disconnecting does not abort peers; it is only cancelled if all waiters disconnect. If the loader raises, nothing is cached and the exception propagates to all waiters.
Best-effort cross-process locks (lock=True)¶
Across multiple workers, enable lock=True on a shared store (RedisStore) to coordinate recomputation:
reports = cache.namespace("report", ttl=3600)
# Best-effort cross-process lock: one worker computes on a miss while peers wait
# up to `lock_wait` before falling back to computing it themselves.
@reports.cached("monthly", lock=True)
async def monthly(month: str) -> dict[str, int]:
return await build_report(month)
@app.get("/reports/{month}")
async def report(month: str) -> dict[str, int]:
return await monthly(month)
get_or_set takes lock=True as well:
async def monthly_report(month: str) -> dict[str, int]:
# On a miss, one worker takes the store's lock and builds the report. The
# others wait for it to appear, for up to the cache's `lock_wait`.
return await reports.get_or_set(
month, lambda: build_report(month), type=dict[str, int], lock=True
)
One worker acquires the store lock and computes the value while other workers wait for the value to appear. Cross-process locking is best-effort coordination, not an exactly-once guarantee:
- Lock expiry (
lock_ttl=30s): Auto-expires if the holder crashes; set higher than expected computation time. - Bounded wait (
lock_wait=5s): Waiters fall back to computing the value themselves afterlock_wait, so a slow loader (e.g., 10s with defaultlock_wait=5) may still run in multiple workers. - Fail-open on store error: If lock acquisition fails, the caller computes the value immediately.
Set lock_ttl= and lock_wait= on the Cache:
# Values in this cache compute in well under a second, so both times are set below
# their defaults of 30s and 5s: a lock whose holder crashed expires after 2s, and a
# worker waits 0.5s for another worker's value before computing its own.
cache = Cache(store, lock_ttl=2, lock_wait=0.5)
lock=True adds 3 store round trips to a miss for the worker that takes the lock. A worker that waits polls instead (one read and one lock attempt every 20–200 ms) until the value appears or lock_wait passes. Reserve it for expensive computations.
Note on Redis token_ttl: on a miss, RedisStore creates generation tokens with token_ttl=300s (5 minutes). If a loader takes longer than token_ttl, its tokens expire before write-back and the result won't be stored—increase RedisStore(client, token_ttl=...) for multi-minute computations.
Stale-while-revalidate and proactive refresh¶
Serve cached values immediately while refreshing in the background:
shop = cache.namespace("shop")
# Fresh for 60s; for 300s after expiry, serve stale immediately and refresh in background.
@shop.cached("stock", ttl=60, stale=300)
async def stock() -> dict[str, int]:
return await warehouse.stock()
# Fresh for 1h; once 10 minutes old, trigger a proactive background refresh on access.
@shop.cached("prices", ttl=3600, refresh_after=600)
async def prices() -> dict[str, int]:
return {"tea": 4 + (await warehouse.stock())["counted"]}
stale=: Forstaleseconds after TTL expiry, return the expired value immediately and trigger one background refresh.refresh_after=: Once an entry's age exceedsrefresh_after(while still withinttl), return it immediately and refresh in the background. Leave more than one loader duration betweenrefresh_afterandttlso active entries stay warm.- Combine with
lock=Trueto coordinate background refreshes across workers (except behindTieredStore, where each worker with an L1 copy may refresh once).
Important constraints:
- Background refreshes run after the HTTP response returns, so the decorated function must not depend on request-scoped resources (like a closed DB session dependency).
- Background refresh errors are logged and emitted to observers; the existing value continues serving while valid, and refresh retries after a brief backoff.
- Await
cache.drain()during application shutdown so in-flight background refreshes complete cleanly:
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
yield
# Wait for in-flight background refreshes before shutdown.
await cache.drain()
app = FastAPI(lifespan=lifespan)
TTL jitter¶
Avoid synchronized expiration spikes by passing jitter= (fraction of TTL, e.g., Cache(jitter=0.1) or per namespace). A 600s TTL with jitter=0.1 stores computed values for a random duration between 540s and 600s. Explicit set() calls keep their exact TTL; with refresh_after=, jitter applies to the refresh threshold instead of the TTL.
Set a default on the cache and override it for one namespace:
# Each loaded value is cached for a random 90-100% of its TTL, so values loaded at
# the same moment do not all expire, and reload, at the same moment.
cache = Cache(store, jitter=0.1)
users = cache.namespace("user", ttl=600)
# Every rate is loaded when the app starts. This namespace overrides the cache's
# jitter to spread them further: each is cached for 50-100% of the hour.
rates = cache.namespace("rate", ttl=3600, jitter=0.5)
Response caching and stampedes¶
@ns.response does not coalesce concurrent misses directly (see Concurrent misses). Either move expensive work into an @ns.cached helper, or place CoalescingMiddleware outside ResponseCacheMiddleware (see Middleware order).