AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

LRU cache under 90 seconds

1:22Reel coming soon

Design an LRU cache in one picture
Design an LRU cache in one picture

Theory

Read or listen first. About 3 min.

What it is

A cache keeps copies of things that are slow to get. It has little room, so it must choose what to keep. Least recently used, LRU, is one such choice: when the room is full, throw out the entry that nobody has touched for the longest time.

In an object design round the task is a class with two methods, get and put, and a fixed capacity. Both must take O(1) time on average, however many entries there are.

No single textbook structure can do that. A hash map finds but has no order. A linked list has an order but cannot find. The answer is to let one object live in both: the map leads to the node, and the node knows its neighbours.

Why it exists

The rule works because of temporal locality: what was used a moment ago is likely to be used again soon. This is a habit of programs and people, not a law. A report that reads every row once breaks it, and this page shows what to do then.

Interviewers like the problem because it is small and has sharp edges. Four pointer writes must be in the right order, two structures must change together, and a method called get secretly writes. You see all three again in real systems.

It also grows well. Threads, expiry, weights, loading, counting and other policies each ask for one change. Whether that change is small tells the interviewer whether the first design was good.

A short history

  1. 1966

    Laszlo Belady of IBM publishes a study of replacement algorithms for virtual storage. The MIN rule, remove what is needed furthest in the future, is the limit that no real policy can beat.

  2. 1993

    LRU-K, by Elizabeth O'Neil, Patrick O'Neil and Gerhard Weikum, looks at the K-th last use instead of the last one. Databases needed an answer to scans.

  3. 1994

    2Q, by Theodore Johnson and Dennis Shasha, gets a similar effect with queues and constant time.

  4. 2002

    Java 1.4 ships LinkedHashMap with an access order and a hook called removeEldestEntry: an LRU cache in a few lines.

  5. 2011

    Python 3.2 adds functools.lru_cache. Its Python source is a dictionary and a circular doubly linked list.

  6. 2015

    The TinyLFU paper by Gil Einziger, Roy Friedman and Ben Manes asks a new question: should the newcomer be let in at all?

Words to know

Hit and miss
The key is in the cache, or it is not.
Hit rate
Hits divided by all lookups. Hits divided by hits plus misses.
Eviction
Removing an entry because the room is needed. Expiry is different: the entry is too old.
MRU and LRU
Most recently used, the front of our list, and least recently used, the back.
Sentinel
A node without data that always exists, so that every real node has two neighbours.
Touch
Move a node to the front because it was used.
Scan
A walk over many keys, each used once. It can flush a cache.
Working set
The keys that are really needed in a stretch of time.
Time to live
How long an entry may be given out after it was written.
Single flight
Many callers miss the same key, one of them loads it, all get that result.
Shard or segment
An independent part of the cache with its own lock and its own order.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

A key is asked for. The map finds the node. The list moves it to the front.

Understand it

Story

The coat rail by the door

Before any class, look at a rail with room for three coats. It shows the whole algorithm, and also why two structures are needed and not one.

Three coats, and a fourth one arrives
frontbackredbluegreen

The board without the rail does not know who is last. The rail without the board cannot find anybody.

What an interviewer looks for here

  • Two structures

    You say why one is not enough before you say which two.

  • Small operations

    unlink and pushFront are written once. Everything else is made of them.

  • The invariant

    Map and list hold the same nodes. You check it at each line.

  • The hidden write

    get changes the order, so a read lock is not enough.

  • A limit

    You know when LRU is the wrong policy, and what you would measure.

  • Restraint

    No factory, no listener, no builder until somebody asks for one.

Step 1

Why one structure is not enough

Write the three things the cache must do in a row: find a key, move an entry to the front, remove the last entry. Then try each structure you know.

Three jobs, six candidates

StructureFind a keyMove to frontRemove the oldest
Array with time stampsO(n)O(1), write a stampO(n), find the smallest
Sorted array or list by useO(n)O(n) to shiftO(1)
Hash map with time stampsO(1)O(1)O(n)
Map and a heap of stampsO(1)O(log n)O(log n)
Map and a singly linked listO(1)O(n), who is before me?O(n)
Map and a doubly linked listO(1)O(1)O(1)
Hash map times are averages. With an adversary or a bad hash they grow, which is worth one sentence aloud.
Python
class Entry:    def __init__(self, key, value, used):        self.key, self.value, self.used = key, value, usedclass SlowCache:    def __init__(self, capacity):        self.capacity = capacity        self.entries = []        self.clock = 0        self.looks = 0                  # how many entries we had to look at    def get(self, key):        self.clock += 1        for entry in self.entries:      # a walk to find            self.looks += 1            if entry.key == key:                entry.used = self.clock                return entry.value        return None    def put(self, key, value):        self.clock += 1        for entry in self.entries:      # a walk to know whether it is new            self.looks += 1            if entry.key == key:                entry.value, entry.used = value, self.clock                return        if len(self.entries) == self.capacity:            self.looks += len(self.entries)         # and one more to find the oldest            self.entries.remove(min(self.entries, key=lambda e: e.used))        self.entries.append(Entry(key, value, self.clock))cache = SlowCache(1000)for key in range(1000):    cache.put(key, key)cache.looks = 0cache.put("new", 1)print(cache.looks, "looks for one put")       # 2000 looks for one put
The first idea of most people. It works, and it looks at 2,000 entries to store one.
Edit and run it in your browser

From the question to the structure

Avoid

The design most people overbuild

The opposite mistake is as common. Every word from a patterns book becomes a class, and the entry that should be evicted is still found by a walk.

The design to avoid: much architecture around a slow loop

CacheManager- instance: CacheManager+ getInstance()+ get(key)+ put(key, value)

1/4A global manager

One cache for the whole program, reached from everywhere. Two tests now share their entries.

usesdepends onimplementsowns (dies together)

A pattern cannot repair a missing data structure.

Step 2

The design to reach

The design to reach: a map that finds, a list that orders, a node in both

CallerLruCache- capacity: int- nodes: Map<K, Node>- order: RecencyList+ get(key): V+ peek(key): V+ put(key, value): Entry+ remove(key): bool- evict(): Entry

1/4Two verbs

Start with what the caller sees: get and put. Nothing else is needed to use a cache. peek and remove come from the layers you will put around it later.

usesowns (dies together)has (lives on)

What each class owns, and what it must not know

ClassOwnsDoes not know
LruCacheCapacity, the map, the promise that map and list agreePointers
RecencyListBoth sentinels and every pointer writeKeys, capacity, why a node moves
NodeOne pair and two neighboursAnything else. It has no methods

Step 3

Sentinels: no special cases

A list without sentinels has four shapes: empty, the first node, the last node, the only node. Each needs its own branch, and the branches are where the bugs are. Two nodes without data, head and tail, stand at the ends for ever. Now every real node has a neighbour on both sides, and there is one shape.

Python
# without sentinels                     # with sentinelsdef unlink(self, node):                 def unlink(self, node):    if node.prev is None:                   node.prev.next = node.next        self.first = node.next              node.next.prev = node.prev    else:        node.prev.next = node.next    if node.next is None:        self.last = node.prev    else:        node.next.prev = node.prev
Ten lines with four paths, or two lines with one. The right side is also the one you can write under pressure.

The list is never empty of nodes

head.next is the most recent, tail.prev the least recent. Solid arrows are links of the list, dotted ones are references from the map.

Three operations, and the order of their writes

  1. 1

    Unlink

    node.prev.next = node.next, then node.next.prev = node.prev. The neighbours shake hands over the node. Either order is right, as long as the node still holds both neighbours.

  2. 2

    Push to the front

    First fill in the new node: prev is the head, next is the one that is first now. Then head.next.prev = node, and last head.next = node. The last two lines may not change places.

  3. 3

    Touch

    Unlink, then push. A node that is first already goes through the same six writes, and nothing breaks.

Step 4

The life of an entry

One entry

One put

Known comes before full. The other order evicts an entry when you only wanted to change one.

A full cache meets a new key

Step 5

A read that writes

Look at get again. It returns a value, so it sounds harmless. But it unlinks a node and links it somewhere else. Two threads that only read can therefore destroy the list. That single fact decides the whole discussion about threads.

How do you make it safe for many threads?

BreaksA read and write lock, with get under the read lock
How
Many readers hold the lock together, writers alone.
Limit
Readers move nodes. Two of them write the same pointers at the same time.
Choose when
Never for a strict LRU.
WorksOne lock around get and put
How
The lookup and the move are one step. Easy to read and to prove.
Limit
One operation at a time. Fine until a measurement says otherwise.
Choose when
The default. Say it first.
WorksShards
How
The hash of the key chooses one of N small caches with their own locks.
Limit
N orders instead of one. A crowded shard evicts while another has room.
Choose when
The lock is measurably busy and the cache is large.
StrongReads leave notes, one thread applies them
How
get reads a concurrent map and appends to a buffer. Whoever gets the lock replays the buffer.
Limit
The order is a little late, and notes may be lost under load.
Choose when
Very many reads. This is how Caffeine works.

Step 6

When LRU is the wrong rule

Pattern of useWhat LRU doesBetter
The same keys again and againKeeps themLRU is right
A scan over everything onceThrows out all hot keysSegments, 2Q, or do not cache the scan
A loop a bit longer than the cacheMisses every single timeRandom or most recently used
A few stars, many one-time keysStars survive only if they come often enoughLFU with ageing, or TinyLFU
All keys equally likelyAs good as randomA larger cache, or none
Policies compared for a whole service are on cache eviction. Here we care about the objects.

The loop that LRU cannot serve

keys=C+1;⇒;hits=0\text{keys} = C + 1 ;\Rightarrow; \text{hits} = 0
Capacity 3, keys 1 2 3 4 1 2 3 4. Each key is evicted exactly one step before it is needed again.

Do

  • Use a head and a tail sentinel.
  • Store the key in the node.
  • Move a node on get and on put.
  • Evict before you insert, so the limit holds at every moment.
  • Ask whether threads matter before you write a lock.
  • Show the pointers, then mention the library class.

Do not

  • Use a singly linked list: removing from the middle needs the node before it.
  • Forget the touch in get.
  • Leave the key out of the node: eviction becomes a search in the map.
  • Put a read lock around get.
  • Hide behind OrderedDict or LinkedHashMap without knowing what is inside.
  • Evict on an update.

Summary

The whole topic in one minute.

An LRU cache is a hash map and a doubly linked list over the same nodes. The map answers *where*, the list answers *who is last*. Every use moves a node to the front, and a full cache gives up the node at the back. Both calls are O(1).

The invariant is one sentence: the map and the list hold the same nodes, at most as many as the capacity. One class changes both, so the sentence can be checked after each call.

Everything after that is a layer or a trade. A lock is enough for most. Shards and buffered reads buy throughput for exactness. Deadlines, weights, loaders and counters wrap around the core and leave it alone.

  • The map finds in O(1), the doubly linked list moves and removes in O(1). Neither can do both.
  • Two sentinels remove every special case from the list.
  • Each node holds its key, so an eviction can clean the map.
  • get changes the order. It is a write.
  • Known before full, evict before insert, unlink before delete.
  • One lock first. Shards and buffered reads trade exactness for throughput.
  • LRU fails on scans and on loops longer than the cache.

Sources