KatInterview

Designing a Validated In-Memory Cache for Repeated Parsing

Data Structure DesignModel answer
MediumModel answerData Structure Designcachinghash-maplru

Last updated

Speed up a script that repeatedly parses files by adding a thread-safe, bounded, in-memory cache, and justify its keys, eviction, staleness checks and complexity.

You have a script you wrote earlier that, for each input path, locates a file and parses it into a computed result (for example, reading a license file and extracting structured data). Profiling shows the same files are processed over and over, and the script is now slow.

Propose and analyze a dictionary-backed, in-memory cache that speeds up repeated lookups. Your answer should cover:

  1. Placement. Which call in the script is worth caching, why it qualifies, and which calls should be left alone.
  2. Keys and values. What identifies a computation, what you store, and what normalization ensures that logically equal inputs share one entry.
  3. Hit rate. An estimate of the expected hit rate and the assumptions behind it (number of distinct inputs versus number of lookups, locality of access).
  4. Eviction. Which policy you pick (none, LRU, LFU, TTL) and how the working-set size and memory budget justify it.
  5. Staleness. How you keep entries correct when the underlying file changes, and which consistency-versus-cost trade-off you accept.
  6. Concurrency. What can go wrong with multiple threads or processes (races, many callers missing the same key at once) and how you prevent it.
  7. Code. get/put pseudocode or real code that includes the validity check performed on every read.
  8. Complexity. Time and space cost of the operation before and after adding the cache.

Hints

Hint 1

Only pure, deterministic, expensive work whose inputs repeat is worth caching. Side effects, time-dependent calls and trivially cheap operations are not.

Hint 2

A cheap fingerprint of the source (modification time in nanoseconds, size, inode) can be compared on every read, and costs far less than re-reading and re-parsing the file.

Hint 3

When many threads miss the same key together, let one compute while the rest wait on a per-key lock and then re-check the cache. Never hold the global lock during disk I/O.

Hint 4

With N lookups over U distinct keys and unlimited capacity, only first accesses miss, so the hit rate is roughly 1 - U/N.