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

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.

Python
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
Why is it safe to set _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.
Edit and run it in your browser

LRU and LFU

LRULFU
RemembersThe last useThe number of uses
A scan of one-time keysFlushes everythingCannot push out the stars
Yesterday's starGone soonStays for a long time. Needs ageing: halve all counts now and then
A new key that will be popularGets a full chanceHas count 1 and is the first to go
MemoryTwo linksTwo links and a count

Segments: a trial before you may stay

Python
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 neither
A key used once stays in the trial part and leaves with the next scan. A second use promotes it. The one that had to leave the protected part goes back to trial, not out.
Edit and run it in your browser

The family

PolicyIdeaExtra cost
FIFOOldest insert leavesNone. A hit writes nothing
RandomAny one leavesNone. Good against loops
ClockA ring and one bit: a used entry gets a second roundOne bit, a hit writes it
Segmented LRU, 2QTrial and protectedA second list
LRU-KThe time of the K-th last use decidesK time stamps
ARCTwo lists and the memory of what they lost; their sizes adaptKeys of evicted entries
W-TinyLFUA small window, then the newcomer must be more frequent than the victimA 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. 1

    Record keys

    A day of keys from production, without values.

  2. 2

    Replay

    The same trace through each policy and several sizes. A policy needs no real values, so this takes minutes.

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

T=h⋅thit+(1−h)⋅tmissT = h \cdot t_{hit} + (1 - h) \cdot t_{miss}
With 0.1 ms for a hit and 20 ms for a miss (assumed): 90 percent gives 2.09 ms, 92 percent gives 1.69 ms. Two points save about a fifth, because misses dominate.

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.