SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

LRU Cache Design

Build an LRU cache with a hash map and a doubly linked list, so get and put both take O(1).

โฑ 12 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The classic interview question: build an LRU cache where both get and put take O(1) time. The answer is two structures working together: a hash map to find an entry instantly, and a doubly linked list to keep entries in order of use.

  • Hash map: key โ†’ pointer to the list node. Finds any entry without walking the list.
  • Doubly linked list: most recently used at the front, least recently used at the back. A node can be unlinked and moved in O(1).
  • On access: move the node to the front. When full: remove the node at the back, and its map entry.

02Concept: What is it?

The page "Cache Eviction Policies" explains what LRU means: when the cache is full, throw out the item that was used longest ago. This page is about how to build it so that it is fast, which is what an interview or a real library has to solve.

Think about what each operation needs. Find a key: a hash map does this in O(1). Mark it as just used: it must move to the "newest" end. Find the oldest: it must be at the "oldest" end. A hash map alone has no order. A list alone cannot find a key quickly. Together they cover every step.

Why a doubly linked list? To remove a node from the middle in O(1), you must fix the node before it and the node after it. Each node therefore needs a prev and a next pointer. With a singly linked list you would have to walk to find the previous node, and that is O(n).

Two structures, one cache
๐Ÿ—‚๏ธHash mapA โ†’ node, B โ†’ node, C โ†’ node
โ†’โ†“points into
๐Ÿ”—HEAD โ‡„ C โ‡„ A โ‡„ B โ‡„ TAILfront = newest, back = oldest
The map points into the list. The list order is the recency order.
๐Ÿง Sentinel nodes
Add a fake HEAD and a fake TAIL node that never hold data. Then every real node always has a prev and a next, and you never need special cases for an empty list or for the first or last node.

03Real-Life Example

๐ŸตThe Pile of Books on a Desk
You keep your books in a stack. Whenever you use one, you pull it out and put it on top. When the desk is full and you need space, you remove the book at the very bottom, the one you have not touched for longest. The stack order is the linked list. The index card with the shelf position of every book is the hash map: it lets you grab a book without searching the stack.
Desk of books
LRU cache
Top of the pile
Front of the list (most recent)
Bottom of the pile
Back of the list (least recent, evicted first)
Index card for each book
Hash map entry
Pulling out a book and putting it on top
Unlink the node, insert at the front
Removing the bottom book
Evict the node before TAIL
Desk size
Cache capacity
Access C, then add D when full (capacity 3)
1๏ธโƒฃA โ‡„ B โ‡„ Cbefore
โ†’โ†“get C
2๏ธโƒฃC โ‡„ A โ‡„ BC moved to the front
โ†’โ†“put D
3๏ธโƒฃD โ‡„ C โ‡„ AB evicted
C moves to the front. D then pushes out the oldest, B.

04Why Do We Need It?

โšกO(1) everything
get, put and evict each take a fixed number of steps, however big the cache is.
๐Ÿง Keeps what is hot
Recently used items are likely to be used again, so hit rate is good.
๐Ÿ“Bounded memory
A fixed capacity means the cache never grows without limit.
๐ŸงฉSimple parts
Two basic structures, a few pointer changes, easy to test.
๐ŸŽฏA core interview skill
It tests hash maps, linked lists, pointers and edge cases in one problem.
๐Ÿ”งBasis of real caches
Most production caches are this idea plus locking, expiry and tuning.
A hash map gives speed of lookup, a linked list gives order, and together you get a cache that finds, updates and evicts in O(1).

05Where Do We Use It?

๐Ÿง In-process caches
Guava, Caffeine, Pythonโ€™s functools.lru_cache and Javaโ€™s LinkedHashMap all use this design or a close cousin.
๐Ÿ—„๏ธDatabase buffer pools
Keep recently used disk pages in memory. Evict the least recently used page.
๐ŸงฎOperating systems
Page replacement approximates LRU, often with the CLOCK algorithm.
๐ŸŒCDNs and web caches
Keep popular objects, drop the ones nobody asks for.
๐ŸงฐRedis and Memcached
Redis uses an approximated LRU. Memcached keeps LRU lists per slab class.
๐ŸŽ“Coding interviews
โ€œDesign an LRU cacheโ€ is one of the most common questions.

06Types / Parts / How It Works

The operations

OperationStepsCost
get(key)Look up the node in the map. If missing, return not found. Otherwise move it to the front and return the value.O(1)
put(key, value), key existsFind the node, change its value, move it to the front.O(1)
put(key, value), key is new, room leftMake a node, add it after HEAD, add it to the map.O(1)
put(key, value), key is new, cache fullRemove the node before TAIL, delete its key from the map, then insert the new node.O(1)

Why not something simpler?

IdeaFind a keyUpdate recencyEvict oldestVerdict
Hash map onlyO(1)No order keptO(n) to find oldestCannot evict fast
Array or queue onlyO(n)O(n) to moveO(1)Too slow to find and move
Singly linked list + mapO(1)O(n) to find the previous nodeO(n) for the tailโ€™s previousNeeds the prev pointer
Map + doubly linked listO(1)O(1)O(1)The standard answer
Map with a timestamp per keyO(1)O(1)O(n) scan to find the smallestSimple but slow to evict

Making it work with many threads

Options when many threads share the cache
One big lock
๐Ÿ”’Every get and put waitscorrect, but a bottleneck
Shard the cache
๐Ÿ—‚๏ธN small LRUspick one by hash(key) % N
Approximate LRU
๐ŸŽฒSample a few, evict the oldestRedis style, or CLOCK bit
One lock is simplest. Sharding spreads contention. Approximations avoid moving on every read.
Simple, slow under load Less contention, slightly uneven Cheapest per read, not exact
  • The read problem: a get changes the list (it moves the node), so even reads need a lock. Caffeine and similar caches record reads in a small buffer and replay them in batches.
  • CLOCK: one reference bit per entry and a sweeping hand. A read just sets the bit. The hand clears bits and evicts the first entry whose bit is already 0.
  • LFU: evicts the least frequently used instead. Needs counts, and frequency buckets to stay O(1). Better for steady hot items, worse when popularity changes.
VisualizerRun an LRU cache by handSet the capacity to 3. Press put on A, B and C, then get A, then put D. See which key is evicted, and how the list and map change at each step.
Pick a key, then get or put
A
B
C
D
E
F
Doubly linked list: most recently used on the left, least recently used on the right
HEADโ‡„TAIL
โ— front: most recently usedโ— next to be evicted (when full)
Hash map: key โ†’ pointer to its list node (so a lookup never walks the list)
(empty)
Entries
0 / 3
Hits
0
get found the key
Misses
0
get did not find it
Hit rate
0%
of get calls
Last evicted
none
0 so far
The cache is empty. Press put on a key to add it, or get to try reading it. The newest or last-used key always goes to the front.

Try this: capacity 3, put A, B, C, then get A, then put D. B is evicted, not A, because reading A made it recent. Every step is a hash lookup plus a few pointer changes, so it stays O(1) however big the cache is.

07How to Use It / Steps / Implementation

Building it step by step

  1. 1
    Define a node
    key, value, prev and next. The key is stored in the node so that eviction can delete it from the map.
  2. 2
    Create HEAD and TAIL sentinels
    Link HEAD โ‡„ TAIL. Real nodes always live between them.
  3. 3
    Write two helpers
    remove(node) joins its neighbours. addFront(node) inserts it right after HEAD.
  4. 4
    get
    If the key is not in the map, return not found. Otherwise remove(node), addFront(node), and return the value.
  5. 5
    put (existing key)
    Update the value, then remove and addFront.
  6. 6
    put (new key)
    If size equals capacity, take tail.prev, remove it and delete its key from the map. Then create the node, addFront, and add it to the map.
  7. 7
    Test the edges
    Capacity 1, repeated puts of one key, get of a missing key, and evicting right after a get.
LRU cache in TypeScript (O(1) get and put)
class N { constructor(public k = 0, public v = 0, public prev?: N, public next?: N) {} }

class LRU {
  private map = new Map<number, N>();
  private head = new N(); private tail = new N();
  constructor(private cap: number) { this.head.next = this.tail; this.tail.prev = this.head; }

  private remove(n: N) { n.prev!.next = n.next; n.next!.prev = n.prev; }
  private addFront(n: N) {
    n.next = this.head.next; n.prev = this.head;
    this.head.next!.prev = n; this.head.next = n;
  }
  get(k: number): number {
    const n = this.map.get(k); if (!n) return -1;
    this.remove(n); this.addFront(n); return n.v;
  }
  put(k: number, v: number) {
    let n = this.map.get(k);
    if (n) { n.v = v; this.remove(n); this.addFront(n); return; }
    if (this.map.size === this.cap) {
      const old = this.tail.prev!; this.remove(old); this.map.delete(old.k);
    }
    n = new N(k, v); this.map.set(k, n); this.addFront(n);
  }
}
๐Ÿ’กA JavaScript shortcut
A JS Map remembers insertion order. To refresh a key: delete it and set it again. To evict: delete map.keys().next().value. It is fine for quick code, but interviewers usually want the explicit list.

08Key Terms to Know

TermMeaning in easy words
LRULeast Recently Used: evict the entry that was used longest ago
Hash mapA structure that finds a value by key in O(1) on average
Doubly linked listNodes with both prev and next pointers, so one node can be removed in O(1)
Sentinel (dummy) nodeA fake HEAD or TAIL node that removes edge cases
CapacityThe maximum number of entries the cache holds
Hit / missThe key was found in the cache / it was not
EvictionRemoving an entry to make room
Move to frontMarking an entry as most recently used
CLOCKAn approximate LRU using one bit per entry and a sweeping hand
Approximate LRUSampling a few entries and evicting the oldest of those
LFULeast Frequently Used: evict the entry with the fewest accesses
Lock stripingSplitting a big lock into many small locks, one per shard

09Pros, Cons and Trade-offs

โœ… Pros
  • O(1) get, put and eviction
  • Good hit rate when recent use predicts future use
  • Small, simple code
  • Bounded memory
  • A well-known, well-tested design
โš ๏ธ Cons
  • Every read changes the list, which needs locking
  • Extra memory for two pointers per entry plus the map
  • A one-time scan can flush the whole cache
  • Ignores frequency (a popular item can be evicted by a scan)
  • Pointer chasing is not cache-friendly for the CPU

Trade-offs

ChoiceWe gainWe lose
Exact LRU, one lockCorrect and simpleContention under load
Sharded LRUParallel accessEviction is only per shard
Approximate LRU / CLOCKCheap readsSometimes evicts a better item
LRU vs LFULRU adapts quicklyLFU holds steady hot keys better
Segmented LRU / TinyLFUResists scansMore code and tuning
Store value in nodeOne lookupLarge values make nodes heavy

10Common Problems and Mistakes

Common mistakes

  1. A singly linked list. You cannot remove a middle node in O(1) without its previous node.
  2. Forgetting the key in the node. On eviction you hold the tail node but cannot say which map key to delete.
  3. Not moving on update. A put on an existing key must also refresh its recency.
  4. Evicting before checking for an existing key. Updating a full cache then throws out an innocent entry.
  5. Pointer order bugs. Set the new node's links before changing its neighbours'. Sentinels make this much safer.
  6. Reading without a lock. A get edits the list, so two threads can corrupt it.
  7. Capacity 0 or 1. Test them. An off-by-one here is common.

Things to watch

๐ŸงนScan pollution
A big one-time read pushes out everything hot. Use a segmented LRU or TinyLFU.
โฐExpiry
Real caches also need TTLs. Keep expiry separate from recency.
๐Ÿ“ฆSize by bytes
Capacity in entries is not capacity in memory when values differ in size.
๐ŸงตContention
Measure lock wait time before you add complexity.

11Real-World Examples

โ˜•Java LinkedHashMap
With accessOrder set to true and removeEldestEntry overridden, it is an LRU cache in a few lines.
๐ŸPython lru_cache
functools.lru_cache is a dictionary plus a circular doubly linked list, written in C.
๐Ÿš€Caffeine
Uses TinyLFU admission and buffers reads, which beats plain LRU on scans.
๐ŸงฐRedis
Offers allkeys-lru, but samples a few keys instead of tracking exact order, to save memory.
๐Ÿ—„๏ธInnoDB buffer pool
A midpoint-insertion LRU: new pages enter in the middle so a table scan cannot flush hot pages.
๐ŸงLinux page cache
Uses active and inactive lists, a CLOCK-style approximation of LRU.
Mini case: scan flushes the cache
๐Ÿ”ฅHot keys cached95% hit rate
โ†’โ†“report scans 1M rows
๐ŸงนPlain LRUall hot keys evicted
โ†’โ†“use segmented LRU
๐Ÿ›ก๏ธHot segment protectedscan stays in probation
A plain LRU loses its hot keys to a one-time scan. A segmented LRU keeps them.

12Related Topics to Read Next

Cache Eviction Policiesโ†’

The ideas of LRU, LFU and FIFO, before the implementation.

Caching Strategiesโ†’

Where the cache sits and how it is filled.

Skip Listsโ†’

Another structure that keeps order with fast updates.

Redis vs Memcachedโ†’

How real caches approximate and tune LRU.

Local Cache vs Distributed Cacheโ†’

Where an in-process LRU fits.

Heap and Priority Queueโ†’

A different way to find the โ€œsmallestโ€ item fast.

Ring Bufferโ†’

Another fixed-size structure that overwrites the oldest entry.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Parts: hash map (key โ†’ node) plus doubly linked list (recency order).
  • โœ”get: map lookup, move node to front.
  • โœ”put: update and move, or insert at front. If full, evict the node before TAIL.
  • โœ”Node holds: key, value, prev, next.
  • โœ”Use sentinels: dummy HEAD and TAIL, no edge cases.
  • โœ”Threads: lock, shard, or approximate (CLOCK, sampling).
  • โœ”Weakness: scans flush the cache. Use segmented LRU or TinyLFU.
  • โœ”One line: โ€œThe map finds it, the list orders it, and the back of the list goes first.โ€
โ† Previous
Trie (Prefix Tree)
Next โ†’
Heap and Priority Queue