KatInterview

Warm-Restart Persistence for an In-Memory LRU Cache

System DesignModel answer
HardModel answerSystem Designlru-cachewrite-ahead-logsnapshots

Last updated

Design how a single-node LRU cache saves its entries and recency order so it restarts warm after a crash, balancing write-path latency, durability, and bounded recovery time.

Your service runs a single-process, in-memory LRU cache with a fixed capacity of about 1,000,000 entries. It is built from a hash map plus a doubly linked list, and get(key) and put(key, value) both run in O(1). Right now the cache is purely volatile. After a crash or restart it comes back empty, and every request is a cold miss until it refills.

Your task is to design a persistence scheme so that after a crash or restart the cache comes back mostly populated, with a usable recency order, instead of empty.

Sizing assumptions (illustrative)

  • Average value of roughly 1 KB, average key of roughly 32 bytes.
  • Up to about 50,000 put operations per second; get traffic is considerably higher.
  • Hot-path get and put must remain O(1) and take microseconds, so persistence must add very little steady-state latency.
  • Recovery time must be bounded. "Replay the entire history" is not acceptable.
  • Assume a source of truth sits behind the cache unless you argue otherwise, and state that assumption explicitly because it determines the durability target.

Your answer should cover

  1. Which data has to be persisted in order to rebuild the cache.
  2. How both the key-value entries and the LRU ordering are reconstructed on startup.
  3. Whether you would use snapshots, a write-ahead log (WAL), or both, and why.
  4. The durability-versus-latency trade-off on the write path.
  5. The recovery procedure after a crash, including partially written (torn) records.
  6. A brief note on how this would extend to a distributed cache.

Also list the clarifying questions you would ask first, and say how each answer would change your design.

Hints

Hint 1

Start by asking what the cache sits in front of. If the data can always be reloaded from a source of truth, a lost entry is only a miss, so warm-start is a best-effort optimization rather than database-grade durability.

Hint 2

Do not persist linked-list pointers. Persist keys, values, and a recency order expressed as a sequence from most to least recently used, and rebuild the pointers on load. Also think about whether logging every get is worth its cost.

Hint 3

Combine a periodic snapshot with a WAL of mutations written since that snapshot. Make each log record self-checking (length plus CRC) so a torn tail can be detected and dropped, and make snapshot replacement atomic using write-to-temp, fsync, rename, then fsync of the directory.