Concurrent Least-Recently-Used Cache with Constant-Time Operations
Data Structure DesignModel answerLast updated
Build a fixed-capacity cache with O(1) lookup, update and eviction by recency, then make it safe for many threads and state exactly what consistency it guarantees.
Concurrent Least-Recently-Used Cache with Constant-Time Operations
You are asked to build a small in-memory cache that holds at most capacity entries, where capacity is a positive integer. It supports two operations:
get(key): if the key is stored, return its value and treat the key as the most recently used one. If it is not stored, return a clearly defined "miss" result (for example-1,None, or an emptyOptional).put(key, value): if the key already exists, replace its value and treat it as the most recently used. Otherwise insert it as the most recently used entry. If this insertion would push the size abovecapacity, remove the entry that was used least recently.
Both operations must run in O(1) average time.
Part 1: Single-threaded design
Describe the data structures you would use and the invariants they maintain. Walk through the tricky cases: an empty cache, a cache with one entry, updating an existing key, a capacity of 1, and an insertion that triggers eviction.
Part 2: Concurrent callers
Now suppose many threads call get and put on the same instance at the same time. Explain how you would make it safe. In your answer:
- State the consistency guarantee you are offering.
- Identify the exact linearization point of
get,put, and eviction. - Discuss alternatives to a single lock and what they cost.
- Explain how you would test the result.
Questions worth settling first
- Are keys and values immutable? Can a value be null?
- Is strict linearizability required, or is approximate recency acceptable in exchange for throughput?
- Does an evicted value need cleanup (closing a handle, notifying a listener)?
- Is contention on one instance actually measured, or is a single lock likely enough?
Hints
Hint 1
Pair a hash map from key to node with a doubly linked list ordered by recency. Ask which structure gives O(1) lookup and which gives O(1) removal and reinsertion at a known position.
Hint 2
A `get` hit changes the recency order, so it mutates shared state. That is why a plain read-write lock does not let hits run in parallel. Think about what a single mutex must protect: the map, the list, and the size, together.
Hint 3
Sentinel head and tail nodes remove most null-pointer branches (empty, one element, capacity one). For scaling beyond one lock, think about sharding by key hash and what global-recency guarantee you give up when you do.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Single-threaded design
Structures
- A hash map
key -> node. - A doubly linked list of nodes ordered by recency. Each node stores
key,value,prev,next. The head side is most recent, the tail side is least recent. - Two sentinel nodes,
headandtail, that never hold data. Because every real node always has non-null neighbors, insertion and removal need no special cases for an empty list, a single node, or the ends.
Invariants
- The map and the list contain exactly the same set of keys.
size == len(map) <= capacity.- Walking from
head.nexttotail.prevvisits nodes from most to least recent. - Each node's key is stored in the node, so eviction can delete the right map entry from the tail node alone.
Operations
Helpers, all O(1): unlink(node), push_front(node), move_to_front(node).
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=None, value=None):
self.key, self.value = key, value
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.cap = capacity
self.map = {}
self.head, self.tail = Node(), Node()
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _push_front(self, n):
n.prev, n.next = self.head, self.head.next
self.head.next.prev = n
self.head.next = n
def get(self, key):
n = self.map.get(key)
if n is None:
return None # defined miss
self._unlink(n)
self._push_front(n)
return n.value
def put(self, key, value):
n = self.map.get(key)
if n is not None:
n.value = value
self._unlink(n)
self._push_front(n)
return
if len(self.map) == self.cap:
lru = self.tail.prev
self._unlink(lru)
del self.map[lru.key]
n = Node(key, value)
self.map[key] = n
self._push_front(n)
Edge cases
- Empty cache:
getmisses;putlinks between the two sentinels. - One entry: unlinking and relinking it is safe because the sentinels remain.
- Capacity 1: every new key evicts the previous one. Evict before inserting so the size never exceeds the capacity.
- Updating an existing key never evicts, even when full.
- A
geton the entry that is already most recent still works, just redundantly.
Complexity: O(1) average time per operation (hash lookups), O(capacity) space.
Making it thread-safe
Why get is a write. A hit reorders the list, so it modifies shared state. Two concurrent hits can corrupt prev/next pointers. This is the most common mistake: wrapping only put in a lock, or using a read-write lock and taking the read side for get.
Baseline: one mutex. Acquire a single lock at the start of get and put and release it at the end (for example with self.lock:). The lock protects invariants 1 to 4 together, since they span the map, the list, and the size.
Consistency guarantee: linearizability. Every operation appears to take effect atomically at one instant between its call and return, and the resulting order is consistent with a sequential LRU cache.
Linearization points (with a single lock):
get: the moment inside the critical section where the map lookup (and, on a hit, the move to front) happens. A miss linearizes at the lookup.put: the moment the map entry is installed or updated and the node is placed at the front, inside the critical section.- Eviction: part of the same
put. It linearizes at the same instant as theputthat caused it, so no observer can see the cache over capacity or see the new key present while the old victim is still present.
Because everything happens under one lock, the lock-held interval is the atomic step, and any point in it works as the linearization point.
Pitfalls
- Calling user code (eviction callbacks, value loaders,
__hash__/__eq__of foreign keys) while holding the lock can deadlock or stall everyone. Collect evicted entries into a local list and invoke callbacks after releasing the lock. The trade-off: a callback may observe a cache that has already moved on. - Returning a mutable value lets callers mutate it outside the lock. Prefer immutable values or defensive copies.
- A check-then-act pattern across two calls (
if get(k) is None: put(k, v)) is not atomic. Offer aget_or_computeorput_if_absentthat holds the lock, or accept duplicated work.
Alternatives and trade-offs
| Approach | Gain | Cost |
|---|---|---|
| Single mutex | Simple, strictly linearizable, easy to reason about | One hot lock; throughput caps at one core's worth of cache work |
| Read-write lock | Looks attractive | Useless for strict LRU, since hits write recency |
Sharding by hash(key) % N, each shard its own LRU and lock | Near-linear scaling with shards | Recency and capacity are per shard, so the global victim may not be the true LRU; hot shards evict early; capacity per shard is capacity / N |
| Approximate recency (record accesses in a lock-free buffer, apply in batches; or CLOCK / sampled eviction) | Hits avoid the global lock; very high read throughput | Recency is slightly stale, so strict linearizable LRU order is lost; harder to test |
| Per-entry timestamps plus periodic eviction | Cheap hits | Eviction is O(n) or needs a heap, and the order is approximate |
A sensible answer: start with one mutex, measure contention, then shard (for example 16 or 64 shards, roughly a few times the thread count) if the lock is hot. Move to buffered recency updates only if the product accepts approximate LRU. With a single lock, critical sections of tens of nanoseconds typically sustain millions of operations per second, which is enough for most services.
Testing concurrent behavior
- Sequential model check: run random operation sequences against the cache and a simple reference implementation (an ordered dictionary), and compare results.
- Invariant checks: after stress runs, verify map size equals list length, size is at most capacity, and list links are symmetric.
- Stress tests: many threads with overlapping keys, small capacity (1, 2, 3) to force constant eviction, run for a long time and under a race detector or thread sanitizer where available.
- History checking: record each call's start, end, arguments, and result, then check that some sequential ordering consistent with real-time order explains all results (a linearizability checker).
- Callback tests: verify each evicted entry's callback fires exactly once and never under the lock.
Common mistakes
- Forgetting that
getmodifies recency, and so locking it incorrectly. - Not storing the key in the node, making eviction unable to remove the map entry.
- Evicting after insertion, which briefly exceeds capacity and breaks capacity 1.
- Evicting when merely updating an existing key.
- Running callbacks while holding the lock.
- Claiming sharding preserves exact global LRU order.