An async TTL cache stores the result of an expensive coroutine, such as a database query or an HTTP call, and reuses it until a time-to-live runs out. The part that makes it correct under load is request coalescing, also called single flight: when many coroutines miss the same key at once, only the first one starts a fetch and the rest await that same fetch. Without it, a popular key that expires triggers a cache stampede, with hundreds of identical requests hitting the backend in the same instant. The standard Python 3.12 design caches the in-flight asyncio.Task per key rather than the value, and wraps each wait in asyncio.shield so one caller giving up doesn't cancel the fetch for everyone else.
This guide shows the stampede, builds the cache in three steps, covers a cache-less single-flight deduplicator with per-caller timeouts, and lists the follow-ups interviewers ask. Every snippet is complete and runs on Python 3.12 or newer.
The stampede
A cache that stores only finished values has a gap. Between the first miss and the first fetch completing, every other caller also misses.
import asyncio
calls = 0
async def fetch(key: str) -> str:
global calls
calls += 1
await asyncio.sleep(0.05)
return key.upper()
class NaiveCache:
def __init__(self) -> None:
self.values: dict[str, str] = {}
async def get(self, key: str) -> str:
if key not in self.values:
self.values[key] = await fetch(key)
return self.values[key]
async def main() -> None:
cache = NaiveCache()
await asyncio.gather(*(cache.get("model-config") for _ in range(100)))
print("fetches:", calls) # fetches: 100
asyncio.run(main())All 100 coroutines check the dict before any fetch finishes, so all 100 fetch. Adding an asyncio.Lock around the whole get fixes the count but serialises every key behind one lock, so a slow fetch for one key blocks hits for all the others.
Cache the task, not the value
Keep a second dict of in-flight tasks. The first caller to miss creates the task and every later caller awaits the same one. When the task finishes, a done callback moves its result into the value dict with an expiry time and removes the in-flight entry.
import asyncio
import time
from collections.abc import Awaitable, Callable, Hashable
from typing import Any
class TTLCache:
def __init__(self, ttl: float, clock: Callable[[], float] = time.monotonic) -> None:
self.ttl = ttl
self.clock = clock
self.values: dict[Hashable, tuple[Any, float]] = {}
self.inflight: dict[Hashable, asyncio.Task] = {}
async def get(self, key: Hashable, fetch: Callable[[Hashable], Awaitable[Any]]) -> Any:
hit = self.values.get(key)
if hit is not None and hit[1] > self.clock():
return hit[0]
task = self.inflight.get(key)
if task is None:
task = asyncio.ensure_future(fetch(key))
self.inflight[key] = task
task.add_done_callback(lambda t: self._finish(key, t))
return await asyncio.shield(task)
def _finish(self, key: Hashable, task: asyncio.Task) -> None:
if self.inflight.get(key) is task:
del self.inflight[key]
if not task.cancelled() and task.exception() is None:
self.values[key] = (task.result(), self.clock() + self.ttl)
calls = 0
async def fetch(key: str) -> str:
global calls
calls += 1
await asyncio.sleep(0.05)
return key.upper()
async def main() -> None:
cache = TTLCache(ttl=60)
results = await asyncio.gather(*(cache.get("a", fetch) for _ in range(100)))
print(set(results), "fetches:", calls) # {'A'} fetches: 1
await asyncio.gather(cache.get("a", fetch), cache.get("b", fetch))
print("fetches:", calls) # fetches: 2
asyncio.run(main())A few choices here are deliberate, and interviewers probe each one.
- The hit check uses
is not Noneon the tuple, not on the value. A cachedNone,0,Falseor""is still a hit. Writingif self.values.get(key):refetches every falsy value forever. - The expiry starts when the fetch completes, not when it started. A fetch that took two seconds with a 60-second TTL gives 60 seconds of freshness.
- Failures are not cached. The done callback stores only successful results, so the next
getafter an error tries again. Every caller who was waiting on the failed fetch gets the same exception. task.exception()in the callback marks the exception as retrieved. Without that, a failed fetch whose callers were all cancelled logs "Task exception was never retrieved" when it is garbage collected.- The callback is registered before anyone awaits, so it runs before the waiting callers resume. By the time they return, the value is already cached.
Why the shield matters
When a coroutine awaiting a task is cancelled, the cancellation passes into the task it awaits. Without asyncio.shield, the first caller timing out cancels the shared fetch, and every other caller waiting on it gets a CancelledError they never asked for.
import asyncio
async def fetch() -> str:
await asyncio.sleep(0.05)
return "value"
async def waiter(task: asyncio.Task, shielded: bool) -> str:
return await (asyncio.shield(task) if shielded else task)
async def run(shielded: bool) -> str:
shared = asyncio.ensure_future(fetch())
impatient = asyncio.create_task(waiter(shared, shielded))
patient = asyncio.create_task(waiter(shared, shielded))
await asyncio.sleep(0.01)
impatient.cancel()
[got] = await asyncio.gather(patient, return_exceptions=True)
shown = type(got).__name__ if isinstance(got, BaseException) else repr(got)
return f"shielded={shielded}: patient got {shown}"
async def main() -> None:
print(await run(shielded=False))
print(await run(shielded=True))
asyncio.run(main())
# shielded=False: patient got CancelledError
# shielded=True: patient got 'value'With the shield, the cancelled caller stops waiting and the fetch keeps running. Its result is still cached, so even if every caller gives up, the next request is a hit. A request that arrives while the fetch is still running joins it, even when all the earlier callers have been cancelled, because the in-flight entry stays until the task itself finishes.
TTL expiry and failures, tested with a fake clock
Injecting the clock makes expiry testable without sleeping for the TTL.
import asyncio
from collections.abc import Hashable
from typing import Any
class TTLCache:
def __init__(self, ttl: float, clock) -> None:
self.ttl, self.clock = ttl, clock
self.values: dict[Hashable, tuple[Any, float]] = {}
self.inflight: dict[Hashable, asyncio.Task] = {}
async def get(self, key, fetch):
hit = self.values.get(key)
if hit is not None and hit[1] > self.clock():
return hit[0]
task = self.inflight.get(key)
if task is None:
task = asyncio.ensure_future(fetch(key))
self.inflight[key] = task
task.add_done_callback(lambda t: self._finish(key, t))
return await asyncio.shield(task)
def _finish(self, key, task) -> None:
if self.inflight.get(key) is task:
del self.inflight[key]
if not task.cancelled() and task.exception() is None:
self.values[key] = (task.result(), self.clock() + self.ttl)
now = 0.0
calls = 0
async def flaky(key: str) -> int:
global calls
calls += 1
if calls == 2:
raise ConnectionError("backend blip")
return calls
async def main() -> None:
global now
cache = TTLCache(ttl=10, clock=lambda: now)
print(await cache.get("k", flaky)) # 1
now = 9.9
print(await cache.get("k", flaky)) # 1
now = 10.0
try:
await cache.get("k", flaky)
except ConnectionError as exc:
print("error:", exc) # error: backend blip
print(await cache.get("k", flaky)) # 3
asyncio.run(main())At now = 10.0 the entry has expired, the refetch fails, and the failure is not cached, so the very next get fetches again and succeeds.
Single flight without a cache
Sometimes you want coalescing but no caching, for example for a value that must always be fresh but is expensive to compute. Drop the value dict and keep only the in-flight map. Per-caller timeouts are a common addition, and asyncio.wait_for around the shield gives each caller its own deadline without touching the shared work.
import asyncio
class SingleFlight:
def __init__(self) -> None:
self.inflight: dict[object, asyncio.Task] = {}
async def do(self, key, fn, timeout: float | None = None):
task = self.inflight.get(key)
if task is None:
task = asyncio.ensure_future(fn())
self.inflight[key] = task
task.add_done_callback(lambda t: self._forget(key, t))
return await asyncio.wait_for(asyncio.shield(task), timeout)
def _forget(self, key, task) -> None:
if self.inflight.get(key) is task:
del self.inflight[key]
if not task.cancelled():
task.exception()
calls = 0
async def load() -> str:
global calls
calls += 1
await asyncio.sleep(0.05)
return f"report v{calls}"
async def main() -> None:
group = SingleFlight()
results = await asyncio.gather(
group.do("report", load, timeout=0.01),
group.do("report", load),
group.do("report", load),
return_exceptions=True,
)
print([type(r).__name__ if isinstance(r, Exception) else r for r in results])
print(await group.do("report", load), "| entries left:", len(group.inflight))
asyncio.run(main())
# ['TimeoutError', 'report v1', 'report v1']
# report v2 | entries left: 0The impatient caller times out at 10 ms while the other two get the shared result. The next call after the fetch finished starts a new one, because nothing is cached. The done callback removes each entry when its task finishes, so the map holds only keys with work in flight, even when every caller timed out and nobody is left to clean up.
Follow-ups interviewers ask
Memory and eviction
The value dict above never forgets an expired key unless it is requested again. Delete expired entries on read, sweep periodically, or bound the cache with an LRU. An OrderedDict with move_to_end(key) on every hit and popitem(last=False) when full gives O(1) LRU eviction.
Stale-while-revalidate
Instead of making callers wait when an entry expires, return the stale value immediately and start one background refresh. Callers never see refresh latency, at the cost of occasionally reading a value slightly past its TTL. The in-flight map keeps the refresh single-flight.
Expiry jitter
If a thousand keys are loaded at startup with the same TTL, they all expire together and the stampede comes back in a different form. Add a small random amount to each expiry, for example ttl * random.uniform(0.9, 1.1).
Negative caching
Not caching failures protects correctness, but a backend that is down gets hammered by every miss. Caching a "not found" or an error for a short TTL, such as a second, is a reasonable middle ground. Combine it with a circuit breaker when the backend is unhealthy for long.
Threads and multiple processes
This cache is safe within one event loop because the miss check and the self.inflight[key] = task assignment run with no await between them. Across threads you need a lock. Across processes or machines you need a shared cache such as Redis, and the single-flight step becomes a short-lived lock key with SET key value NX PX 5000, with the other callers polling or subscribing for the result.
Why not functools.lru_cache?
On an async function, lru_cache caches the coroutine object, not its result. The second caller gets a coroutine that has already been awaited and fails with RuntimeError. It also has no TTL. Libraries such as async-lru and aiocache fill that gap in production.
Common mistakes
- Caching values only. Concurrent misses all fetch.
- Truthiness checks on the cached value.
None,0and""are never treated as hits. - Awaiting the shared task without
shield. One cancelled caller cancels the fetch for everyone. - Caching exceptions by accident, for example by storing the task itself as the cached value after it failed.
- Never removing in-flight entries, or removing them from the caller's
finally. If every caller is cancelled, no caller is left to clean up. Use a done callback on the task. - TTL measured from the start of the fetch. Slow fetches get shorter freshness than specified.
Practise it
Two problems cover this pattern from different sides. Async TTL Cache with Request Coalescing asks for the cache, including cached falsy values and fetches that survive every caller being cancelled (30 minutes). Async Request Deduplicator asks for single flight with per-caller timeouts and no memory growth for finished keys (35 minutes).
- 20Dynamic Request Batcherhard
Group concurrent inference requests into batches that flush when full or when the oldest request has waited long enough, with cancellation and drain.
- 21Async TTL Cache with Request Coalescingmedium
Build an asyncio cache whose entries expire after a TTL, where concurrent misses for the same key share one fetch that survives caller cancellation.
- 22Async Retry with Exponential Backoffmedium
Retry a failing coroutine with capped exponential backoff, re-raise the last error, and never swallow cancellation.
- 25Async Request Deduplicatorhard
Collapse concurrent fetches for the same key into one shared call, with per-caller timeouts that never cancel the shared work.
The caching and deduplication topic pages collect related problems. The asyncio interview guide covers shield, cancellation and timeouts in more depth.
Frequently asked questions
What is request coalescing?
When several callers ask for the same key at the same time, only the first starts the backend request and the others wait for that same request. It is also called single flight, after the Go package of that name, and it prevents a cache stampede when a popular key expires.
What is a cache stampede?
A burst of identical backend requests that happens when a popular cache entry is missing or expires and many callers miss at once. Each caller fetches the same value, which can overload the backend exactly when the cache stops protecting it.
How do I make a TTL cache for async functions in Python?
Keep a dict of cached values with their expiry time and a dict of in-flight asyncio tasks per key. On a miss, reuse the in-flight task if there is one, otherwise create it. Await it through asyncio.shield, and in a done callback store successful results with an expiry and remove the in-flight entry.
Why use asyncio.shield in a shared cache fetch?
Cancelling a coroutine that awaits a task also cancels that task. Without shield, the first caller to time out or be cancelled would cancel the shared fetch for every other caller waiting on it. With shield, only the cancelled caller stops waiting.
Does functools.lru_cache work with async functions?
Not correctly. It caches the coroutine object, which can only be awaited once, so the second call raises RuntimeError. It also has no TTL. Use a hand-written cache like the one in this guide or a library such as async-lru.
Should a cache store failed results?
Usually not, so the next request can retry after a transient error. Some systems cache failures or not-found results for a very short TTL to protect a backend that is down, which is called negative caching.