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

Beyond one process

Sampling, rings, and what stays the same

The point: when the cache moves out of the process, the linked list usually goes first and the hard questions become who owns a key and who hears about a change. Keep this short in an object design round and say where it belongs.

No list: sample at eviction

Redis keeps no exact LRU list, because it would cost more memory. It stores a small stamp with each key. When room is needed, it looks at a few random keys, five by default (maxmemory-samples), and evicts the one that has been idle longest. Since version 3.0 it also keeps a pool of good candidates.

Python
import randomclass SampledLru:    """No list at all: a time stamp on each entry, and a small random sample at eviction."""    def __init__(self, capacity, samples=5, rng=random):        self._capacity, self._samples, self._rng = capacity, samples, rng        self._data, self._keys, self._place = {}, [], {}   # key -> [value, used], and an array to sample from        self._clock = 0    def get(self, key):        self._clock += 1        entry = self._data.get(key)        if entry is None:            return None        entry[1] = self._clock                             # one write, no neighbours        return entry[0]    def put(self, key, value):        self._clock += 1        if key not in self._data:            if len(self._data) == self._capacity:                self._evict()            self._place[key] = len(self._keys)            self._keys.append(key)        self._data[key] = [value, self._clock]    def _evict(self):        picks = self._rng.sample(self._keys, min(self._samples, len(self._keys)))        victim = min(picks, key=lambda k: self._data[k][1])        hole, last = self._place.pop(victim), self._keys.pop()        if last != victim:                                 # fill the hole with the last one            self._keys[hole], self._place[last] = last, hole        del self._data[victim]def age_of_victims(samples):    rng = random.Random(7)    cache = SampledLru(1000, samples, rng)    for key in range(1000):        cache.put(key, key)    for key in range(1000, 1400):        cache.put(key, key)    return sum(k >= 400 for k in range(1000) if k not in cache._data)   # a true LRU drops 0..399print({n: age_of_victims(n) for n in (1, 5, 10)}, "wrong victims of 400")
The array and the place table make a random sample O(1). With one sample the policy is random: about half of the victims are wrong here. Five samples are much better, ten better still.
Edit and run it in your browser
Exact listSampling
A hit writesSix pointers of three nodesOne stamp in the entry itself
Memory for orderTwo pointersOne stamp
VictimThe oldestProbably an old one
Another policyAnother structureAnother comparison: idle time, count, nearest expiry

Who owns a key?

With several cache servers, each key has a home. hash % n moves almost all keys when n changes. A ring of hashes moves about K/n of K keys when one of n servers joins or leaves. How a ring is built is on consistent hashing, and the whole service is on distributed cache.

Python
from bisect import bisectfrom hashlib import sha256def spot(text):    return int.from_bytes(sha256(text.encode()).digest()[:8], "big")class RemoteCache:    """The same two verbs as before. What is behind them has changed."""    def __init__(self, clients, points=100):        self._ring = sorted((spot(f"{name}#{i}"), name) for name in clients for i in range(points))        self._clients = clients    def _home(self, key):        i = bisect(self._ring, (spot(key), "")) % len(self._ring)        return self._clients[self._ring[i][1]]    def get(self, key):        try:            return self._home(key).get(key)        except ConnectionError:            return None                    # a broken cache is a miss, not an error    def put(self, key, value):        try:            self._home(key)[key] = value        except ConnectionError:            passthree = RemoteCache({n: {} for n in ("a", "b", "c")})four = RemoteCache({n: {} for n in ("a", "b", "c", "d")})names = lambda cache, key: next(n for n, c in cache._clients.items() if c is cache._home(key))moved = sum(names(three, f"k{i}") != names(four, f"k{i}") for i in range(10_000))print(round(moved / 10_000, 2))            # about 0.25: one quarter of the keys move to d
Python's own hash of text differs from process to process, so two clients would disagree about the home of a key. Use a fixed hash.
Edit and run it in your browser

Three challenges, one sentence each

ChallengeWhat goes wrongFirst answer
InvalidationThe value changed, two processes still hold the old oneShort time to live, and a message with the key. Messages can be lost, so never only the message
Copies on other nodesA copy written later and without order overwrites a newer valueA version with each value, the higher one wins
A node is lostIts keys miss at once and hit the storeSingle flight, a limit on loads, slow warm-up
A hot keyOne node gets all callsA small local cache in front, for a second or two

Two levels

A near cache in front of a shared one

The near cache is exactly the class of this page, with a short time to live.

The interviewer says: make it distributed.

BreaksShare one linked list between machines
How
Every hit writes to a remote list.
Limit
A network call for each pointer.
Choose when
Never.
WorksOne LRU on each server, keys by a ring
How
Each server evicts on its own.
Limit
No global order, as with shards.
Choose when
The normal answer.
StrongThe same, plus a near cache and a story for invalidation
How
Time to live, versions, single flight.
Limit
Say what may be stale and for how long.
Choose when
Reads are many, and a little staleness is fine.