Repair a Faulty LRU Cache and Add Crash-Safe Persistence
Data Structure DesignModel answerLast updated
Find and fix the bugs in a broken fixed-capacity LRU cache, then make its acknowledged writes survive a crash using an append-only log, snapshots and atomic file replacement.
A teammate's in-memory cache is returning wrong results in production. Your job has two stages: repair it, then make its contents survive a restart.
The original code is not available, so here is a stand-in with the same structure. It is meant to be a least-recently-used cache that never holds more than capacity entries.
class Cache:
"""Keeps at most `capacity` entries; when full, drops the least recently used one."""
def __init__(self, capacity):
self.capacity = capacity
self.items = {} # key -> value
self.recency = [] # keys; index 0 = least recently used, last = most recently used
def get(self, key):
if key in self.items:
return self.items[key]
return None
def put(self, key, value):
if len(self.items) > self.capacity:
victim = self.recency.pop()
del self.items[victim]
self.items[key] = value
self.recency.append(key)
Before you start, say which assumptions you would confirm with the requester. For example: does a read count as a use, what does overwriting an existing key do, is capacity 0 legal, must the cache survive a process crash only or a power loss too, and must recency order be restored after restart or only the data?
Part 1: Debug
List every bug you can find. For each one, give a short call sequence that demonstrates it. Then write a corrected version where get and put run in constant time, state the complexity, and describe the tests that would have caught each bug (one targeted test per bug).
Part 2: Durability
Extend the repaired cache so that after a crash and restart it contains the same keys and values it had acknowledged before the crash. Explain:
- what is written to disk, in what format, and in what order relative to the in-memory update;
- how recovery works, including a half-written record at the end of the file;
- how recovery stays consistent with eviction even though reads are not persisted;
- how you stop the on-disk data from growing forever, and how you make switching to a new snapshot atomic;
- what durability costs in latency and throughput.
Hints
Hint 1
Trace a cache of capacity 2 through put(a), put(b), put(c), then get(a), and then put(a) twice. Check which key is removed, how many entries exist, and what the recency list contains.
Hint 2
For constant-time operations you need a hash map from key to a node in a doubly linked list (or an ordered dictionary). Every get hit and every overwrite should move the node to the most-recent end.
Hint 3
For durability, replay must not re-decide evictions, because reads were never logged and would lead to different victims. Log evictions explicitly, make each record self-checking with a length and checksum, fsync before acknowledging, and replace snapshots with write-temp, fsync, rename, fsync-directory.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Bugs and fixes
Assumptions I would state: a get hit counts as a use; put on an existing key overwrites the value and refreshes recency without evicting anything; capacity 0 means nothing is ever stored; get on a missing key returns None.
Bugs, each with a reproducing sequence
getnever refreshes recency. Capacity 2:put(a),put(b),get(a),put(c). A correct cache evictsb. This one would evicta(once the other bugs are fixed), becauseastill looks oldest.- Eviction removes the wrong end.
recency.pop()removes the most recently used key, not the least. After the cache is full, the newest key is discarded. - Wrong threshold: the cache can exceed capacity. The check is
len > capacityand runs before insertion. Capacity 1:put(a),put(b),put(c). The size reaches 2 and stays above the limit, and eviction only starts one insert late. - Overwrites add duplicates to the recency list.
put(a,1),put(a,2)leavesrecency = [a, a]. A later eviction deletesafromitems, and the stale secondathen triggersKeyErroron a later eviction, or evicts a key that is no longer present. - Overwrites can evict an unrelated key. On a full cache, updating an existing key is not a growth, yet the code runs eviction anyway.
- Capacity 0 and an empty recency list. With capacity 0, popping from an empty list raises
IndexError; the cache should simply store nothing. - Performance. Even once corrected, a Python list needs O(n) to remove a key from the middle or pop from the front, so refreshing recency is linear.
Corrected implementation
A hash map plus a doubly linked list gives O(1) for both operations. Python's OrderedDict is exactly that:
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.d = OrderedDict() # first = least recent, last = most recent
def get(self, key):
if key not in self.d:
return None
self.d.move_to_end(key) # a read is a use
return self.d[key]
def put(self, key, value):
if self.capacity <= 0:
return
if key in self.d:
self.d[key] = value
self.d.move_to_end(key)
return
if len(self.d) >= self.capacity:
self.d.popitem(last=False) # drop least recently used
self.d[key] = value
Both operations are O(1) average time, and space is O(capacity). If the interviewer wants no library help, implement the same thing with a dict from key to node and a doubly linked list with sentinel head and tail nodes.
Tests, one per bug
- Read refreshes recency (bug 1): the sequence above must evict
b. - Evicts the oldest (bug 2): fill to capacity, add one more, assert the first inserted key is gone and the newest is present.
- Size bound (bug 3): after many inserts,
lennever exceeds capacity. - Overwrite (bugs 4, 5):
put(a,1),put(a,2)on a full cache keeps all other keys, returns 2, and leaves one recency entry. - Capacity 0 and 1 (bug 6): no exceptions; capacity 1 keeps only the latest key.
- A randomized test that compares against a trivially correct, slow reference model over thousands of random operations.
Part 2: Durability
Guarantee
State it first: every put that returned successfully is present after a process crash or power loss. That requires fsync (not just write or flush, which only reach the OS page cache). If only process crashes mattered, a plain write would suffice because the OS keeps the data. Recency from reads is not guaranteed to be exact, since reads are not persisted; that is a deliberate trade-off to keep reads fast.
On-disk format: an append-only log plus snapshots
Each log record is [length][checksum][type][key][value], with types PUT and EVICT. The checksum (CRC32 or similar) covers everything after it.
Write path for put:
- Determine in memory whether this insert will evict, and which key.
- Append the
EVICTrecord (if any) and thePUTrecord to the log as one buffered write. fsyncthe log.- Apply the change to the in-memory structure.
- Acknowledge to the caller.
Logging before applying is the write-ahead rule: if a crash happens between steps 3 and 4, replay recreates the change, and the caller was never told it succeeded, so nothing acknowledged is lost.
Why evictions are logged
If replay re-ran the normal eviction logic, it would pick victims from the replay-time recency order, which differs from the original order because get calls were never logged. The result could be a different key set. Recording EVICT explicitly makes replay a pure, deterministic application of records with no policy decisions, so recovered contents equal the pre-crash contents.
Recovery
- Load the latest complete snapshot, if any, inserting entries in the order they were saved (least to most recent) so approximate recency is preserved.
- Replay the log that belongs to that snapshot record by record, applying
PUTandEVICTdirectly. - Stop at the first record that is truncated or fails its checksum. That is a torn write from the crash. Truncate the file at the last good offset and continue appending from there. Because we only acknowledge after
fsync, a torn record was never acknowledged, so dropping it is safe. A bad record in the middle of the file (followed by valid data) indicates real corruption and should be reported, not silently skipped.
Bounding disk usage
The log grows with every write, even when keys are overwritten. Periodically (for example when the log exceeds a multiple of the live data size) take a snapshot:
- Write the full contents, in recency order, to
snapshot.tmp, with a header holding a generation number and a checksum or trailer. fsyncthe temp file.renameit oversnapshot(atomic on POSIX within a filesystem).fsyncthe containing directory so the rename itself is durable.- Switch to a fresh log file tied to the new generation, then delete the old log.
A crash at any step leaves either the old snapshot with its old log, or the new snapshot (with a new, possibly empty log). Naming logs by generation lets recovery ignore a stale log that predates the snapshot. Writes must pause or be copied into the new log while the snapshot is taken; a simple approach is to hold the cache lock briefly to copy the state, then write it out in the background.
Cost and trade-offs
- An
fsyncper write costs roughly 0.1 to 10 ms depending on storage (SSD versus network disk), capping a single-writer cache at hundreds to a few thousand writes per second. - Group commit batches the records of concurrent writers into one
fsync, greatly increasing throughput at a small latency cost. - Relaxing to fsync every N ms improves speed but weakens the guarantee to "lose at most the last N ms". That is acceptable only if agreed with the requester.
- Reads stay purely in memory, so they are unaffected.
Common mistakes
- Calling
flush()and believing the data is on disk. - Updating memory before the log, then crashing and losing an acknowledged write (or acknowledging something never logged).
- Letting replay re-run eviction instead of logging it.
- Rewriting the snapshot in place, so a crash leaves a half-written file.
- Forgetting to
fsyncthe directory after a rename. - Treating any corrupt record, including a torn tail, as fatal, or alternatively skipping corruption in the middle of the log.