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, andfetch. - 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 newerputvalue or reviving adeleted 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
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 subsequentfetchafter that flight finishes starts a fresh load. putanddeleteinvalidate older in-flight loads. If thread C callsput(K, new_val, ttl)ordelete(K)while an earlier load forKis 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 theirfetchcalls overlapped theput/deletein real time.- Per-caller wait timeouts without killing the load. A caller whose
timeoutexpires raisesTimeoutErrorand 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.
- 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
See why the two obvious designs fail
Suppose a hot key
Kreceives1,000requests per second, its TTL just expired, andloader()takes100 ms(0.1 s):- Thread-safe dictionary alone (miss storm). Individual
dictreads and writes are atomic, butif get(K) is MISS: val = loader(); put(K, val)is a check-then-act race across two separate steps. During the100 mswindow before the first loader finishes,1,000 req/s * 0.1 s = 100threads 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). - Global lock held across
loader()(head-of-line blocking). Wrapping the entirefetchin oneLockstops duplicate loads forK, but freezes the entire cache for100 ms. Ten threads requesting 10 different missing keys take10 * 100 ms = 1,000 mssequentially instead of100 msin 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!- Thread-safe dictionary alone (miss storm). Individual
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 forkey) - 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
KAND prevent an older in-flight load forKfrom 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) strictlyO(1)in-memory dictionary work—never performing I/O, sleeping, or callingloader()insidewith self._lock:.Reading the clock and checking
clock() >= entry.expires_atalso 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 insidewith self._lock:when_live_valuereads the entry and checksself._clock() >= entry.expires_at. -put(key, value, ttl): the instant insidewith self._lock:when it writes_entries[key]and detaches any older_flights[key]. -delete(key): the instant insidewith 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)Coalesce concurrent misses with a per-key Flight
A
_Flightobject represents one specific load attempt for one key. It holds athreading.Event(done) plus fields forok,value, anderror.When
fetch(key, loader, ttl, timeout)runs, it acquiresself._lockbriefly to decide one of three paths: 1. Cache hit:_live_value(key)finds an unexpired value and returns immediately. 2. Joiner:_flightsalready has an active_Flightforkey; grab a local reference to thatflight(is_leader = False). 3. Leader: no flight exists forkey; create a new_Flight(), store it inself._flights[key], and markis_leader = True.Then
fetchreleasesself._lock. Only the leader runsloader(), completely outside the lock, while all joiners block onflight.done.wait(timeout). Because_flightsonly 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] = NonePublish with generation awareness and trace a delete race
What happens when the leader finishes
loader()att = 100 ms, if another thread calleddelete(K)orput(K, ...)att = 50 ms?Inside a
finallyblock (so even unexpected exceptions likeKeyboardInterruptnever leave waiters hanging forever!), the leader re-acquiresself._lockand checks object identity:if self._flights.get(key) is flight:Using the
flightinstance itself as the generation token solves two subtle concurrency problems at once: 1. Stale publication prevention. Becauseputanddeletepoppedflightout ofself._flights,self._flights.get(key) is flightevaluates toFalse! So the outdated load does not write its stale value into_entries, and does not touch any newer flightF2that started after the delete. 2. ABA immunity. If you instead used an integer counter stored inside_entries[key]that got deleted and recreated back at0, an old load could falsely match the new0(the ABA problem — mistaking a recreated state with the same number for the original state). A live Python_Flightobject has a unique identity for its entire lifetime.Notice the exact order at the end of
_load: we update_entriesand remove_flights[key]underself._lockfirst, and callflight.done.set()afterward. That establishes a strict happens-before edge (a memory-visibility guarantee that writes beforeset()are visible to every thread waking fromwait()), and ensures any woken caller that immediately callscache.get(key)sees the published value.Let's trace four threads racing on key
K(100 msloader):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 v2What is the linearization point of
fetchon a miss? - Ifflightpublishes into_entries, all callers offlightlinearize at that publication critical section. - Ifflightwas detached by a concurrentputordelete, its callers linearize immediately before thatputordelete(equivalent to "loadedv1, cached it briefly, and then C deleted/replaced it"). - A failed or timed-outfetchleaves cache state unchanged and linearizes inside its execution interval.Handle errors, caller timeouts, and recency/cleanup extensions
- Loader failures:
_loadrecordsflight.error = exc, skips caching, deletes_flights[key], and callsflight.done.set(). Every caller waiting onflightraises a freshLoadError(...) 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
timeouttoflight.done.wait(timeout). Because the leader executesloader()on its own thread, bounding the leader's wait bytimeoutas well simply means submitting_loadto a boundedThreadPoolExecutorso the leader waits onflight.done.wait(timeout)identically to joiners. If a hung loader never returns, storingflight.started_atlets a laterfetchreplace a flight older thanmax_load_durationso 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 sameself._lock. When a background cleanup thread wakes up, it acquiresself._lock, pops a small batch (e.g., 64 expired heap items), verifiesentry.expires_atstill 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 entireTTLCacheinto64independent stripes indexed byhash(key) % 64.
- Loader failures:
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 (likeput/deletedetaching an active flight) execute atomically. Keep every critical section (code executed while holding the lock) toO(1)in-memory pointer/dict operations and never runloader()under the lock. - Per-key flight coalescing.
_flights[key]stores a_Flightcontaining athreading.Eventand outcome slots (ok,value,error). The first missing thread becomes the leader; concurrent callers for the same key wait onflight.done.wait(timeout), while callers for other keys proceed in parallel. - Generation-aware publication via object identity. A completing leader writes to
_entriesonly ifself._flights.get(key) is flight. Becauseputanddeletepop_flights[key], an older in-flight load cannot overwrite a newerputor resurrect a deleted key, and using the_Flightobject identity avoids the ABA problem (where a reset integer counter accidentally matches an old generation). - Unconditional cleanup in
finally. Unregistering the flight and callingflight.done.set()insidefinallyguarantees that loader exceptions,CancelledError, orKeyboardInterruptnever strand waiting threads or wedge the key permanently, anddone.set()after lock release establishes a strict happens-before memory-visibility guarantee forflight.valueandflight.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, andfetchhits linearize inside their single critical section; afetchmiss that publishes linearizes at publication, and afetchmiss detached byput/deletelinearizes immediately before thatput/delete.
Common mistakes
- Holding
self._lock(or a lock acquired inside it) acrossloader(): stalls unrelated keys and cache hits behind slow I/O, and deadlocks immediately ifloader()calls back into the cache on a non-reentrantLock. - Publishing unconditionally after
loader()returns: without checkingself._flights.get(key) is flight, adelete(K)orput(K, v_new)during a 100 ms load gets silently overwritten by stale data when the slow load finishes. - Forgetting
finallycleanup whenloader()raises: leavesflightstuck in_flights[key]withdoneunset, causing every current and futurefetch(key)to hang or time out forever. - Using
Noneto mean "cache miss": breaks callers that legitimately return and cacheNonefromloader(); 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-clocktime.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 wrapperraise LoadError(...) from flight.errorin each waiter. - Recursive same-key
fetchinsideloader(): ifloader()for keyKcallscache.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
Kto a designated owner node via consistent hashing (mapping keys onto a server ring so one cache node owns and coalescesK), 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
404or 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, HTTP503). 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
Lockobjects: insert_Flightentries into_flightsonly while a load is actively running and remove them insidefinally, 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 ofMlocks—such as 256 or 1,024—indexed byhash(key) % M) so lock memory staysO(M)regardless of key cardinality. - How must the cache contract or implementation change if callers can mutate returned objects in place? Returning one shared
dictorlistreference to the leader, joiners, and subsequentgethits 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, frozendataclass), cloning viacopy.deepcopy(value)onputand on every read (get/fetch), or storing serialized bytes and deserializing a fresh object per caller.
Follow-up questions
- How can you coalesce duplicate misses across an entire cluster of application servers rather than within a single process?
- When a loader fails, when does negative caching help and why is it risky for temporary infrastructure errors?
- How do you keep synchronization memory bounded even if billions of distinct keys pass through the cache over time?
- How must the cache contract or implementation change if callers can mutate returned objects in place?
Similar questions
- Daily User Growth and Churn Rollup
- Statistical Sample Size and Power Drivers
- Simulate a Read-Through TTL Cache
- ML Foundations, Production Tuning, and Recommender Systems
- Multi-Metric Experiment Design and Launch Trade-Off Communication
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models
More Tubi interview questions
- Simulate a Read-Through TTL Cache Medium
- Daily User Growth and Churn Rollup Medium
- Statistical Sample Size and Power Drivers Hard Pro
- ML Foundations, Production Tuning, and Recommender Systems Medium Pro
- Multi-Metric Experiment Design and Launch Trade-Off Communication Hard Pro
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models Medium Pro
- Streaming Movie Recommendation Pipeline and Model (AI-Assisted) Medium Pro
- Designing Artwork Selection for a Video Streaming Library Medium Pro
- Core ML Screen: Decision Trees, Optimization, Metrics, and Attention Medium Pro
- Proportional Random Index Sampler Medium Pro