KatInterview

Hardening a Coalescing TTL Cache: Failures, Invalidation, Eviction

Data Structure DesignModel answer
HardModel answerData Structure Designasynccacherace-conditions

Last 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

  1. Review. Name at least three distinct defects or races. Your analysis must cover:
    • what happens when load rejects,
    • 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.
  2. 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.
  3. 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?

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.