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

Design a High-Concurrency LRU
& W-TinyLFU Cache.

A classic HashMap + DoublyLinkedList LRU serializes every read behind a global write lock, collapsing 64-core throughput from 1.2M ops/sec to 140K ops/sec.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, eliminate read-path lock contention via 128-way lock striping or Caffeine-style read ring buffers (or SIEVE 1-bit `visited` flags), and pair with W-TinyLFU (1% window + 4-bit Count-Min Sketch) for scan resistance.

TL;DR30-second simplified summary
▾

Core Mechanics: Every textbook teaches HashMap + DoublyLinkedList for O(1) LRU.

Visual & Structural Flow: Depicts 1% Admission Window -> 4-bit Count-Min Sketch -> Segmented Main (128 Striped Shards -> Read Ring Buffer -> W-TinyLFU (CMS) -> Timing Wheel TTL); Lock-Free Read Buffer Drain & W-TinyLFU Admission Filter (64 Reader Cores -> Striped Read Buffer -> 4-bit CMS Filter -> Main SLRU (99%)).

Trade-Offs & Production: A ReentrantReadWriteLock still requires an exclusive write lock on get() to mutate the LRU list. Scale to 1.2M+ ops/sec within 8 GB (~880 MB metadata + 7.12 GB payload): Zero-Contention Read Path: Partition into 128 shards (78,125 entries and 9,375 ops/s per.

Failure Modes & Application: Caffeine (Java) and Ristretto/Otter (Go) implement this exact architecture: L1 In-Process Caches: Sits in front of Redis/DB in high-QPS API servers to serve 95% hot reads in < 50 us.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why classic LRU fails on 64-core servers.

Why this matters: The mechanism: understand how Why classic LRU fails on 64-core servers works from first principles.

Think of Why classic LRU fails on 64-core servers as the intuition layer for Design a High-Concurrency LRU & W-TinyLFU Cache: The mechanism: understand how Why classic LRU fails on 64-core servers works from first principles.

Every textbook teaches HashMap + DoublyLinkedList for O(1) LRU. On a 64-core server handling 1,200,000 get()/sec (95% reads), get() is not read-only: it must unlink the node and move it to the MRU head—forcing a global write lock that caps throughput at ~140,000 ops/sec (>85% CPU spent spinning).

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Mutex convoying, one-hit scan pollution, and expired-key leaks.

Why this matters: The problem: see what breaks without Mutex convoying, one-hit scan pollution, and expired-key leaks under real concurrency or scale.

Three bottlenecks destroy in-process cache performance:

  1. Global Write-Lock Contention: 64 threads serialize on one mutex (140k vs 1.2M ops/sec).
  2. One-Hit Scan Pollution: A batch job scanning 10M cold keys flushes the entire hot working set out of a pure LRU.
  3. Lazy-TTL Memory Leak: Keys that expire without being read again occupy the 8 GB budget unless swept.
W-TinyLFU + Striped Cache

1% Admission Window -> 4-bit Count-Min Sketch -> Segmented Main

128 Striped Shards9.4k ops/s/shard…Read Ring BufferLossy batch promote…W-TinyLFU (CMS)Blocks 1-hit scan…Timing Wheel TTLO(1) active expiry…periodic CMS halving

Striped read ring buffers remove read-path locks while W-TinyLFU protects hot entries from sequential scans.

Engineering Decision Framework
Problem
How to implement Design a High-Concurrency LRU & W-TinyLFU 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, eliminate read-path lock contention via 128-way lock striping or Caffeine-style read ring buffers (or SIEVE 1-bit visited flags), and pair with W-TinyLFU (1% window + 4-bit Count-Min Sketch) for scan resistance.
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 Design a High-Concurrency LRU & W-TinyLFU 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 `RWLock` and un-aged frequency counters.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Naive RWLock and un-aged frequency counters as the intuition layer for Design a High-Concurrency LRU & W-TinyLFU Cache: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

A ReentrantReadWriteLock still requires an exclusive write lock on get() to mutate the LRU list. Meanwhile, a naive LFU without periodic counter halving lets historically hot keys permanently block newly hot keys.

Design Trade-Off

Naive `RWLock` and un-aged frequency counters

Before · Fixed TTL + Direct DB
  • Synchronized cache avalanche
  • 1,000 duplicate DB queries
  • Big-key event-loop freeze
After · Jittered TTL + Singleflight
  • 1 origin fetch per expired key
  • Randomized TTL spreads expiry
  • O(1) HashMap + DLL eviction
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Lock Striping / SIEVE + W-TinyLFU + Timing Wheel.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Scale to 1.2M+ ops/sec within 8 GB (~880 MB metadata + 7.12 GB payload):

  • Zero-Contention Read Path: Partition into 128 shards (78,125 entries and 9,375 ops/s per shard) + a Caffeine-style striped read ring buffer (drains promotions asynchronously under tryLock) or SIEVE (if (!node.visited) node.visited = true; avoids even dirtying the cache line on hot reads!).
  • Scan Resistance (W-TinyLFU): Admit new keys into a 1% Window LRU; on eviction, a 4-bit Count-Min Sketch (periodically halved) admits the candidate to Main SLRU only if its frequency beats the Main victim.
  • Active TTL: Hierarchical timing wheel sweeps expired entries in O(1).
Deferred Promotion & Eviction

Lock-Free Read Buffer Drain & W-TinyLFU Admission Filter

64 Reader CoresStriped Read Buffer4-bit CMS FilterMain SLRU (99%)1. get(k): ConcurrentHashMap +append ring2. tryLock() drains batch ->promote/evict3. One-hit scan (freq=1 <victim=12) -> reject

Readers never wait on list locks; a single tryLock drain updates LRU order and filters one-hit scans via CMS.

// SIEVE / Deferred-Read Pattern: avoid write-locking on hot reads
public V get(K key) {
    Node<K, V> node = map.get(key); // ConcurrentHashMap lock-free read
    if (node == null || node.isExpired(clock.millis())) return null;
    if (!node.visited) {
        node.visited = true; // Avoids cache-line bouncing on hot keys
    }
    readBuffer.offer(node);  // Lossy ring buffer drained asynchronously
    return node.value;
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where high-concurrency W-TinyLFU caches are used.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Caffeine (Java) and Ristretto/Otter (Go) implement this exact architecture:

  • L1 In-Process Caches: Sits in front of Redis/DB in high-QPS API servers to serve 95% hot reads in < 50 us.
  • Database & Storage Block Caches: RocksDB/CockroachDB Pebble use segmented/clock-pro caches to resist large range-scan pollution.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does Caffeine use a lossy read ring buffer and W-TinyLFU instead of a global-lock LRU?

Recommended Learning Flow