Warm-Restart Persistence for an In-Memory LRU Cache
System DesignModel answerLast 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
putoperations per second;gettraffic is considerably higher. - Hot-path
getandputmust 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
- Which data has to be persisted in order to rebuild the cache.
- How both the key-value entries and the LRU ordering are reconstructed on startup.
- Whether you would use snapshots, a write-ahead log (WAL), or both, and why.
- The durability-versus-latency trade-off on the write path.
- The recovery procedure after a crash, including partially written (torn) records.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions and framing
I would first state that the cache fronts a source of truth (a database or a service). A lost entry then costs only a miss, so the goal is warm restart, not strict durability. Durability becomes a configuration knob. If the interviewer says the cache holds the only copy of the data, the design moves toward database-style durability: synchronous log flushes and no approximate recency.
Questions I would ask, and how the answers change the design:
- Cost of a miss. If recomputation is cheap, persistence is not worth the complexity. If it involves a cross-region call or model inference, a warm restart is very valuable.
- How exact must eviction order be? This is the biggest cost lever (see below).
- Failure model. A process crash leaves the OS page cache intact, so
write()alone survives it. Power loss or a kernel panic requiresfsync. - TTLs. If entries expire, store absolute expiry timestamps so time spent down is counted correctly.
What must be persisted
- Key-to-value entries.
- Recency as a sequence of keys from MRU to LRU. Never persist pointers; they are rebuilt on load.
- Metadata: format version, capacity, the snapshot ID and the WAL position it corresponds to, and absolute expiry times if TTLs exist.
Sizing: 10^6 entries x ~1 KB is about 1 GB of data. A full snapshot is therefore on the order of 1 GB, taking several seconds to tens of seconds to write. At 50k puts/s, the WAL grows at roughly 50 MB/s, or about 3 GB per minute, so the log must be truncated aggressively.
Snapshot vs WAL vs both
| Option | Data lost on crash | Recovery time | Steady-state cost |
|---|---|---|---|
| Snapshot only | Everything since last snapshot | Fast (one load) | Periodic large writes |
| WAL only | Almost nothing | Slow, grows with history | Per-write append |
| Snapshot + WAL | Almost nothing | Bounded: load + short replay | Both, but amortized |
I choose snapshot + WAL. The snapshot bounds recovery time and lets the log be truncated. The WAL narrows the loss window to the interval since the last log flush. Since the cache is an optimization, a snapshot-only design is also defensible if losing a few minutes of writes is acceptable, and it is much simpler.
Write path
- Serialize the record:
[length][type][key][value][expiry][CRC32]. - Append to an in-memory buffer owned by a dedicated writer thread (or a lock-free queue). The hot path never touches the disk.
- Apply the change to the in-memory map and list.
The log record is ordered before the apply, but the ordering only matters relative to what gets flushed, not what the caller waits on.
Flush policy is the durability knob:
- Async, flush every ~10-100 ms (default): survives a process crash as long as buffers were handed to the OS; loses at most a few tens of ms on power loss. Added hot-path latency is a queue push, around a microsecond.
- Group commit with
fsync: batch many writes perfsync, giving a few ms of latency but much better throughput. Use this when stronger guarantees are required. - Synchronous
fsyncper put: correct but limits throughput to the device's sync rate. Not appropriate at 50k puts/s unless the device is very fast.
Log put and delete records. Evictions need not be logged, because replaying puts in order against a fixed capacity reproduces the same evictions deterministically.
The recency trap on get
Every get changes the order. Logging each one would turn the read-heavy path into a disk-write path and defeat the purpose. My default is approximate recency:
- Do not log gets.
- Recency in the snapshot reflects the in-memory order at snapshot time, which captures reads up to that moment.
- Recency in the WAL reflects only puts.
The result is a slightly imperfect eviction order after restart, but the right working set is present, and that is what matters for warmth. If exact order is required, either log touches in batches (for example, periodically emit a compact "recently touched" key list), or sample-and-sort: record a coarse last-access timestamp per entry and reconstruct order by sorting on it at load time.
Snapshot procedure
Take a consistent snapshot without blocking the cache for seconds:
- Briefly lock and record the current WAL position, then copy-on-write fork the process, or iterate under a short lock in chunks using a per-entry version stamp.
- Write entries in MRU-to-LRU order to
snapshot.tmp, with a header, per-block checksums, and a footer. fsyncthe file,renameit tosnapshot.<id>, thenfsyncthe directory so the rename itself is durable.- Only then delete WAL segments older than the recorded position, and keep the previous snapshot as a fallback.
Take snapshots on a schedule (for example every few minutes) or when the WAL exceeds a size threshold, whichever comes first.
Recovery
- Find the newest snapshot whose header and footer checksums validate. If it is corrupt, fall back to the previous one. If none is valid, start cold.
- Load entries in order. Because they are stored MRU to LRU, insert them so that final list order matches. Rebuild the hash map and the pointers.
- Replay WAL segments starting at the recorded position. Validate each record's length and CRC. At the first invalid or incomplete record, stop and truncate there: that is a torn tail from the crash, and everything after it is untrustworthy.
- Apply puts and deletes in order, evicting from the LRU end whenever capacity is exceeded.
- Drop entries whose absolute expiry has passed.
- Open a fresh WAL segment and begin serving. Optionally serve while loading in the background, treating not-yet-loaded keys as misses.
Recovery time is dominated by reading ~1 GB, about a few seconds on NVMe, plus replaying at most a few minutes of log.
Failure modes and common mistakes
- Non-atomic snapshot replacement leaving a half-written file in place. Use tmp + fsync + rename + directory fsync.
- No checksums, so a torn record is replayed as garbage.
- Unbounded WAL, making recovery time grow forever.
- Logging every
get, destroying read latency. - Holding a global lock during the whole snapshot, causing latency spikes.
- Persisting relative TTLs, so entries live too long after a long outage.
- Stale data: a warm cache may hold values that changed in the source during downtime. Mitigate with short TTLs, a version or epoch stamp stored with entries, or a "restore only if downtime under X" rule.
Distributed extension
For a sharded or replicated cache, each node persists its own shard with this scheme. Alternatively, a restarting node can warm itself from a replica's hot keys, and consistent hashing limits how many keys move when a node is absent. The same trade-off applies: replicate asynchronously for warmth, synchronously only if the cache is the system of record.