Skip to main content
← PROBLEMS / LOW-LEVEL-DESIGN
An end-to-end domain learning journey

Implement a Thread-Safe
LRU Cache.

Implement an in-memory LRU cache with strict O(1) average-time get and put operations and zero-edge-case pointer bugs.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Database Indexing: B-Trees vs LSM-Trees
B-Trees organize sorted keys into fixed-size mutable pages optimized for fast, predictable point and range reads, whereas LSM-Trees buffer writes in memory and flush immutable sorted runs to disk for high write throughput.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. 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 every put().
  2. Head/Tail Edge-Case Bugs: Managing raw head/tail pointers without dummy sentinel nodes leads to null-pointer dereferences when capacity == 1 or when removing the last node.
O(1) Data Structure

HashMap Lookup + Sentinel Doubly Linked List (MRU <-> LRU)

HashMap<K, Node>O(1) direct node…Dummy Head (MRU)Insert / promote afte…Active Nodesprev <-> node <->…Dummy Tail (LRU)Evict tail.prev in…full -> pop tail.prev

Sentinel head/tail nodes eliminate null checks while the hash map gives O(1) node access.

Engineering Decision Framework
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 (dummy head and tail) 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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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).

Request & State Flow

Naive array/list shifting and `O(log N)` min-heaps

App WorkerSingleflight / L1Redis L2Origin DB1. GET key (coalesce duplicates)2. Check L2 distributed cache3. Single origin query on miss4. Populate cache with jitteredTTL
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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-null prev and next, making _remove(node) and _add_front(node) 4-line pointer swaps.
  • Update vs. Insert Order: In put(key, value), if key exists, update node.val and promote to MRU without evicting; only evict tail.prev when inserting a new key at len(map) > capacity.
  • Thread Safety: Guard get/put with a threading.Lock (or stripe across N shards for multi-core scale).
O(1) Operations

get(k) Promotion vs. put(k, v) Capacity Eviction

CallerHashMapDoublyLinkedList1. get(k) -> miss: return -12. get(k) -> hit: unlink + insertafter head3. put(new_k) at cap: unlinktail.prev, del map

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)
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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, Redis allkeys-lru eviction, and Linux page-cache active/inactive lists.
  • Multi-Core API Servers: Sharded LRU (64-128 segments) or SIEVE/Caffeine caches scale single-lock LRU to 1M+ ops/sec.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does an `LRUCache` use dummy `head` and `tail` sentinel nodes in its doubly linked list?

Recommended Learning Flow