KatInterview

Repair a Faulty LRU Cache and Add Crash-Safe Persistence

Data Structure DesignModel answer
MediumModel answerData Structure Designlru-cachedebuggingwrite-ahead-log

Last 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.