Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Other policies
LFU in O(1), segments, and when LRU loses
The point: LRU remembers when, LFU remembers how often. Each fails where the other is good. Real caches mix them and judge the newcomer before they let it in.
LFU that stays O(1)
A heap of counters gives O(log n). Better: one ordered bucket for each count, and a number that remembers the smallest count. A use moves a key one bucket up. Only an insert can make the smallest count jump, and then it is 1.
from collections import OrderedDict, defaultdictclass LfuCache: """Least frequently used. Among equals, the least recently used goes. O(1).""" def __init__(self, capacity): self._capacity = capacity self._value, self._uses = {}, {} self._bucket = defaultdict(OrderedDict) # uses -> keys in order of recency self._least = 0 def _touch(self, key): uses = self._uses[key] del self._bucket[uses][key] if not self._bucket[uses]: del self._bucket[uses] if self._least == uses: self._least = uses + 1 # this key has just moved there self._uses[key] = uses + 1 self._bucket[uses + 1][key] = None def get(self, key, default=None): if key not in self._value: return default self._touch(key) return self._value[key] def put(self, key, value): if key in self._value: self._value[key] = value self._touch(key) return if len(self._value) == self._capacity: victim, _ = self._bucket[self._least].popitem(last=False) if not self._bucket[self._least]: del self._bucket[self._least] del self._value[victim], self._uses[victim] self._value[key], self._uses[key] = value, 1 self._bucket[1][key] = None self._least = 1 # the newcomer is always the weakestc = LfuCache(2)c.put("a", 1)c.put("b", 2)c.get("a")c.put("c", 3) # b has one use, a has twoprint(c.get("a"), c.get("b"), c.get("c")) # 1 None 3_least to uses + 1? Because the key that emptied the lowest bucket has just moved to the next one, so that bucket is not empty.LRU and LFU
| LRU | LFU | |
|---|---|---|
| Remembers | The last use | The number of uses |
| A scan of one-time keys | Flushes everything | Cannot push out the stars |
| Yesterday's star | Gone soon | Stays for a long time. Needs ageing: halve all counts now and then |
| A new key that will be popular | Gets a full chance | Has count 1 and is the first to go |
| Memory | Two links | Two links and a count |
Segments: a trial before you may stay
from collections import OrderedDictclass SegmentedLru: """New entries are on trial. A second use moves them to the protected part.""" def __init__(self, trial, protected): self._trial_room, self._safe_room = trial, protected self._trial, self._safe = OrderedDict(), OrderedDict() def get(self, key, default=None): if key in self._safe: self._safe.move_to_end(key) return self._safe[key] if key not in self._trial: return default value = self._trial.pop(key) # second use: promoted if len(self._safe) == self._safe_room: old_key, old_value = self._safe.popitem(last=False) self._trial[old_key] = old_value # demoted, not thrown away self._safe[key] = value return value def put(self, key, value): if key in self._safe or key in self._trial: self.get(key) self._safe[key] = value return if len(self._trial) == self._trial_room: self._trial.popitem(last=False) self._trial[key] = valuecache = SegmentedLru(2, 2)for key in ("hot1", "hot2"): cache.put(key, 1) cache.get(key)for row in range(1000): # the report that reads all rows once cache.put(f"row{row}", 1)print([cache.get(k) for k in ("hot1", "hot2")]) # [1, 1]: plain LRU of four would keep neitherThe family
| Policy | Idea | Extra cost |
|---|---|---|
| FIFO | Oldest insert leaves | None. A hit writes nothing |
| Random | Any one leaves | None. Good against loops |
| Clock | A ring and one bit: a used entry gets a second round | One bit, a hit writes it |
| Segmented LRU, 2Q | Trial and protected | A second list |
| LRU-K | The time of the K-th last use decides | K time stamps |
| ARC | Two lists and the memory of what they lost; their sizes adapt | Keys of evicted entries |
| W-TinyLFU | A small window, then the newcomer must be more frequent than the victim | A compact sketch of counts |
Who is let in?
Eviction asks who must leave. Admission asks whether the newcomer deserves the place. TinyLFU keeps an approximate count for keys, also for those not in the cache, and compares the newcomer with the victim. A one-time key loses and is never stored. That single question is what makes it resist scans.
Measure, do not argue
- 1
Record keys
A day of keys from production, without values.
- 2
Replay
The same trace through each policy and several sizes. A policy needs no real values, so this takes minutes.
- 3
Compare with the limit
Belady's rule, remove what is needed furthest in the future, can be computed on a recorded trace. It shows how much is left to win.
- 4
Decide
Two points of hit rate may be worth it or not. Multiply by the cost of a miss.
What a point is worth
A nightly report flushes your cache. What do you do?
BreaksMake the cache larger
- How
- Ten times the memory.
- Limit
- The report reads more than that.
- Choose when
- Never for scans.
WorksLet the report go around the cache
- How
- It peeks, and does not put.
- Limit
- Every scanning caller must know.
- Choose when
- Few, known scans. Databases do this with special buffers.
StrongA policy with a trial part
- How
- Segments, 2Q or TinyLFU.
- Limit
- More code, or a library.
- Choose when
- Scans are part of life.