Design an LRU cache
medium 85 minDesign 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
1/4The core
One interface with four methods, one class that keeps the promise of LRU.
implementsowns (dies together)
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}Which counter?
| Kind | Under many writers | Reading | Use it for |
|---|---|---|---|
| A plain field | Loses counts | Cheap | Under the lock of the cache: then it is exact and free |
| AtomicLong | Correct, writers retry on one memory word | Exact | Few writers, or when you need the new value |
| LongAdder | Correct, writers spread over cells | A sum, not one moment | Statistics. 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.
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 500What to watch, and what it means
| Number | Looks wrong when | Probably |
|---|---|---|
| Hit rate | Falls suddenly | A deployment, a scan, a changed key |
| Hit rate | Near 1 with few entries | The cache is larger than needed |
| Evictions | Many, with a low hit rate | Too small, or the wrong policy |
| Evictions | None, with a low hit rate | Keys never repeat. Caching does not help here |
| Expirations | Most removals are expiries | The time to live is shorter than the data needs |
| Load time p99 | Rises | The store is in trouble, and the cache hides it from the mean |
| Size | Below capacity for ever | Capacity 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.