No. 21medium30 min14 tests

Async TTL Cache with Request Coalescing

Description

A model-config service is slow and gets hit by many coroutines asking for the same keys at once. Put a cache in front of it that never sends two identical requests at the same time.

class AsyncTTLCache:
    def __init__(self, ttl_seconds: float): ...
    async def get(self, key, fetch_fn): ...

fetch_fn(key) is an async function that returns a value or raises.

  • On a hit, get returns the cached value without calling fetch_fn.
  • On a miss, get calls fetch_fn(key), caches the value and returns it.
  • A cached value expires ttl_seconds after its fetch completed. After that the next get fetches again.
  • Request coalescing: while a fetch for a key is in flight, every other get for that key waits for that same fetch instead of starting another. They all get its value, or all get its exception. Gets for different keys fetch concurrently.
  • Failures are not cached. The next get after a failed fetch tries again.
  • Cancelling a caller does not cancel the shared fetch. Even if every waiting caller is cancelled, the fetch runs to completion and its value is cached.
  • A get that arrives while the fetch is still running joins it, even if every earlier caller has been cancelled.
  • If the fetch itself ends in cancellation (for example fetch_fn raises CancelledError), its waiting callers get CancelledError, nothing is cached, and the next get starts a new fetch.
  • Any value is cacheable, including None, False, 0 and "".
  • __init__ raises ValueError if ttl_seconds <= 0.

Example

calls = 0

async def fetch(key):
    global calls
    calls += 1
    await asyncio.sleep(0.05)
    return key * 2

cache = AsyncTTLCache(ttl_seconds=1)
await asyncio.gather(*(cache.get(5, fetch) for _ in range(20)))   # [10] * 20
calls                       # 1
await cache.get(5, fetch)   # 10, from cache

Constraints

  • 0 < ttl_seconds <= 3600
  • Keys are hashable. Up to 10^4 distinct keys.
  • Coalesced callers share the first caller's fetch, even if they passed a different fetch_fn.

Solution

Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.
Reveal solution

Approach

Keep two dicts. _values maps a key to (value, expires_at). _in_flight maps a key to the asyncio.Task currently fetching it.

On get, check _values first. Look the entry up and compare the expiry time, never the value's truthiness, so None and 0 are cached like anything else. On a miss, reuse the in-flight task if there is one, otherwise create it. Then await asyncio.shield(task).

The fetch runs in its own task, not in the first caller's coroutine, for a reason. If the first caller ran fetch_fn inline and was cancelled, the fetch would die with it and every coalesced waiter would get a CancelledError it never asked for. As a task, the fetch belongs to the cache. shield makes sure a cancelled caller stops waiting without cancelling that shared task. So the fetch finishes, and its value is cached, even when nobody is left waiting.

The task's wrapper stores the value with expires_at = now + ttl after the fetch returns, which starts the TTL at completion. Its finally removes the in-flight entry on success and failure alike, which is why failures are not cached and the next get retries.

There is no await between checking _in_flight and inserting the new task, so two callers cannot both start a fetch. That is why no lock is needed.

Complexity

O(1) per get plus the fetch itself. Space is O(k) for k cached keys. Expired entries are only removed when read again.

Pitfalls

  • if cached_value: as the hit test. Falsey values look like misses and get fetched every time.
  • Awaiting the task directly instead of through shield. Cancelling one caller cancels the fetch for everyone.
  • Running the fetch inline in the first caller and parking the others on an Event. Same cancellation problem, plus you must forward exceptions by hand.
  • Caching the exception, so one transient failure poisons the key for the whole TTL.
  • Stamping expires_at before the fetch starts. A fetch slower than the TTL produces an entry that is already stale.
  • Holding an asyncio.Lock across the fetch. That serializes unrelated keys.
  • Cleaning up the in-flight entry in except Exception. CancelledError is a BaseException, so a cancelled fetch stays in the map and every later caller gets CancelledError. Use finally.
  • Removing the in-flight entry from the caller's side when that caller is cancelled or times out. The fetch is still running, so the next caller starts a duplicate.

Follow-ups interviewers ask

  • Memory grows without bound. Add an LRU cap with OrderedDict, and sweep expired keys periodically or on insert.
  • Stale-while-revalidate: return the expired value right away and refresh in the background.
  • Cache failures for a short negative TTL so a dead backend is not hammered.
  • If every caller is cancelled and fetches are expensive, should the fetch be cancelled? Track a waiter count and cancel when it drops to zero, if that suits the workload.

Reference solution

import asyncio
import time


class AsyncTTLCache:
    def __init__(self, ttl_seconds: float):
        if ttl_seconds <= 0:
            raise ValueError("ttl_seconds must be positive")
        self.ttl_seconds = ttl_seconds
        self._values: dict = {}  # key -> (value, expires_at)
        self._in_flight: dict[object, asyncio.Task] = {}

    async def _fetch(self, key, fetch_fn):
        try:
            value = await fetch_fn(key)
            self._values[key] = (value, time.monotonic() + self.ttl_seconds)
            return value
        finally:
            del self._in_flight[key]

    async def get(self, key, fetch_fn):
        entry = self._values.get(key)
        if entry is not None:
            value, expires_at = entry
            if time.monotonic() < expires_at:
                return value
            del self._values[key]

        task = self._in_flight.get(key)
        if task is None:
            task = asyncio.create_task(self._fetch(key, fetch_fn))
            self._in_flight[key] = task
        # shield: a cancelled caller stops waiting, but the shared fetch keeps going.
        return await asyncio.shield(task)

Notes

solution.pySaved
import asyncio
import time


class AsyncTTLCache:
    def __init__(self, ttl_seconds: float):
        """Entries expire ttl_seconds after their fetch completes. ValueError if ttl_seconds <= 0."""
        raise NotImplementedError

    async def get(self, key, fetch_fn):
        """Return the cached value, or fetch it once even when many callers miss at the same time."""
        raise NotImplementedError
Python loads on first run

Run checks the 2 example tests. Submit runs all 14 and marks the problem solved when they pass.