Designing a Validated In-Memory Cache for Repeated Parsing
Data Structure DesignModel answerLast updated
Speed up a script that repeatedly parses files by adding a thread-safe, bounded, in-memory cache, and justify its keys, eviction, staleness checks and complexity.
You have a script you wrote earlier that, for each input path, locates a file and parses it into a computed result (for example, reading a license file and extracting structured data). Profiling shows the same files are processed over and over, and the script is now slow.
Propose and analyze a dictionary-backed, in-memory cache that speeds up repeated lookups. Your answer should cover:
- Placement. Which call in the script is worth caching, why it qualifies, and which calls should be left alone.
- Keys and values. What identifies a computation, what you store, and what normalization ensures that logically equal inputs share one entry.
- Hit rate. An estimate of the expected hit rate and the assumptions behind it (number of distinct inputs versus number of lookups, locality of access).
- Eviction. Which policy you pick (none, LRU, LFU, TTL) and how the working-set size and memory budget justify it.
- Staleness. How you keep entries correct when the underlying file changes, and which consistency-versus-cost trade-off you accept.
- Concurrency. What can go wrong with multiple threads or processes (races, many callers missing the same key at once) and how you prevent it.
- Code.
get/putpseudocode or real code that includes the validity check performed on every read. - Complexity. Time and space cost of the operation before and after adding the cache.
Hints
Hint 1
Only pure, deterministic, expensive work whose inputs repeat is worth caching. Side effects, time-dependent calls and trivially cheap operations are not.
Hint 2
A cheap fingerprint of the source (modification time in nanoseconds, size, inode) can be compared on every read, and costs far less than re-reading and re-parsing the file.
Hint 3
When many threads miss the same key together, let one compute while the rest wait on a per-key lock and then re-check the cache. Never hold the global lock during disk I/O.
Hint 4
With N lookups over U distinct keys and unlimited capacity, only first accesses miss, so the hit rate is roughly 1 - U/N.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The goal is not just "wrap it in a memoizer" but to show that the cache is correct (it never serves stale data without us accepting it knowingly), bounded, and safe under concurrency. I'll use the running example of resolve_and_parse(path) -> Result, which reads a file and parses it.
1. Where to cache
Cache the parse/resolve step. It qualifies because it is:
- Expensive: a syscall plus O(L) work in the file length.
- Deterministic: identical content yields an identical result.
- Repeated: the same files recur (e.g. one license referenced by thousands of packages).
Do not cache calls with side effects (writing, logging), calls depending on time or randomness, calls that are already O(1) (the cache adds overhead), or inputs that never recur (they only pollute the cache).
2. Keys and values
- Key: a canonical path, e.g.
realpath(expanduser(p)), so./a/../b, symlinks and~collapse to one entry. For license strings, strip, case-fold and collapse internal whitespace so"MIT "and"mit"match. - Value:
(fingerprint, result), where the fingerprint is(mtime_ns, size, inode).
Keys must be hashable and immutable. Return immutable results or copies so callers cannot corrupt shared entries.
3. Hit rate
With N lookups over U distinct keys and unbounded capacity, only the first access to each key misses, so hit_rate ≈ 1 − U/N. For 100,000 scans over 300 distinct files that is about 99.7%.
Assumptions: U is small relative to N (if U ≈ N the cache is pure overhead); popularity is skewed (Zipf-like, so a small cache catches most hits); and if capacity is below U, reuse distance must be shorter than the time to eviction. Verify with hit/miss counters rather than trusting the estimate.
4. Eviction
- Working set small (hundreds to thousands of small results): plain dict, no eviction. Simplest and correct.
- Memory-capped or unbounded input: LRU via
OrderedDict, O(1) per operation, matching temporal locality. - LFU only if popularity is stable and one-off scans would flush an LRU; it needs more bookkeeping.
- TTL is a staleness tool, not a sizing tool; use it when no cheap validator exists (e.g. a remote source).
Choice here: bounded LRU with capacity ≈ memory_budget / avg_entry_size.
5. Invalidation and staleness
Validate on every read: stat the file and compare against the stored fingerprint; on mismatch, drop the entry and recompute. stat is much cheaper than read plus parse.
Caveats:
- Coarse mtime granularity or a same-size rewrite within one clock tick can fool the check. If strict correctness matters, use a content hash (SHA-256); this costs a full read but still saves the parse.
- Take the fingerprint before computing. If the file changes mid-compute, the stored fingerprint is already old, so the next read recomputes. This errs toward recomputation, never toward staleness.
| Strategy | Cost per read | Consistency |
|---|---|---|
| Stat-on-read | one syscall | near-strong |
| TTL | free | stale for up to TTL |
| No validation | free | correct only if inputs are immutable |
6. Concurrency
- Races on get/put:
move_to_endand eviction are multi-step, so guard the structure with one short-held lock. Never hold it during I/O. - Stampede: if N threads miss the same key, N parses happen. Use single-flight: a per-key lock where the first thread computes and the others wait, then re-check the cache (double-checked locking).
- Failures: do not cache exceptions; release the per-key lock in
finallyso waiters retry rather than deadlock. - Multiple processes: memory is not shared, so the cache is process-local. Options: accept duplication (usually fine), use Redis/memcached (network hop), or a file cache with atomic rename. Process-local is the right default for a script.
7. Code
import os
import threading
from collections import OrderedDict
class ValidatedLRUCache:
def __init__(self, compute, capacity=1024):
self._compute = compute
self._capacity = capacity
self._data = OrderedDict() # key -> (fingerprint, value)
self._lock = threading.Lock() # guards _data, _inflight, counters
self._inflight = {} # key -> per-key lock
self.hits = 0
self.misses = 0
@staticmethod
def normalize(path):
return os.path.realpath(os.path.expanduser(path))
@staticmethod
def fingerprint(key):
st = os.stat(key)
return (st.st_mtime_ns, st.st_size, st.st_ino)
def _lookup_locked(self, key, fp):
entry = self._data.get(key)
if entry is None:
return False, None
if entry[0] != fp: # source changed
del self._data[key]
return False, None
self._data.move_to_end(key)
self.hits += 1
return True, entry[1]
def put(self, key, fp, value):
with self._lock:
self._data[key] = (fp, value)
self._data.move_to_end(key)
while len(self._data) > self._capacity:
self._data.popitem(last=False)
def get(self, path):
key = self.normalize(path)
fp = self.fingerprint(key) # before compute
with self._lock:
found, value = self._lookup_locked(key, fp)
if found:
return value
key_lock = self._inflight.setdefault(key, threading.Lock())
try:
with key_lock:
with self._lock: # re-check: another thread may have filled it
found, value = self._lookup_locked(key, fp)
if found:
return value
self.misses += 1
value = self._compute(key) # no global lock held during I/O
self.put(key, fp, value)
return value
finally:
with self._lock:
self._inflight.pop(key, None)
A small wrinkle: popping the in-flight lock in finally is safe because late arrivals re-check the cache and, on a hit, never need the lock.
8. Complexity
- Before: each lookup costs one syscall plus O(L) parsing, where L is the file length. Extra space is O(1).
- After, hit: one
statplus O(1) hash lookup and LRU update, so O(1) with respect to L. - After, miss: the original cost plus O(1) bookkeeping.
- Space: O(C · S) for capacity C and average entry size S, plus O(in-flight keys) for per-key locks.
- Overall: expected time per lookup is roughly
h · O(1) + (1 − h) · O(L)where h is the hit rate.
Common mistakes
- Caching without any validation, then serving stale data after a file edit.
- Holding the global lock during I/O, which serializes all callers.
- Forgetting normalization, so equal inputs get separate entries and the hit rate collapses.
- Caching failures or mutable results that callers later modify.
- Using an unbounded dict for unbounded input, causing a memory leak.