Hardening a Coalescing TTL Cache: Failures, Invalidation, Eviction
Data Structure DesignModel answerLast updated
Review a promise-coalescing TTL cache in TypeScript, find its failure, invalidation and memory bugs, write a fixed version, and explain how to port it safely to multithreaded C++20.
Context
A colleague has opened a pull request adding a small in-process cache in front of a slow remote service. The cache should:
- return a stored value while its TTL is still valid,
- let simultaneous callers asking for the same missing key share one fetch (no stampede),
- allow a key to be invalidated manually.
The code under review:
type Stored<V> = { data: V; validUntil: number };
class CoalescingCache<V> {
private values = new Map<string, Stored<V>>();
private running = new Map<string, Promise<V>>();
constructor(private ttlMs: number) {}
async get(key: string, load: (k: string) => Promise<V>): Promise<V> {
const found = this.values.get(key);
if (found && found.validUntil > Date.now()) {
return found.data;
}
const shared = this.running.get(key);
if (shared) {
return shared;
}
const p = load(key).then((data) => {
this.values.set(key, { data, validUntil: Date.now() + this.ttlMs });
this.running.delete(key);
return data;
});
this.running.set(key, p);
return p;
}
invalidate(key: string): void {
this.values.delete(key);
}
}
What to deliver
- Review. Name at least three distinct defects or races. Your analysis must cover:
- what happens when
loadrejects, - what happens when
invalidate(key)runs while a load for that key is still pending, - how memory behaves over time if a large number of different keys are each requested only once.
- what happens when
- Rewrite. Provide a corrected class. Failures must not stay in the cache, and an invalidation must stop an older pending load from writing its result into the store.
- Concurrency model. Contrast this code with a multithreaded C++ version:
- Why does the JavaScript version need no lock around
values.set()? - Which primitives (
std::shared_mutex, double-checked locking, condition variables or futures) would a C++20 port need so that cache hits are never blocked by a slow network fetch?
- Why does the JavaScript version need no lock around
Hints
Hint 1
Draw a timeline of two or three calls and mark every point where control can return to the event loop. Ask what state each map is in when a promise settles, including the rejection path.
Hint 2
The pending-load map is keyed only by a string. When an old load finishes after the key was invalidated and restarted, how does it know it is no longer the load that owns that key? Think about comparing object identity before committing or cleaning up.
Hint 3
For C++, separate three concerns: the fast read path (shared lock), the single-flight coordination (a short critical section that only inserts or looks up a shared future), and the slow fetch (no lock held). Then ask how invalidation is detected after the fetch returns, for example with a generation counter.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer shows
JavaScript has no data races on a single thread, but it still has logical races: other code can run at every await or promise callback. A good review walks each settlement path (fulfilled, rejected, invalidated mid-flight) and checks who owns the bookkeeping maps at that moment. Then it explains what changes once real threads exist.
Defects
- A rejected load poisons the key. The
running.delete(key)call sits only in the success callback. Ifloadrejects, the rejected promise stays inrunningforever. Every latergetreturns that same rejection, so one transient error makes the key unusable until restart. - Invalidation does not affect an in-flight load.
invalidatetouches onlyvalues. If a load started before the invalidation, it will still write its (now stale) result with a fresh TTL. Callers who arrive after the invalidation also join the old promise, because it is still inrunning. The invalidation is effectively ignored. - The obvious patch introduces an ownership bug. If you just add
running.delete(key)toinvalidate, a new load B can start. When old load A finally settles, it deletes B's entry fromrunningand overwrites B's fresher value, since both are keyed by the plain string. Cleanup and commit must verify "am I still the current load for this key?" - Unbounded memory. Expired entries are removed only if the same key is requested again. A workload of many one-off keys grows
valueswithout limit, and there is no size cap. - Minor points.
Date.now()follows the wall clock, which can jump. Use a monotonic clock such asperformance.now().- A synchronous throw from
loadis not caught by.then, so it escapes before anything is registered. This is fine here, but it matters once you reorder the code. - The
asyncwrapper adds a needless extra promise layer on cache hits.
Fixed implementation
Design choices:
- Every load gets its own token object. Only the load whose token is still registered may commit or clean up.
try/finallyguarantees cleanup on success and failure. Errors are never stored.invalidateremoves the stored value and the pending token, orphaning the old load.- A
Mapin insertion order doubles as an LRU, capped bymaxEntries.
type Stored<V> = { data: V; validUntil: number };
type Token<V> = { promise: Promise<V> };
export class CoalescingCache<V> {
private values = new Map<string, Stored<V>>(); // insertion order = recency
private running = new Map<string, Token<V>>();
constructor(
private readonly ttlMs: number,
private readonly maxEntries = 10_000,
private readonly clock: () => number = () => performance.now(),
) {}
get(key: string, load: (k: string) => Promise<V>): Promise<V> {
const hit = this.values.get(key);
if (hit) {
if (hit.validUntil > this.clock()) {
this.values.delete(key); // move to most-recent position
this.values.set(key, hit);
return Promise.resolve(hit.data);
}
this.values.delete(key); // expired: drop now
}
const joined = this.running.get(key);
if (joined) return joined.promise;
const token = { promise: undefined as unknown as Promise<V> };
this.running.set(key, token); // register before calling load
token.promise = this.execute(key, load, token);
return token.promise;
}
private async execute(
key: string,
load: (k: string) => Promise<V>,
token: Token<V>,
): Promise<V> {
try {
const data = await load(key); // a sync throw becomes a rejection
if (this.running.get(key) === token) this.put(key, data);
return data;
} finally {
if (this.running.get(key) === token) this.running.delete(key);
}
}
private put(key: string, data: V): void {
this.values.delete(key);
this.values.set(key, { data, validUntil: this.clock() + this.ttlMs });
while (this.values.size > this.maxEntries) {
const oldest = this.values.keys().next().value as string;
this.values.delete(oldest);
}
}
invalidate(key: string): void {
this.values.delete(key);
this.running.delete(key); // orphan any pending load
}
sweep(): void { // optional, run on a timer
const t = this.clock();
for (const [k, s] of this.values) if (s.validUntil <= t) this.values.delete(k);
}
}
Why it works
- Failure:
finallyalways removes the registered token. Current waiters see the rejection, and the nextgetretries from scratch. - Invalidation: an orphaned load fails the
running.get(key) === tokencheck, so it can neither write tovaluesnor remove a newer load's token. Callers who joined before the invalidation still get the old value, which is acceptable because their request preceded the invalidation. - Synchronous throw: the token is registered before
executeruns, sofinallycleans it up. - Memory:
valuesnever exceedsmaxEntries, andrunningis bounded by the number of distinct concurrent requests.
Complexity: get, put and invalidate are O(1) amortized. sweep is O(n). Space is O(maxEntries + concurrent keys).
Edge cases: ttlMs = 0 means nothing is ever served from the store, but coalescing still works. undefined values are fine because the code tests for the entry object. Note that a load that calls get for the same key synchronously would see an unset token.promise, so forbid re-entrancy or defer the call by a microtask.
Event loop versus threads
Why JavaScript needs no lock. Each synchronous run executes to completion on one thread. The check-then-act sequence running.get then running.set, and values.set, cannot be interrupted. Interleaving happens only at await and promise callbacks, which is where defects 1 to 3 live. Worker threads have separate heaps, so they do not share these maps unless you use SharedArrayBuffer and Atomics.
Porting to C++20. Any two threads can touch the maps at once, so you need explicit design:
- Store: protect it with
std::shared_mutex. Hits take astd::shared_lockand run in parallel. Inserts, expiry removal and invalidation take astd::unique_lock. - Miss path (double-checked locking): check under the shared lock, release it, take the unique lock on the in-flight table, and check again. Another thread may have registered a fetch or filled the store in between. Never upgrade a shared lock in place, because that deadlocks.
- Single flight: the in-flight table holds a
std::shared_future<V>plus a generation number. The first thread inserts astd::promise, releases the lock, then runs the fetch. Followers copy theshared_futureand callget(). The future acts as the condition variable. If you hand-roll it, use a per-key mutex,std::condition_variableand a predicate loop to avoid lost and spurious wakeups. - Never hold a lock during the fetch. Only the short map operations are locked, so hits are never blocked by a slow network call.
- Failure: catch exceptions, call
promise.set_exception, and erase the in-flight record in a scope guard (RAII). - Invalidation: bump a per-key generation (or replace the in-flight record). After the fetch, take the unique lock and commit only if the generation still matches. This is the same identity check as in the TypeScript version.
- LRU: a read mutates recency, so a shared lock is not enough. Use sharded caches (hash key to one of N shards, each with its own mutex), or an approximate policy such as CLOCK or sampled eviction, to keep reads cheap.
- Clock: use
std::chrono::steady_clock.
Common mistakes
- Cleaning up only on success.
- Clearing the in-flight map in
invalidatewithout an identity check on settle. - Holding the write lock during the fetch.
- Upgrading a
shared_lockto a unique lock in place. - Caching errors, or relying on TTL alone to bound memory.