When traffic spikes expose hidden coupling, combine a hash map (`key -> Node`) for O(1) lookup with a sentinel-bounded doubly linked list (dummy `head` and `tail`) for O(1) MRU promotion and LRU tail eviction.
TL;DR30-second simplified summary▾
Core Mechanics: Whether in an OS page cache, database buffer pool, or API cache, bounded memory forces eviction when capacity is exceeded.
Visual & Structural Flow: Depicts HashMap Lookup + Sentinel Doubly Linked List (MRU <-> LRU) (HashMap<K, Node> -> Dummy Head (MRU) -> Active Nodes -> Dummy Tail (LRU)); get(k) Promotion vs. put(k, v) Capacity Eviction (Caller -> HashMap -> DoublyLinkedList).
Trade-Offs & Production: Using a Python list (remove + append) is O(N) per get(), while a min-heap keyed by access timestamp degrades to O(log N) and leaves stale heap entries. Implement clean O(1) primitives with zero special cases: Sentinel head & tail: Every real node always has a non-null prev and next, making _remove(node) and _add_front(node) 4-line pointer swaps.
Failure Modes & Application: LRU (and its striped/W-TinyLFU variants) underpins caching across every layer: Language & OS Primitives: Python @functools.lru_cache, Redis allkeys-lru eviction, and Linux page-cache active/inactive lists.
Why O(1) LRU is the foundation of in-memory caching.
Why this matters: The mechanism: understand how Why O(1) LRU is the foundation of in-memory caching works from first principles.
Think of Why O(1) LRU is the foundation of in-memory caching as the intuition layer for Implement a Thread-Safe LRU Cache: The mechanism: understand how Why O(1) LRU is the foundation of in-memory caching works from first principles.
Whether in an OS page cache, database buffer pool, or API cache, bounded memory forces eviction when capacity is exceeded. To sustain high throughput, both get(key) and put(key, value)—including promoting a hit to Most Recently Used (MRU) and evicting the Least Recently Used (LRU)—must complete in O(1) time.
O(N) eviction stalls and null-pointer bugs without sentinel nodes.
Why this matters: The problem: see what breaks without O under real concurrency or scale.
Two implementation flaws break naive LRU caches:
- O(N) Linear Scan on Eviction: Tracking timestamps in a hash map without a linked list forces an
O(N)scan to find the oldest key on everyput(). - Head/Tail Edge-Case Bugs: Managing raw
head/tailpointers without dummy sentinel nodes leads to null-pointer dereferences whencapacity == 1or when removing the last node.
HashMap Lookup + Sentinel Doubly Linked List (MRU <-> LRU)
Sentinel head/tail nodes eliminate null checks while the hash map gives O(1) node access.
- Problem
- How to implement Implement a Thread-Safe LRU Cache without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When traffic spikes expose hidden coupling, combine a hash map (
key -> Node) for O(1) lookup with a sentinel-bounded doubly linked list (dummyheadandtail) for O(1) MRU promotion and LRU tail eviction. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Implement a Thread-Safe LRU Cache experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive array/list shifting and `O(log N)` min-heaps.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Naive array/list shifting and O(log N) min-heaps as the intuition layer for Implement a Thread-Safe LRU Cache: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Using a Python list (remove + append) is O(N) per get(), while a min-heap keyed by access timestamp degrades to O(log N) and leaves stale heap entries. Only HashMap + DoublyLinkedList achieves true O(1).
Naive array/list shifting and `O(log N)` min-heaps
Enterprise solution: Sentinel Doubly Linked List + Per-Instance Lock.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Implement clean O(1) primitives with zero special cases:
- Sentinel
head&tail: Every real node always has a non-nullprevandnext, making_remove(node)and_add_front(node)4-line pointer swaps. - Update vs. Insert Order: In
put(key, value), ifkeyexists, updatenode.valand promote to MRU without evicting; only evicttail.prevwhen inserting a new key atlen(map) > capacity. - Thread Safety: Guard
get/putwith athreading.Lock(or stripe acrossNshards for multi-core scale).
get(k) Promotion vs. put(k, v) Capacity Eviction
Both get() and put() execute a constant number of pointer and hash-map operations.
import threading
class _Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key: int = 0, val: int = 0):
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.map: dict[int, _Node] = {}
self.head, self.tail = _Node(), _Node()
self.head.next, self.tail.prev = self.tail, self.head
self.lock = threading.Lock()
def _remove(self, node: _Node) -> None:
node.prev.next, node.next.prev = node.next, node.prev
def _add_front(self, node: _Node) -> None:
node.next, node.prev = self.head.next, self.head
self.head.next.prev = self.head.next = node
def get(self, key: int) -> int:
with self.lock:
node = self.map.get(key)
if not node:
return -1
self._remove(node)
self._add_front(node)
return node.val
def put(self, key: int, value: int) -> None:
with self.lock:
if key in self.map:
node = self.map[key]
node.val = value
self._remove(node)
self._add_front(node)
return
if len(self.map) >= self.cap:
lru = self.tail.prev
self._remove(lru)
del self.map[lru.key]
node = _Node(key, value)
self.map[key] = node
self._add_front(node)
Where LRU caches are used in systems.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
LRU (and its striped/W-TinyLFU variants) underpins caching across every layer:
- Language & OS Primitives: Python
@functools.lru_cache, Redisallkeys-lrueviction, and Linux page-cache active/inactive lists. - Multi-Core API Servers: Sharded LRU (
64-128segments) or SIEVE/Caffeine caches scale single-lock LRU to1M+ops/sec.
Practice: Make the trade-off yourself.
Why does an `LRUCache` use dummy `head` and `tail` sentinel nodes in its doubly linked list?