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

Weights

When entries are not equal, and what one entry really costs

The point: a limit on entries protects memory only if entries are alike. Otherwise give each a weight, and accept that one newcomer may push out several.

The change is small

Python
from collections import OrderedDictclass WeightedLru:    def __init__(self, limit, weigh):        self._limit, self._weigh = limit, weigh        self._data, self._total = OrderedDict(), 0     # key -> (value, weight)    def get(self, key, default=None):        if key not in self._data:            return default        self._data.move_to_end(key)        return self._data[key][0]    def put(self, key, value):        weight = self._weigh(value)                    # weigh once, remember the answer        if key in self._data:            self._total -= self._data.pop(key)[1]      # an update may change the weight        if weight > self._limit:            return []                                  # would empty the cache and still not fit        evicted = []        while self._total + weight > self._limit:      # one newcomer may cost many            old, (_, w) = self._data.popitem(last=False)            self._total -= w            evicted.append(old)        self._data[key] = (value, weight)        self._total += weight        return evictedc = WeightedLru(10, len)c.put("a", "xxx")c.put("b", "xxx")c.put("c", "xxx")print(c.put("d", "xxxxxx"), c._total)                  # ['a', 'b'] 9print(c.put("e", "x" * 11), c._total)                  # [] 9
if became while. The weight is measured once and stored, because a value that changes later would make the total drift.
Edit and run it in your browser

Five decisions

QuestionChoiceOther choice
A value heavier than the whole cacheDo not store it. Remove an older value of that keyError, if the caller must know
An update makes it heavierTake the old weight off first, then make roomForget this and the total only grows
What is a weight?Bytes of the value plus a fixed partCost to load it again: a different policy
Is the order still O(1)?Each eviction is O(1), and each entry is evicted once, so O(1) amortisedOne call may be slow. Bound it by spreading the work over later calls
Weight 0Allowed, and never helps as a victimPinned entries. Too many, and nothing can be evicted

What does one entry cost?

Interviewers ask for a memory sum. Take a 64-bit Java process with compressed pointers and assume 16 bytes for an object header with padding. A node holds four references of 4 bytes, so about 32 bytes. The hash map entry holds a hash, a key, a value and a next, about 32 bytes as well, plus 4 to 8 bytes of table. Say 70 bytes before key and value.

A million entries

106×(70+60+200) B=330 MB10^6 \times (70 + 60 + 200)\ \text{B} = 330\ \text{MB}
Assumed: 60 bytes for a key, 200 for a value. The structure itself is a fifth. With values of 20 bytes it would be almost half, and then compact layouts begin to pay.

Make it smaller

  1. 1

    Put the links into the map entry

    Java's LinkedHashMap does this: its entry is a hash map entry with two more references. One object and not two.

  2. 2

    Arrays and not objects

    Keep prev and next in two int arrays, indexed by slot. Four bytes a link, no headers, friendly to processor caches. A free list gives out slots.

  3. 3

    One bit and not two links

    Clock keeps entries in a ring and one bit for each. No links at all.

Python
class SlotList:    """The same list with indices. Slot 0 is the sentinel of a ring: next[0] first, prev[0] last."""    def __init__(self, capacity):        self.prev = list(range(capacity + 1))        self.next = list(range(capacity + 1))     # every slot points at itself    def unlink(self, i):        p, n = self.prev[i], self.next[i]        self.next[p], self.prev[n] = n, p    def push_front(self, i):        first = self.next[0]        self.prev[i], self.next[i] = 0, first        self.prev[first], self.next[0] = i, i    def last(self):        return self.prev[0]                        # 0 means emptys = SlotList(3)for slot in (1, 2, 3):    s.push_front(slot)s.unlink(1)s.push_front(1)print(s.next[0], s.next[1], s.next[3], "last", s.last())   # 1 3 2 last 2
One sentinel is enough if the list is a ring. Python's own lru_cache, in its Python source, uses a ring with one root in the same way.
Edit and run it in your browser

Memory that the collector sees

A large cache of small objects is a lot of work for a garbage collector, because long-lived objects are walked again and again. Soft references look like a way out, but then the collector decides what leaves and when, under pressure, all at once. Prefer a clear limit. For very large caches use another process, see the last pages.

The limit is 2 GB and values are between 100 bytes and 5 MB.

BreaksLimit the number of entries
How
100,000 entries.
Limit
10 MB or 500 GB, depending on luck.
Choose when
Equal entries only.
WorksWeights
How
Count bytes, evict until it fits.
Limit
One large value pushes out thousands of small ones.
Choose when
The default.
StrongWeights, and a limit for a single value
How
Values above 1 MB go to another cache or are not cached.
Limit
A second number to choose.
Choose when
Sizes differ by orders of magnitude.