AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Watch lesson4:49

Metrics

Counting without slowing down

The point: without numbers a cache is a belief. Count hits, misses, evictions and the time of loads. Keep the counters out of the way of the calls they count.

A layer that counts

Layers around one small core

«interface»Cache+ get(key): V+ peek(key): V+ put(key, value)+ remove(key): boolLruCache- nodes- order

1/4The core

One interface with four methods, one class that keeps the promise of LRU.

implementsowns (dies together)

The Decorator pattern. New features are new classes, and the core never changes.
Java
final class CountingCache<K, V> implements Cache<K, V> {    private final Cache<K, V> inner;    private final LongAdder hits = new LongAdder();      // many writers, rare readers    private final LongAdder misses = new LongAdder();    CountingCache(Cache<K, V> inner) { this.inner = inner; }    public V get(K key) {        V value = inner.get(key);        (value == null ? misses : hits).increment();        return value;    }    record Snapshot(long hits, long misses) {        double hitRate() {            long total = hits + misses;                  // not a third counter: it would disagree            return total == 0 ? 0.0 : (double) hits / total;        }    }    Snapshot snapshot() { return new Snapshot(hits.sum(), misses.sum()); }    // peek, put and remove pass on}
The total is computed from the two counters. A separate counter of all gets, raised at another moment, gives a rate above 100 percent now and then.

Which counter?

KindUnder many writersReadingUse it for
A plain fieldLoses countsCheapUnder the lock of the cache: then it is exact and free
AtomicLongCorrect, writers retry on one memory wordExactFew writers, or when you need the new value
LongAdderCorrect, writers spread over cellsA sum, not one momentStatistics. Its documentation recommends it for that

Atomic counters make the counters safe, not the cache. A class with three atomic fields and an unguarded list is still broken.

Averages lie

Adding up nanoseconds gives a mean, and a mean hides the slow ones. Keep a histogram: a few buckets, one count each. Then p95 is a walk over eight numbers.

Python
from bisect import bisect_leftfrom collections import OrderedDictclass Stats:    BOUNDS = [1, 2, 5, 10, 50, 100, 500]        # milliseconds    def __init__(self):        self.hits = self.misses = self.evictions = 0        self.load_ms = [0] * (len(self.BOUNDS) + 1)    def loaded(self, ms):        self.load_ms[bisect_left(self.BOUNDS, ms)] += 1    def hit_rate(self):        total = self.hits + self.misses        return self.hits / total if total else 0.0    def percentile(self, p):        """The upper bound of the bucket that holds the p-th load."""        need, seen = p * sum(self.load_ms), 0        for bound, count in zip([*self.BOUNDS, float("inf")], self.load_ms):            seen += count            if count and seen >= need:                return bound        return Nones = Stats()s.hits, s.misses = 900, 100for ms in [1] * 90 + [400] * 10:                # ten slow loads among a hundred    s.loaded(ms)mean = (90 * 1 + 10 * 400) / 100print(s.hit_rate(), "mean", mean, "p50", s.percentile(.5), "p95", s.percentile(.95))# 0.9 mean 40.9 p50 1 p95 500
Ninety loads of 1 ms and ten of 400 ms. The mean of 40.9 ms describes no call at all. p95 says what the slowest see.
Edit and run it in your browser

What to watch, and what it means

NumberLooks wrong whenProbably
Hit rateFalls suddenlyA deployment, a scan, a changed key
Hit rateNear 1 with few entriesThe cache is larger than needed
EvictionsMany, with a low hit rateToo small, or the wrong policy
EvictionsNone, with a low hit rateKeys never repeat. Caching does not help here
ExpirationsMost removals are expiriesThe time to live is shorter than the data needs
Load time p99RisesThe store is in trouble, and the cache hides it from the mean
SizeBelow capacity for everCapacity is not your limit

How do you measure the time of a get?

BreaksTwo clock reads around every get
How
nanoTime before and after.
Limit
The clock can cost as much as the hit.
Choose when
Not on hits.
WorksMeasure loads only
How
A load takes milliseconds, so the clock is free.
Limit
Says nothing about lock waits.
Choose when
The default.
StrongLoads always, hits as a sample
How
Every 1,000th hit is timed into a histogram.
Limit
Rare spikes may be missed.
Choose when
The lock is under suspicion.