KatInterview

Memoization Cache: Key Design and Write-Ahead Log Recovery

Data Structure DesignModel answer
HardModel answerData Structure Designlru-cachememoizationcrash-recovery

Last updated

Build a Python LRU memoization cache with correct argument-key normalization, then add crash recovery via an append-only log with torn-write handling.

Memoization Cache with Crash Recovery

You are building a memoization layer in Python. The cache stores the return value of a function call keyed on the function identity and its arguments. On a repeated call with equivalent arguments, the cached value is returned directly. The cache holds at most capacity entries; when it is full, it evicts whichever entry was used least recently.

Use this interface as your starting point:

class LRUCache:
    def __init__(self, capacity: int, file_path: str | None = None) -> None: ...
    def get(self, key):   ...  # returns the cached value, or a sentinel on a miss
    def put(self, key, value) -> None: ...

def make_key(func, args: tuple, kwargs: dict): ...

def memoize(cache: LRUCache):
    """Decorator that serves calls of the wrapped function from `cache`."""

Constraints

  • One cache instance may hold results for multiple different functions.
  • get and put must run in O(1) time, not counting key construction.
  • In Part 2, a file_path is provided; every mutation must be appended to that file and forced to disk before the call returns.

Questions worth clarifying before you code

  • Should f(1, 2), f(1, b=2), and f(a=1, b=2) share one cache entry when the function signature says b has a default of 2? What about a call that omits b entirely and relies on its default?
  • What should happen when an argument is unhashable or mutable (a list, a dict)? Should the call bypass the cache silently, or raise?
  • Should a call that raises an exception store anything in the cache?
  • In Part 2, does a cache hit (which updates recency) also need to be logged, so that LRU order is exact after a restart?
  • What durability level is required: surviving a Python process crash, or also surviving a sudden power loss?

Part 1 — Key generation, LRU mechanics, and the decorator

Implement make_key, the LRUCache class, and the memoize decorator.

Two calls must produce the same key when they invoke the same function with logically equivalent arguments, and must never produce the same key for calls that differ.

Your answer should address:

  • What uniquely identifies a function across multiple functions stored in the same cache
  • How positional arguments, keyword arguments, and default parameter values are normalized so that equivalent calls collide correctly
  • How to handle unhashable or otherwise un-keyable arguments
  • How the LRU eviction policy is implemented with O(1) get and put
  • Edge cases in the decorator: a cached None result (distinguishing it from a cache miss), and whether exceptions are cached

Part 2 — Persist mutations and recover after a crash

When file_path is given, the cache must append a record to that file for every change, then flush the write to disk. A new cache constructed with the same file_path must replay that log and reconstruct the cache contents and recency order as they were just before the crash.

Design the log record format. Specifically, decide how records are framed so that, after reopening the file, it can be split back into the exact records that were written — even if the last write was interrupted mid-way.

Your answer should address:

  • The record structure and the framing mechanism, with a clear argument for why a record boundary cannot be confused with payload data
  • Which operations are logged (writes, evictions, hits) and the replay rules that restore both values and LRU order
  • How a torn final record (partially written before a crash) is detected and handled
  • Whether keys remain stable between process restarts
  • How you would prevent the log from growing without bound

Hints

Hint 1

For key generation, inspect the function's signature with `inspect.signature` and call `.bind(*args, **kwargs).apply_defaults()` — this fills in defaults and normalizes positional vs. keyword forms into one canonical mapping. Then build the key as a tuple of (function qualified name + module, sorted keyword items). For unhashable arguments, fall back to `repr()` or skip caching entirely — pick one…

Hint 2

O(1) LRU is a classic: a dict maps keys to doubly-linked-list nodes; every access moves the touched node to the head; the tail is always the eviction candidate. Python's `collections.OrderedDict` gives you this for free with `move_to_end` and `popitem(last=False)`.

Hint 3

For the log, the reliable framing pattern is a length-prefixed record: write a fixed-width big-endian integer giving the byte length of the payload, then the payload. On replay, read the length field first; if fewer bytes remain than the declared length, the record is torn — discard it and stop. This avoids any delimiter-in-data problem without escaping.