Memoization Cache: Key Design and Write-Ahead Log Recovery
Data Structure DesignModel answerLast 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.
getandputmust run in O(1) time, not counting key construction.- In Part 2, a
file_pathis 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), andf(a=1, b=2)share one cache entry when the function signature saysbhas a default of2? What about a call that omitsbentirely 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)
getandput - Edge cases in the decorator: a cached
Noneresult (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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Design Decisions
Part 1 — Key Generation and LRU Mechanics
Identifying equivalent calls
A function call is identified by two things: which function is being called, and the logical set of argument values it receives. The tricky part is that Python allows the same logical call to be written several ways — f(1, 2), f(1, b=2), and f(a=1, b=2) are all identical if the signature is def f(a, b). Using the raw (args, kwargs) tuple as the key would treat these as different entries, which is wrong.
The fix is inspect.signature(func).bind(*args, **kwargs).apply_defaults(). This returns a BoundArguments whose .arguments ordered dict contains every parameter name mapped to its resolved value, whether it came in positionally, by keyword, or from a default. Converting that to a sorted tuple of (name, value) pairs gives a canonical form.
The function itself is identified by (func.__qualname__, func.__module__). Using the object identity (id(func)) would break across restarts (Part 2), and using only __name__ would collide for two functions with the same name in different modules.
import inspect, pickle, hashlib
_MISS = object() # sentinel distinct from None
def make_key(func, args: tuple, kwargs: dict):
sig = inspect.signature(func)
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
canonical_args = tuple(bound.arguments.items()) # ordered, normalized
func_id = (func.__qualname__, func.__module__)
try:
return (func_id, canonical_args) # hashable fast path
except TypeError:
# At least one argument is unhashable; fall back to repr-based key.
# repr is not guaranteed collision-free, but is a reasonable degradation.
repr_args = tuple((k, repr(v)) for k, v in bound.arguments.items())
return (func_id, repr_args, "__repr_fallback__")
Common mistake: using hash() to compress the key. Hash collisions are rare but real; the cache would return a wrong cached value. Keep the full tuple as the key inside the dict.
LRU data structure
Use collections.OrderedDict. It tracks insertion order, supports O(1) move_to_end, and popitem(last=False) removes the oldest entry in O(1). This matches exactly what LRU needs without a manual linked list.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int, file_path: str | None = None) -> None:
self.capacity = capacity
self._cache: OrderedDict = OrderedDict()
self._log_fh = None
if file_path:
self._recover(file_path)
self._log_fh = open(file_path, "ab")
def get(self, key):
if key not in self._cache:
return _MISS
self._cache.move_to_end(key) # mark as most-recently used
return self._cache[key]
def put(self, key, value) -> None:
if key in self._cache:
self._cache.move_to_end(key)
self._cache[key] = value
if len(self._cache) > self.capacity:
self._cache.popitem(last=False) # evict LRU
if self._log_fh:
self._append_record({"op": "put", "key": key, "value": value})
The decorator
The decorator must distinguish a cached None from a miss. Using None as the sentinel would silently serve stale misses. The private _MISS object handles this. Exceptions are not cached by default — re-raising them is the safer choice; caching an exception result is surprising.
import functools
def memoize(cache: LRUCache):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = make_key(func, args, kwargs)
result = cache.get(key)
if result is not _MISS:
return result
result = func(*args, **kwargs) # exceptions propagate, nothing cached
cache.put(key, result)
return result
return wrapper
return decorator
Part 2 — Write-Ahead Log and Crash Recovery
Record framing
The core problem: how do you split a file back into records when the payload is arbitrary binary data that may contain any byte sequence?
Delimiter-based framing (e.g., newlines) requires escaping every occurrence of the delimiter in the payload, which is error-prone. The robust approach is length-prefixed framing:
[ 4-byte big-endian uint32: payload length ][ payload bytes ]
On replay, read 4 bytes to get n, then read exactly n bytes. If fewer than n bytes remain, the record was torn — discard it and stop. No escaping needed; the length field is always at a known offset.
Serialize each record with pickle (within-process use) or json after encoding non-serializable keys. pickle is simpler here since the keys are Python tuples already in memory.
import struct, pickle, os
_HEADER = struct.Struct(">I") # big-endian unsigned 32-bit int
def _encode_record(self, data: dict) -> bytes:
payload = pickle.dumps(data)
return _HEADER.pack(len(payload)) + payload
def _append_record(self, data: dict) -> None:
raw = self._encode_record(data)
self._log_fh.write(raw)
self._log_fh.flush()
os.fsync(self._log_fh.fileno()) # force to disk; survives power loss
flush() alone pushes bytes out of Python's buffer into the OS page cache — enough for a process crash. fsync() additionally flushes the OS buffer to stable storage. It is significantly slower (a few milliseconds per call on spinning disk) but necessary if the durability requirement includes power failure.
Recovery replay
def _recover(self, file_path: str) -> None:
try:
fh = open(file_path, "rb")
except FileNotFoundError:
return
with fh:
while True:
header = fh.read(_HEADER.size)
if len(header) < _HEADER.size:
break # EOF or torn header — stop
(n,) = _HEADER.unpack(header)
payload = fh.read(n)
if len(payload) < n:
break # torn record — discard and stop
record = pickle.loads(payload)
if record["op"] == "put":
key, value = record["key"], record["value"]
if key in self._cache:
self._cache.move_to_end(key)
else:
self._cache[key] = value
if len(self._cache) > self.capacity:
self._cache.popitem(last=False)
Replay processes records in order. Each put restores both the value and the recency position. The final in-memory state mirrors what was in the cache at the time of the crash.
What to log
putoperations: always log with key and value.gethits: log if you need exact LRU order after recovery. This doubles write traffic for read-heavy workloads. A pragmatic trade-off: log hits in a high-durability system, skip them when throughput matters and approximate recency on restart is acceptable.- Evictions are implied by replaying
puts against a capacity-limited cache; no separate eviction record is needed.
Preventing unbounded log growth
The log grows forever as written. Two options:
- Compaction: periodically write a snapshot (the full current cache contents as a single batch of
putrecords) to a new file, then atomically replace the old log. On recovery, read the snapshot file only. - Log rotation: truncate the log after a snapshot is confirmed durable.
A safe rename pattern: write snapshot to file_path.tmp, fsync it, then os.replace(tmp, file_path) which is atomic on POSIX systems.
Stability of keys across restarts
(func.__qualname__, func.__module__) is stable as long as the source code is not renamed. id(func) is not stable — it changes every process run. This is why using the qualified name is important for Part 2 even if it seemed like a minor detail in Part 1.