Thread-Safe TTL Cache with Single-Flight Loading

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

An in-memory cache with per-entry expiration already exposes get(key), put(key, value, ttl), and delete(key). You are extending it with fetch(key, loader, ttl) (optionally accepting a per-caller wait timeout): when key holds an unexpired entry, return that value right away; when key is missing or expired, run loader(), store the computed result with ttl only if loader() succeeds, and return it to the caller. Failures raised by loader() must never be written into the cache.

Walk through how you would engineer this cache so heavy multithreaded traffic on hot keys stays both thread-safe and high-throughput.

Operating environment and assumptions: - Computing a miss via loader() performs slow external I/O (roughly 100 ms or more) and can raise an exception or exceed a caller's deadline. - Cache hits and misses on unrelated keys must run in parallel without blocking behind another key's slow loader() call. - Concurrent threads may invoke put(key, ...) or delete(key) while a fetch load for that exact key is still executing. - Cached objects are treated as read-only once stored. - State any design assumptions you make upfront (single-process vs. multi-node scope, whether concurrent callers waiting on the same miss share the returned value and error, how mid-flight put/delete calls interact with an active load, and how caller timeouts or stale-on-error policies behave).

Scope & Expectations

  • Core state synchronization & linearizability: Explain how the entry map, expiration timestamps, and any optional eviction or cleanup structures stay mutually consistent under short lock scopes, and identify the exact linearization point of get, put, delete, and fetch.
  • Single-flight request coalescing: Show how concurrent misses on the same key collapse into one loader() execution without stalling cache hits or misses on distinct keys.
  • Write/delete race safety: Prevent an older in-flight loader() completion from overwriting a newer put value or reviving a deleted key.
  • Failure, timeout, and lifecycle cleanup: Specify what happens when loader() raises an exception or a waiting caller times out so failed loads are never cached and waiting threads never hang permanently.

Step-by-step walkthrough

  1. Clarify the concurrency contract up front

    Most concurrency bugs start as ambiguous specifications. Before designing locks, ask the clarifying questions from the prompt and state explicit, consistent rules:

    • Shared result and shared error. Concurrent callers that miss on the same key while a load is running join that single load and receive the same return value—or the same failure wrapped in a LoadError. Errors are never cached, so a subsequent fetch after that flight finishes starts a fresh load.
    • put and delete invalidate older in-flight loads. If thread C calls put(K, new_val, ttl) or delete(K) while an earlier load for K is still running, that older load must not write its stale result into the cache when it finishes. Callers already waiting on that earlier load still receive its value because their fetch calls overlapped the put/delete in real time.
    • Per-caller wait timeouts without killing the load. A caller whose timeout expires raises TimeoutError and stops waiting, while the underlying load continues so the cache still warms for future callers. (Python threads cannot be forcibly killed safely; cancellation is cooperative at best.)
    • No stale-on-error by default. Once an entry expires (clock() >= expires_at), it is treated as absent; if the reload fails, callers see the error rather than expired data.
    • Single-process, monotonic clock, read-only objects. Expirations use time.monotonic() so wall-clock jumps never corrupt TTL math, and stored objects are never mutated in place after insertion.
  2. See why the two obvious designs fail

    Suppose a hot key K receives 1,000 requests per second, its TTL just expired, and loader() takes 100 ms (0.1 s):

    1. Thread-safe dictionary alone (miss storm). Individual dict reads and writes are atomic, but if get(K) is MISS: val = loader(); put(K, val) is a check-then-act race across two separate steps. During the 100 ms window before the first loader finishes, 1,000 req/s * 0.1 s = 100 threads all observe a miss and fire 100 duplicate calls at your backend—a cache stampede (or miss storm, where many threads simultaneously recompute the same expired key).
    2. Global lock held across loader() (head-of-line blocking). Wrapping the entire fetch in one Lock stops duplicate loads for K, but freezes the entire cache for 100 ms. Ten threads requesting 10 different missing keys take 10 * 100 ms = 1,000 ms sequentially instead of 100 ms in parallel, and even fast cache hits stall behind slow network I/O.
    Bad 1 (no flight coordination):   100 threads miss K ──► 100 slow loader() calls hit DB!
    Bad 2 (global lock over loader):  Key A [===100ms===] -> Key B [===100ms===] (serialized!)
    Goal  (short lock + per-key flight):
      Key K (100 threads): 1 leader runs loader() outside lock; 99 waiters sleep on K's Event
      Key B (1 thread):    runs its own loader() in parallel with Key K!
    
  3. Guard coordinated state with short critical sections

    A TTL cache has multiple data structures whose invariants span across them: - _entries: key -> _Entry(value, expires_at) - _flights: key -> _Flight (the active in-progress load allowed to publish for key) - Optional recency/cleanup structures (an LRU doubly linked list or an expiration min-heap)

    Putting an independent lock on each structure is not enough, because transitions like "write a new value for K AND prevent an older in-flight load for K from overwriting it" must happen as one indivisible step.

    Instead, we protect all metadata with one mutex (self._lock) and keep every critical section (the tiny block of code executed while holding the lock) strictly O(1) in-memory dictionary work—never performing I/O, sleeping, or calling loader() inside with self._lock:.

    Reading the clock and checking clock() >= entry.expires_at also happens inside that critical section. That gives every basic operation a crystal-clear linearization point (the single instant at which an operation appears to take effect atomically relative to all other threads): - get(key): the instant inside with self._lock: when _live_value reads the entry and checks self._clock() >= entry.expires_at. - put(key, value, ttl): the instant inside with self._lock: when it writes _entries[key] and detaches any older _flights[key]. - delete(key): the instant inside with self._lock: when it removes _entries[key] and detaches any older _flights[key].

    import threading
    import time
    from typing import Any, Callable, Dict
    
    # Sentinel object distinguishing "cache miss" from a legitimately cached None value
    _MISS = object()
    
    
    class _Entry:
        def __init__(self, value: Any, expires_at: float) -> None:
            self.value = value
            self.expires_at = expires_at
    
    
    class TTLCache:
        def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
            self._lock = threading.Lock()
            self._entries: Dict[Any, _Entry] = {}
            self._flights: Dict[Any, "_Flight"] = {}
            self._clock = clock
    
        def _live_value(self, key: Any) -> Any:
            """Caller must hold self._lock. Return live value or _MISS, lazily dropping expired entries."""
            entry = self._entries.get(key)
            if entry is None:
                return _MISS
            if self._clock() >= entry.expires_at:
                del self._entries[key]
                return _MISS
            return entry.value
    
        def get(self, key: Any) -> Any:
            with self._lock:
                return self._live_value(key)
    
        def put(self, key: Any, value: Any, ttl: float) -> None:
            if ttl <= 0:
                raise ValueError("ttl must be positive")
            with self._lock:
                self._entries[key] = _Entry(value, self._clock() + ttl)
                # Detach any older in-flight load so it cannot overwrite this newer value
                self._flights.pop(key, None)
    
        def delete(self, key: Any) -> None:
            with self._lock:
                self._entries.pop(key, None)
                # Detach any older in-flight load so it cannot resurrect a deleted key
                self._flights.pop(key, None)
    
  4. Coalesce concurrent misses with a per-key Flight

    A _Flight object represents one specific load attempt for one key. It holds a threading.Event (done) plus fields for ok, value, and error.

    When fetch(key, loader, ttl, timeout) runs, it acquires self._lock briefly to decide one of three paths: 1. Cache hit: _live_value(key) finds an unexpired value and returns immediately. 2. Joiner: _flights already has an active _Flight for key; grab a local reference to that flight (is_leader = False). 3. Leader: no flight exists for key; create a new _Flight(), store it in self._flights[key], and mark is_leader = True.

    Then fetch releases self._lock. Only the leader runs loader(), completely outside the lock, while all joiners block on flight.done.wait(timeout). Because _flights only holds entries for keys actively loading right now and deletes them as soon as loading finishes, memory stays bounded by the number of concurrent distinct misses rather than total historical keys.

    import threading
    from typing import Any, Callable, Optional
    
    
    class LoadError(Exception):
        """Raised to callers sharing a failed load; __cause__ holds the original loader exception."""
    
    
    class _Flight:
        """Represents one in-progress load generation for a single key."""
    
        def __init__(self) -> None:
            self.done = threading.Event()
            self.ok = False
            self.value: Any = None
            self.error: Optional[BaseException] = None
    
  5. Publish with generation awareness and trace a delete race

    What happens when the leader finishes loader() at t = 100 ms, if another thread called delete(K) or put(K, ...) at t = 50 ms?

    Inside a finally block (so even unexpected exceptions like KeyboardInterrupt never leave waiters hanging forever!), the leader re-acquires self._lock and checks object identity:

    if self._flights.get(key) is flight:

    Using the flight instance itself as the generation token solves two subtle concurrency problems at once: 1. Stale publication prevention. Because put and delete popped flight out of self._flights, self._flights.get(key) is flight evaluates to False! So the outdated load does not write its stale value into _entries, and does not touch any newer flight F2 that started after the delete. 2. ABA immunity. If you instead used an integer counter stored inside _entries[key] that got deleted and recreated back at 0, an old load could falsely match the new 0 (the ABA problem — mistaking a recreated state with the same number for the original state). A live Python _Flight object has a unique identity for its entire lifetime.

    Notice the exact order at the end of _load: we update _entries and remove _flights[key] under self._lock first, and call flight.done.set() afterward. That establishes a strict happens-before edge (a memory-visibility guarantee that writes before set() are visible to every thread waking from wait()), and ensures any woken caller that immediately calls cache.get(key) sees the published value.

    Let's trace four threads racing on key K (100 ms loader):

    Time   Thread / Event               _entries[K]   _flights[K]   Notes
    -----  ---------------------------  ------------  ------------  ---------------------------------------
    t=0    A: fetch(K) misses           absent        F1            A is leader of F1; runs loader() -> v1
    t=20   B: fetch(K) misses           absent        F1            B joins F1; waits on F1.done
    t=50   C: delete(K)                 absent        absent        Pops F1! (F1 still runs for A & B)
    t=60   D: fetch(K) misses           absent        F2            No active flight -> D leads F2 -> v2
    t=100  F1 finishes with v1          absent        F2            _flights[K] is F2 (!= F1): NOT cached!
                                                                    F1.done.set() -> A and B both return v1
    t=160  F2 finishes with v2          (v2, exp)     absent        _flights[K] is F2: v2 cached!
                                                                    F2.done.set() -> D returns v2
    

    What is the linearization point of fetch on a miss? - If flight publishes into _entries, all callers of flight linearize at that publication critical section. - If flight was detached by a concurrent put or delete, its callers linearize immediately before that put or delete (equivalent to "loaded v1, cached it briefly, and then C deleted/replaced it"). - A failed or timed-out fetch leaves cache state unchanged and linearizes inside its execution interval.

  6. Handle errors, caller timeouts, and recency/cleanup extensions

    • Loader failures: _load records flight.error = exc, skips caching, deletes _flights[key], and calls flight.done.set(). Every caller waiting on flight raises a fresh LoadError(...) from flight.error (raising a new wrapper per thread avoids mutating a single shared exception's __traceback__ from multiple threads simultaneously).
    • Caller vs. leader timeouts: In the inline-leader version, joiners pass timeout to flight.done.wait(timeout). Because the leader executes loader() on its own thread, bounding the leader's wait by timeout as well simply means submitting _load to a bounded ThreadPoolExecutor so the leader waits on flight.done.wait(timeout) identically to joiners. If a hung loader never returns, storing flight.started_at lets a later fetch replace a flight older than max_load_duration so a wedged backend call cannot block refreshes forever.
    • Coordinating LRU and background expiry: Keep an OrderedDict (for LRU) or a (expires_at, seq, key) min-heap under the same self._lock. When a background cleanup thread wakes up, it acquires self._lock, pops a small batch (e.g., 64 expired heap items), verifies entry.expires_at still matches (skipping stale heap entries from overwritten keys), and releases the lock so foreground traffic never stalls. If single-lock contention ever becomes a bottleneck at hundreds of thousands of QPS, shard the entire TTLCache into 64 independent stripes indexed by hash(key) % 64.
  7. Complete reference implementation

    Putting all pieces together gives a compact, runnable TTLCache:

    import threading
    import time
    from typing import Any, Callable, Dict, Optional
    
    _MISS = object()
    
    
    class LoadError(Exception):
        """Raised to callers sharing a failed load; __cause__ holds the original loader exception."""
    
    
    class _Entry:
        def __init__(self, value: Any, expires_at: float) -> None:
            self.value = value
            self.expires_at = expires_at
    
    
    class _Flight:
        """Represents one in-progress load generation for a single key."""
    
        def __init__(self) -> None:
            self.done = threading.Event()
            self.ok = False
            self.value: Any = None
            self.error: Optional[BaseException] = None
    
    
    class TTLCache:
        def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
            # Single short-held mutex coordinating _entries and _flights atomically
            self._lock = threading.Lock()
            self._entries: Dict[Any, _Entry] = {}
            self._flights: Dict[Any, _Flight] = {}
            self._clock = clock
    
        def _live_value(self, key: Any) -> Any:
            """Caller must hold self._lock. Return live value or _MISS, lazily dropping expired entries."""
            entry = self._entries.get(key)
            if entry is None:
                return _MISS
            if self._clock() >= entry.expires_at:
                del self._entries[key]
                return _MISS
            return entry.value
    
        def get(self, key: Any) -> Any:
            with self._lock:
                return self._live_value(key)
    
        def put(self, key: Any, value: Any, ttl: float) -> None:
            if ttl <= 0:
                raise ValueError("ttl must be positive")
            with self._lock:
                self._entries[key] = _Entry(value, self._clock() + ttl)
                # Invalidate any older in-flight load so it cannot overwrite this value
                self._flights.pop(key, None)
    
        def delete(self, key: Any) -> None:
            with self._lock:
                self._entries.pop(key, None)
                # Invalidate any older in-flight load so it cannot resurrect this key
                self._flights.pop(key, None)
    
        def fetch(self, key: Any, loader: Callable[[], Any], ttl: float,
                  timeout: Optional[float] = None) -> Any:
            if ttl <= 0:
                raise ValueError("ttl must be positive")
            with self._lock:
                cached = self._live_value(key)
                if cached is not _MISS:
                    return cached
                flight = self._flights.get(key)
                is_leader = flight is None
                if is_leader:
                    flight = _Flight()
                    self._flights[key] = flight
    
            # Run slow I/O outside self._lock so hits and other keys proceed in parallel
            if is_leader:
                self._load(key, flight, loader, ttl)
    
            if not flight.done.wait(timeout):
                raise TimeoutError(f"fetch({key!r}) timed out after {timeout}s; load continues")
            if not flight.ok:
                raise LoadError(f"loading {key!r} failed") from flight.error
            return flight.value
    
        def _load(self, key: Any, flight: _Flight, loader: Callable[[], Any], ttl: float) -> None:
            try:
                flight.value = loader()
                flight.ok = True
            except BaseException as exc:
                flight.error = exc
                if not isinstance(exc, Exception):
                    raise
            finally:
                # Always unregister and signal waiters, even on Exception or KeyboardInterrupt
                with self._lock:
                    if self._flights.get(key) is flight:
                        del self._flights[key]
                        if flight.ok:
                            self._entries[key] = _Entry(flight.value, self._clock() + ttl)
                flight.done.set()
    

Intuition & how it works

Imagine an office reference board where answers have expiration timestamps. When someone sees an answer is missing or expired, they clip a numbered "Fetching now" ticket under that topic on the board, step outside the boardroom to make the slow 100 ms phone call, and later post the result only if their ticket is still clipped there. Anyone else who wants the same topic sees the ticket and waits quietly beside it instead of making 99 duplicate phone calls, while colleagues looking up different topics walk in and out of the boardroom in microseconds without waiting at all.

Why do the two obvious approaches fail? A thread-safe dictionary alone protects individual reads and writes, but if miss -> load -> put spans multiple steps: if a popular key gets 1,000 requests/second and expires while loader() takes 100 ms, roughly 1,000 * 0.1 = 100 threads all see a miss before the first load finishes, hammering the database with a cache stampede (a burst of duplicate recomputations for the same expired key). Conversely, holding one global lock while calling loader() stops the stampede but blocks cache hits and unrelated keys for the entire 100 ms network call.

Walk through a concrete 4-thread race on key "K" with a 100 ms loader: 1. At t = 0 ms, Thread A misses on "K", registers flight object F1 under _lock, releases _lock, and starts calling loader(). 2. At t = 20 ms, Thread B misses on "K", sees F1 in _flights["K"] (single-flight coalescing — merging concurrent requests for the same key into one shared execution), releases _lock, and waits on F1.done. 3. At t = 50 ms, Thread C calls delete("K"), which removes "K" from _entries and pops F1 out of _flights in one atomic step. At t = 60 ms, Thread D calls fetch("K"), sees no registered flight, and starts a new flight F2. 4. At t = 100 ms, F1 finishes with v1: under _lock, F1 sees _flights.get("K") is F2 (not F1), so it skips writing stale v1 to _entries, wakes A and B with v1, and at t = 160 ms, F2 finishes and cleanly publishes v2 for D and future callers.

Key points

  • Single short-held lock for metadata invariants. Guard _entries, _flights, and any LRU or expiry-heap structures under one mutex (self._lock) so cross-structure updates (like put/delete detaching an active flight) execute atomically. Keep every critical section (code executed while holding the lock) to O(1) in-memory pointer/dict operations and never run loader() under the lock.
  • Per-key flight coalescing. _flights[key] stores a _Flight containing a threading.Event and outcome slots (ok, value, error). The first missing thread becomes the leader; concurrent callers for the same key wait on flight.done.wait(timeout), while callers for other keys proceed in parallel.
  • Generation-aware publication via object identity. A completing leader writes to _entries only if self._flights.get(key) is flight. Because put and delete pop _flights[key], an older in-flight load cannot overwrite a newer put or resurrect a deleted key, and using the _Flight object identity avoids the ABA problem (where a reset integer counter accidentally matches an old generation).
  • Unconditional cleanup in finally. Unregistering the flight and calling flight.done.set() inside finally guarantees that loader exceptions, CancelledError, or KeyboardInterrupt never strand waiting threads or wedge the key permanently, and done.set() after lock release establishes a strict happens-before memory-visibility guarantee for flight.value and flight.error.
  • Clear linearization points. A linearization point is the exact instant inside an operation's call-to-return window when it appears to take effect atomically: get, put, delete, and fetch hits linearize inside their single critical section; a fetch miss that publishes linearizes at publication, and a fetch miss detached by put/delete linearizes immediately before that put/delete.

Common mistakes

  • Holding self._lock (or a lock acquired inside it) across loader(): stalls unrelated keys and cache hits behind slow I/O, and deadlocks immediately if loader() calls back into the cache on a non-reentrant Lock.
  • Publishing unconditionally after loader() returns: without checking self._flights.get(key) is flight, a delete(K) or put(K, v_new) during a 100 ms load gets silently overwritten by stale data when the slow load finishes.
  • Forgetting finally cleanup when loader() raises: leaves flight stuck in _flights[key] with done unset, causing every current and future fetch(key) to hang or time out forever.
  • Using None to mean "cache miss": breaks callers that legitimately return and cache None from loader(); always use a dedicated private sentinel _MISS = object().
  • Measuring TTLs with time.time() instead of a monotonic clock: a monotonic clock (time.monotonic()) only moves forward at a steady rate, whereas NTP adjustments or leap seconds can jump wall-clock time.time() backward or forward and corrupt expirations.
  • Re-raising the exact same exception instance across 50 waiter threads: mutates the exception's shared __traceback__ concurrently; instead, raise a fresh wrapper raise LoadError(...) from flight.error in each waiter.
  • Recursive same-key fetch inside loader(): if loader() for key K calls cache.fetch(K, ...), the leader joins its own flight and waits for itself forever unless bounded by a timeout.

Follow-up questions

  • How can you coalesce duplicate misses across an entire cluster of application servers rather than within a single process? In-process single-flight already cuts 10,000 concurrent misses across 50 app servers down to at most 50 backend loads (one per process). To collapse those 50 down to 1, either route requests for key K to a designated owner node via consistent hashing (mapping keys onto a server ring so one cache node owns and coalesces K), or coordinate through a shared cache like Redis using a short-lived lease (SET lock:K token NX PX 2000) while peers briefly poll or serve slightly expired data using stale-while-revalidate (returning the last cached value immediately while a single background worker refreshes it).
  • When a loader fails, when does negative caching help and why is it risky for temporary infrastructure errors? Distinguish missing-data responses (such as HTTP 404 or an empty database lookup, where caching a "not found" sentinel for a few minutes avoids repeated queries for nonexistent keys) from transient infrastructure failures (socket timeouts, HTTP 503). Caching transient errors for a full TTL turns a brief network hiccup into a prolonged outage; at most, protect an overloaded backend with a tiny negative TTL of 0.5–2 seconds (with jitter) or a circuit breaker, and prefer serving stale cached data when product semantics permit.
  • How do you keep synchronization memory bounded even if billions of distinct keys pass through the cache over time? Never keep permanent per-key Lock objects: insert _Flight entries into _flights only while a load is actively running and remove them inside finally, bounding map size by concurrent active misses rather than total historical keys. Whenever an architecture requires per-key mutexes, use lock striping (a fixed array of M locks—such as 256 or 1,024—indexed by hash(key) % M) so lock memory stays O(M) regardless of key cardinality.
  • How must the cache contract or implementation change if callers can mutate returned objects in place? Returning one shared dict or list reference to the leader, joiners, and subsequent get hits lets a single caller's in-place mutation corrupt cached state and cause data races in peer threads. Enforce isolation by converting loaded results into immutable types (tuple, frozenset, frozen dataclass), cloning via copy.deepcopy(value) on put and on every read (get/fetch), or storing serialized bytes and deserializing a fresh object per caller.

Follow-up questions

Similar questions

More Tubi interview questions

All 11 Tubi questions →