Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Video lesson · Chapter 1 of 6
Make a prediction
LRU cache under 90 seconds
1:22Reel coming soon

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
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.
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.
1994
2Q, by Theodore Johnson and Dennis Shasha, gets a similar effect with queues and constant time.
2002
Java 1.4 ships LinkedHashMap with an access order and a hook called removeEldestEntry: an LRU cache in a few lines.
2011
Python 3.2 adds
functools.lru_cache. Its Python source is a dictionary and a circular doubly linked list.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.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
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.
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
unlinkandpushFrontare 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
getchanges 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
| Structure | Find a key | Move to front | Remove the oldest |
|---|---|---|---|
| Array with time stamps | O(n) | O(1), write a stamp | O(n), find the smallest |
| Sorted array or list by use | O(n) | O(n) to shift | O(1) |
| Hash map with time stamps | O(1) | O(1) | O(n) |
| Map and a heap of stamps | O(1) | O(log n) | O(log n) |
| Map and a singly linked list | O(1) | O(n), who is before me? | O(n) |
| Map and a doubly linked list | O(1) | O(1) | O(1) |
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 putFrom 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
1/4A global manager
One cache for the whole program, reached from everywhere. Two tests now share their entries.
usesdepends onimplementsowns (dies together)
Step 2
The design to reach
The design to reach: a map that finds, a list that orders, a node in both
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
| Class | Owns | Does not know |
|---|---|---|
LruCache | Capacity, the map, the promise that map and list agree | Pointers |
RecencyList | Both sentinels and every pointer write | Keys, capacity, why a node moves |
Node | One pair and two neighbours | Anything 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.
# 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.prevThe list is never empty of nodes
Three operations, and the order of their writes
- 1
Unlink
node.prev.next = node.next, thennode.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
Push to the front
First fill in the new node:
previs the head,nextis the one that is first now. Thenhead.next.prev = node, and lasthead.next = node. The last two lines may not change places. - 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
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
getreads 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 use | What LRU does | Better |
|---|---|---|
| The same keys again and again | Keeps them | LRU is right |
| A scan over everything once | Throws out all hot keys | Segments, 2Q, or do not cache the scan |
| A loop a bit longer than the cache | Misses every single time | Random or most recently used |
| A few stars, many one-time keys | Stars survive only if they come often enough | LFU with ageing, or TinyLFU |
| All keys equally likely | As good as random | A larger cache, or none |
The loop that LRU cannot serve
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.
getchanges 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
- Python documentation: functools.lru_cache
- Python documentation: collections.OrderedDict
- Java SE 21: LinkedHashMap
- Java SE 21: ReentrantReadWriteLock
- Java SE 21: LongAdder
- Caffeine: design
- Redis documentation: key eviction
- memcached blog: replacing the cache replacement algorithm
- Einziger, Friedman, Manes: TinyLFU
- Wikipedia: Cache replacement policies