Recipe 3.4 · Python
Preventing Cache Stampedes
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
A dashboard summary takes eight seconds to compute and is cached for five minutes. Every five minutes the entry expires, and every request that arrives in the next eight seconds misses, so instead of one query the database gets fifty copies of its most expensive one. This is a cache stampede, and it tends to happen at the busiest time of day, because that is when the most requests arrive during the gap.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
This prevents the stampede, but every reader of every cache entry behind that lock now queues behind the eight-second build. And you cannot await inside a lock, so it cannot become async.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""A global lock around every cache read
Source: ImproveCode, Chapter 3, Recipe 3.4 "Preventing Cache Stampedes"
Section: The way it's often written
Book page: 68 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
lock(Sync) -> module-level threading.Lock; HttpRuntime.Cache with absolute expiry -> dict of
(value, expires_at) using local time, as DateTime.Now does.
"""
import threading
from datetime import datetime, timedelta
from typing import Any
HTTP_RUNTIME_CACHE: dict[str, tuple[Any, datetime]] = {}
# Not to copy: a global lock around every cache read.
SYNC = threading.Lock()
def build_summary() -> Any:
raise NotImplementedError
def get_summary() -> Any:
with SYNC:
item = HTTP_RUNTIME_CACHE.get("Dashboard")
s = item[0] if item and item[1] > datetime.now() else None
if s is None:
s = build_summary() # 8 seconds, holding the lock
HTTP_RUNTIME_CACHE["Dashboard"] = (
s, datetime.now() + timedelta(minutes=5))
return s
The improved recipe
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Single-flight cache: one load per key while callers share the result
Source: ImproveCode, Chapter 3, Recipe 3.4 "Preventing Cache Stampedes"
Section: The improved recipe
Book page: 68-69 -- original C# listing
Converted from C# to Python.
ConcurrentDictionary<Lazy<Task>> -> dict of asyncio.Task (the event loop makes check-and-add
atomic); WaitAsync(ct) -> asyncio.shield, so one caller's cancellation never cancels the shared
load; IMemoryCache -> MemoryCache stand-in from the Recipe 3.1 file.
"""
import asyncio
from collections.abc import Awaitable, Callable
from datetime import timedelta
from typing import Any
from p060_r3_1_cache_aside_get_or_create import MemoryCache
class SingleFlightCache:
def __init__(self, cache: MemoryCache) -> None:
self._cache = cache
self._in_flight: dict[str, asyncio.Task[Any]] = {}
async def get_or_create[T](self, key: str,
factory: Callable[[], Awaitable[T]],
time_to_live: timedelta) -> T:
found, cached = self._cache.try_get(key)
if found:
return cached
load = self._in_flight.get(key)
if load is None:
load = asyncio.create_task(self._load(key, factory, time_to_live))
self._in_flight[key] = load
return await asyncio.shield(load)
def remove(self, key: str) -> None:
self._cache.remove(key)
async def _load[T](self, key: str, factory: Callable[[], Awaitable[T]],
time_to_live: timedelta) -> T:
try:
value = await factory() # not tied to any one caller's cancellation
self._cache.set(key, value, time_to_live)
return value
finally:
self._in_flight.pop(key, None)
How it works
The first request that misses adds a Lazy<Task> for the key to the in-flight dictionary and starts the load. Every request that misses while that load is running gets the same Lazy from GetOrAdd and awaits the same task. The database sees one query, and fifty requests share its result. Requests for other keys are not affected at all.
Lazy<T> matters here. ConcurrentDictionary.GetOrAdd may call its value factory more than once when two threads race, keeping only one result. Wrapping the load in Lazy means the losing factory call only creates an unused Lazy object, and the expensive load still starts exactly once.
When the load finishes, its result goes into the cache and the in-flight entry is removed in the finally block. If the load throws, the exception reaches every waiting caller, nothing is cached, and the next request starts a fresh attempt. Failures are not cached.
The shared load runs with CancellationToken.None, because it belongs to every waiting request, not just the one that started it. Each caller instead waits with WaitAsync(ct) (.NET 6 and later), so a cancelled request stops waiting without cancelling the load for the others.
Register it as a singleton: services.AddSingleton<SingleFlightCache>();.
Variations and pitfalls
- This protects one process. With ten web servers you can still get ten loads. That is usually fine. If it is not, use a distributed lock or let one background job refresh the value.
- Refresh ahead. For values that are expensive and read constantly, have a
BackgroundService(Chapter 14) rebuild the entry on a timer before it expires, so readers never miss. - Jitter. When many entries are created at the same moment, such as at startup, add a few random seconds to each lifetime so they do not all expire together.
- HybridCache. Starting with .NET 9, the
Microsoft.Extensions.Caching.Hybridpackage providesHybridCache, which has this stampede protection built in and adds an optional distributed second level. If you are on .NET 9 or later, prefer it over writing your own:
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Get-or-create the dashboard summary through a stampede-safe cache
Source: ImproveCode, Chapter 3, Recipe 3.4 "Preventing Cache Stampedes"
Section: Variations and pitfalls
Book page: 70 -- original C# listing
Converted from C# to Python.
HybridCache has no standard Python equivalent; the SingleFlightCache from this recipe's
improved file plays its role. Usage fragment wrapped in an async function.
"""
from datetime import timedelta
from typing import Any, Protocol
from p068_r3_4_single_flight_cache import SingleFlightCache
class SummaryBuilder(Protocol):
async def build(self) -> Any: ...
async def get_dashboard_summary(hybrid_cache: SingleFlightCache,
builder: SummaryBuilder) -> Any:
# Usage snippet: create one SingleFlightCache at startup.
summary = await hybrid_cache.get_or_create(
"dashboard:summary",
builder.build,
timedelta(minutes=5))
return summary