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

Buffered reads

One order, and reads that do not wait

The point: a read writes a small note that it happened. Later one thread, which holds the lock anyway, replays the notes. The order is a little late, and nobody waits for it.

A log for the order

It is the idea of a write-ahead log, used for recency. The hash table is always right. The order catches up. If notes come too fast, some are dropped: a key that is read so often will be noted again.

Reads and the one who drains

Python
from collections import OrderedDict, dequefrom threading import Lockclass BufferedLru:    """Reads only note that they happened. Somebody with the lock applies the notes."""    def __init__(self, capacity, buffer=64):        self._capacity, self._data = capacity, OrderedDict()        self._lock = Lock()        self._notes = deque(maxlen=buffer)     # full: the oldest note is lost, and that is fine    def get(self, key, default=None):        value = self._data.get(key, default)   # CPython: one atomic dictionary read        if value is not default:            self._notes.append(key)            if len(self._notes) == self._notes.maxlen and self._lock.acquire(blocking=False):                try:                    self._drain()                finally:                    self._lock.release()        return value    def put(self, key, value):        with self._lock:            self._drain()                      # before choosing a victim, hear the news            if key not in self._data and len(self._data) == self._capacity:                self._data.popitem(last=False)            self._data[key] = value            self._data.move_to_end(key)    def _drain(self):        while self._notes:            key = self._notes.popleft()            if key in self._data:              # it may have been evicted since                self._data.move_to_end(key)cache = BufferedLru(3)for key in "abc":    cache.put(key, key.upper())print(cache.get("a"), list(cache._data))       # A ['a', 'b', 'c']: not moved yetcache.put("d", "D")print(list(cache._data))                       # ['c', 'a', 'd']: the note was applied first
The sketch leans on the atomic dictionary reads of the usual CPython. In Java the same shape needs a ConcurrentHashMap and several ring buffers, one for a group of threads.
Edit and run it in your browser

Four rules that make it work

RuleWhy
The buffer has a fixed size, and losing a note is allowedOtherwise readers wait again, or memory grows
Draining uses tryLockA reader never waits. If the lock is taken, somebody is draining already
Writers drain before they evictThe victim is chosen with fresh news
A note is checked when replayedThe key may be gone. Same ghost as before

Writes may not be lost

A lost read note costs a little quality. A lost write note would leave an entry in the table that no policy knows, so it could never be evicted: a leak. Caffeine's design page describes a second buffer for writes that is not allowed to drop anything. When it is full, the writer must help.

When it pays

  • Very many reads on many cores.
  • One global policy matters: small caches, or a clever policy.
  • A library that thousands will use.

When it does not

  • An interview answer that should be finished today.
  • Few threads: one lock is faster.
  • Strict LRU is promised, for example in a test.

Failure walk

What happensResultAnswer
The thread that drains is paused by the systemNotes are dropped meanwhile, writers wait at the lockBounded work for each drain, so it is short
Nobody writes for an hourExpired entries stay in memoryA timer that drains and sweeps
A burst of writesThe write buffer fillsWriters drain themselves: back pressure
A test expects the exact orderIt fails now and thenOffer a method that applies all notes, for tests

Would you build this in a round?

BreaksStart with it
How
Ring buffers from the first minute.
Limit
The core never gets finished.
Choose when
Never.
WorksOne lock, and name the idea
How
"Reads could leave notes."
Limit
No detail.
Choose when
Most rounds.
StrongOne lock, then sketch the notes with their two rules
How
Read notes may be lost, write notes may not.
Limit
Takes five minutes.
Choose when
The interviewer asks how libraries do it.