What is an LRU Cache?
LRU stands for Least Recently Used. An LRU Cache is a fixed-capacity cache that, once it is full, makes room for a new entry by removing the entry that has gone the longest without being read or written.
Caches exist because some work is expensive: a database query, a network call, a disk read, or a heavy computation. Keeping recent results in memory lets us answer repeated requests instantly. Memory is limited, though, so every cache needs an eviction policy that decides what to throw away when space runs out.
LRU bets on temporal locality: data that was used a moment ago is likely to be used again soon, and data that has not been touched for a long time probably will not be. That assumption holds for a huge range of real workloads, which is why LRU (or a close variant) shows up in:
CPU and OS page caches – deciding which memory pages stay in RAM.
Databases – buffer pools in MySQL InnoDB and PostgreSQL keep hot pages in memory.
Web servers and CDNs – keeping frequently requested responses close to users.
Application caches – Redis (
allkeys-lru), Guava/Caffeine in Java,functools.lru_cachein Python.
Example
Take an LRU cache with capacity = 3 and run the following operations:
put(1, A) // cache: [1:A]
put(2, B) // cache: [2:B, 1:A]
put(3, C) // cache: [3:C, 2:B, 1:A] (full)
get(1) // returns A, key 1 becomes most recently used → [1:A, 3:C, 2:B]
put(4, D) // cache full, key 2 is least recently used → evict 2 → [4:D, 1:A, 3:C]
Notice that get(1) saved key 1 from eviction. Without that read, key 1 would have been the oldest entry and would have been removed instead of key 2.
In this article we design an LRU Cache from scratch the way you would in a Low-Level Design interview: clarify requirements, pick the right building blocks, design the classes, write the code, and then make it safe for concurrent use.
1. Clarifying Requirements
Before starting the design, it is important to clarify the requirements by asking relevant questions. This helps uncover hidden assumptions, resolve ambiguities, and define the scope of the system. Gathering these details early ensures that the design aligns with the interviewer's expectations and avoids making incorrect assumptions.
The following is an example of a discussion between the candidate and the interviewer during the requirement clarification phase:
Candidate: Should the cache work only with specific types, such as int keys and int values, or should it be generic?
Interviewer: Make it generic. Any key type is fine as long as it can be hashed and compared for equality.
Candidate: Which operations do we need? Only get and put, or also delete, size and clear?
Interviewer: Focus on get and put. We can talk about extra operations as extensions.
Candidate: What should get return when the key is not in the cache?
Interviewer: Return null (or -1 for an integer-only version). The caller treats it as a cache miss.
Candidate: If put is called with a key that already exists, should we update the value and also treat it as a fresh use?
Interviewer: Yes. Updating a key counts as usage, so the key becomes the most recently used entry.
Candidate: When the cache is full and a new key arrives, we evict exactly one entry, the least recently used one, correct?
Interviewer: Correct. Capacity is a fixed number of entries, and eviction always removes the least recently used entry.
Candidate: Will multiple threads read and write the cache at the same time?
Interviewer: Yes. Assume it sits inside a multi-threaded server, so it must be thread-safe.
Candidate: What are the performance expectations?
Interviewer: Both get and put must run in O(1) average time. A design that scans the cache on eviction is not acceptable.
Based on the discussion, we can summarize the system requirements as follows:
Functional Requirements
Support a
get(key)operation that returns the value if the key exists, otherwisenull.Support a
put(key, value)operation that inserts a new entry or updates an existing one.When inserting a new key into a full cache, evict the least recently used entry first.
Both
getandputmust refresh the recency of the key they touch.Keys and values must be generic (
<K, V>), with hashable keys.
Non-Functional Requirements
Performance:
getandputrun in O(1) average time, including eviction.Thread Safety: concurrent calls must never corrupt the cache or return stale data.
Memory: overhead per entry should be a small constant (a few pointers), and total size is bounded by capacity.
Clean Design: responsibilities are split into small classes that follow object-oriented principles.
With the requirements clearly defined, the next step is to identify the core building blocks of our LRU Cache.
2. Identifying Core Entities
Most LLD problems model real-world things such as users, vehicles or bookings. An LRU Cache is different: it is a data structure design problem. The "entities" are the internal data structures and the small classes that wrap them. Choosing them correctly is the entire problem, because the wrong choice silently turns an O(1) operation into an O(n) one.
Reading the requirements again, the cache has to answer two very different questions on every call:
Where is this key? Find the entry for a key instantly (lookup).
Who is the oldest? Know which entry was used least recently, and update that order on every access (ordering).
Let's work out which structure answers each question in O(1), one requirement at a time.
2.1 The Need for Fast Lookup
Requirement:
Both get and put operations must run in O(1) average time.
Every get("user_123") must find its entry immediately. Scanning a list of entries would be O(n), so we need constant-time access by key. The natural choice is a HashMap:
O(1) average time to look up, insert, update and remove a key.
Works with any hashable key type, which satisfies the generic requirement.
So is a HashMap enough? Not quite. A HashMap stores entries by hash bucket, not by time of use. When the cache is full and we have to evict, the map cannot tell us which key is the least recently used one.
We could store a timestamp next to every value, but then eviction becomes "scan all entries and find the smallest timestamp", which is O(n). With a million entries, every insert into a full cache would touch a million entries. That breaks the O(1) requirement.
Conclusion: the HashMap solves lookup, but we still need a second structure that keeps entries in order of use.
2.2 The Need for Fast Ordering
Requirement:
When the cache is full, automatically evict the least recently used entry.
We need a structure that keeps entries sorted from Most Recently Used (MRU) to Least Recently Used (LRU) and supports these operations, each in O(1):
| Operation | When it happens | What must happen |
|---|---|---|
| Insert at front | put with a new key | The new entry becomes the MRU entry. |
| Move to front | get hit, or put on an existing key | An entry anywhere in the order jumps to the MRU position. |
| Remove from back | put on a full cache | The LRU entry is removed. |
| Remove from middle | Part of "move to front" | Detach an entry from its current position. |
Let's test the obvious candidates against this list.
Option 1: Array / ArrayList
Keeping entries in an array ordered by use looks simple. But moving an element from index i to the front means shifting every element before it by one position. Removing from the middle has the same problem. Both are O(n). Rejected.
Option 2: Singly Linked List
A linked list can insert at the head and unlink a node without shifting anything. The catch is that in a singly linked list each node only knows its next node. To unlink a node, we must update its predecessor's next pointer, and the only way to find the predecessor is to walk from the head. That walk is O(n), even if we already hold a reference to the node itself. Rejected.
Option 3: Doubly Linked List
In a Doubly Linked List (DLL), every node stores both prev and next. Given a node, we can reach both neighbours directly and stitch them together:
node.prev.next = node.next;
node.next.prev = node.prev;
That is two pointer writes, no traversal, so it is O(1). With that one capability, every operation in our table becomes constant time:
Remove from middle – unlink the node through its own
prevandnext: O(1).Insert at front – link the node right after the head: O(1).
Move to front – remove the node, then insert it at the front: O(1) + O(1).
Remove from back – the node just before the tail is the LRU entry; unlink it: O(1).
Here is what moveToFront looks like step by step. Only the four pointers around the moved node change. The rest of the list is untouched, no matter how long it is:
There is one important condition hidden in all of these O(1) claims: we must already have a direct reference to the node. A DLL can unlink a node in O(1), but finding the node for "user_123" by walking the list is still O(n).
But how do we get a direct reference to a node without traversing the list? That's where the HashMap comes back into play.
2.3 Combining Both Structures
Each structure is strong exactly where the other is weak:
| Structure | Good at | Bad at |
|---|---|---|
| HashMap | Finding an entry by key in O(1) | Knowing which entry is least recently used |
| Doubly Linked List | Reordering and evicting in O(1) once a node is in hand | Finding a node by key (O(n) traversal) |
The trick is to make the HashMap store a reference to the list node instead of storing the value directly:
HashMap<K, Node> – maps each key to its node in the list. This is our O(1) "where is this key?" answer.
Doubly Linked List of Nodes – keeps nodes ordered from MRU (just after
head) to LRU (just beforetail). This is our O(1) "who is the oldest?" answer.Node – lives in the list and holds the key, the value, and the
prev/nextpointers.
With both structures working together, every operation becomes a short sequence of O(1) steps:
| Operation | Steps | Cost |
|---|---|---|
get(key) – hit | map.get(key) → node; list.moveToFront(node); return node.value | O(1) |
get(key) – miss | map.get(key) returns nothing; return null | O(1) |
put(key, value) – update | map.get(key) → node; set node.value; list.moveToFront(node) | O(1) |
put(key, value) – insert | If full: list.removeLast() → lru; map.remove(lru.key). Then create node, list.addFirst(node), map.put(key, node) | O(1) |
Why Does the Node Store the Key?
At first, storing the key inside the node looks redundant, because the map already knows the key. It is needed for eviction. When we remove the LRU node from the tail of the list, we also have to remove its entry from the map, and map.remove() needs the key. Without the key in the node, we would have to search the map for the entry whose value is this node, which is O(n) again.
Why Use Dummy Head and Tail Nodes?
We place two permanent sentinel nodes at the ends of the list: a dummy head and a dummy tail. Real entries always live between them. Because every real node then always has a non-null prev and next, we never need special cases for an empty list, a single-element list, or removing the first or last element. The code becomes shorter and much harder to get wrong.
2.4 Entity Overview
Besides the HashMap (which comes from the standard library), we wrap the logic in three small classes:
Core Entities
| Entity | Type | Responsibility |
|---|---|---|
| Node<K, V> | Data Class | Stores one key-value pair and the prev/next pointers for the list. |
| DoublyLinkedList<K, V> | Utility Class | Maintains MRU → LRU order with O(1) addFirst, remove, moveToFront and removeLast. |
| HashMap<K, Node<K, V>> | Standard Library | Gives O(1) key → node lookup. |
| LRUCache<K, V> | Core Class | Exposes get/put, coordinates the map and the list, enforces capacity and eviction, and handles locking. |
Design Summary
These entities form the complete architecture of our LRU Cache:
Lookup is delegated to the
HashMap.Ordering is delegated to the
DoublyLinkedList.Policy (when to evict, what counts as "use") lives only in
LRUCache.Callers see only
getandput. Nodes and pointers stay hidden.
With the core entities identified, let's define their attributes, behaviours and relationships.
3. Designing Classes and Relationships
Now that we have identified the core entities, the next step is to define each class in detail. For each class, we will define:
Attributes – the data the class holds.
Methods – the behaviour it exposes.
Relationships – how it connects to the other classes.
Note
We skip trivial getters and setters to keep the focus on core behaviour. We also work bottom-up: simple classes first, then the classes that depend on them.
3.1 Class Definitions
3.1.1 Data Class: Node
The Node represents a single cache entry and, at the same time, an element of the doubly linked list. It is deliberately a plain data holder with almost no behaviour.
Responsibilities
Hold one key-value pair.
Hold links to the previous and next nodes in the recency order.
Remember its own key so eviction can clean up the map in O(1).
Attributes
| Attribute | Type | Description | Mutable? |
|---|---|---|---|
| key | K | The cache key. Needed to remove the map entry during eviction. | No |
| value | V | The cached value. Replaced when put updates an existing key. | Yes |
| prev | Node<K, V> | The neighbour closer to the MRU end (head). | Yes |
| next | Node<K, V> | The neighbour closer to the LRU end (tail). | Yes |
Methods
| Method | Description |
|---|---|
Node(key, value) | Creates a detached node. prev and next are set later by the list. |
3.1.2 Utility Class: DoublyLinkedList
The DoublyLinkedList owns the recency order. The node right after head is the most recently used entry, and the node right before tail is the least recently used one. It knows nothing about keys, capacity or eviction rules. It only moves nodes around.
Responsibilities
Insert a node at the MRU position.
Detach any node in O(1) using its own pointers.
Move a node to the MRU position.
Remove and return the LRU node.
Attributes
| Attribute | Type | Description | Mutable? |
|---|---|---|---|
| head | Node<K, V> | Dummy sentinel before the first real node. Never holds data. | No (pointer fields change) |
| tail | Node<K, V> | Dummy sentinel after the last real node. Never holds data. | No (pointer fields change) |
Methods
| Method | Description |
|---|---|
DoublyLinkedList() | Creates the two sentinels and links them: head ⇄ tail. |
addFirst(node) | Inserts node right after head (MRU position). |
remove(node) | Detaches node by linking its neighbours to each other. |
moveToFront(node) | remove(node) followed by addFirst(node). |
removeLast() | Detaches and returns the node before tail, or null if the list is empty. |
3.1.3 Core Class: LRUCache
The LRUCache is the only class callers interact with. It coordinates the map and the list, enforces the capacity limit, and decides what counts as "use".
Responsibilities
Expose the public API:
getandput.Keep the map and the list in sync at all times.
Evict the LRU entry when inserting into a full cache.
Make every operation atomic for thread safety.
Attributes
| Attribute | Type | Description | Mutable? |
|---|---|---|---|
| capacity | int | Maximum number of entries. | No |
| map | Map<K, Node<K, V>> | Key → node lookup in O(1). | Yes (contents) |
| list | DoublyLinkedList<K, V> | Recency order of all nodes. | Yes (contents) |
Methods
| Method | Description |
|---|---|
LRUCache(capacity) | Validates capacity and creates an empty map and list. |
get(key) | Returns the value and marks the key as MRU, or returns null on a miss. |
put(key, value) | Updates an existing key (and marks it MRU), or inserts a new key, evicting the LRU entry first if the cache is full. |
Key Design Principles
1. Single Responsibility Principle (SRP)
Lookup lives in the map, ordering lives in the list, and eviction policy lives in the cache. If we later change the policy (for example, to LFU), the list and node classes do not need to change.
2. Encapsulation
The map, list and nodes are private. Callers cannot reach a node and break the pointers. They only see get and put.
3. Thread Safety
Each public method runs as one atomic unit under a lock, so the map and the list are never seen half-updated. Section 6 explains why this matters even for get.
3.2 Class Diagram
4. Code Implementation
Now let's turn the design into working code. We build bottom-up: Node first, then DoublyLinkedList, and finally LRUCache, which ties everything together.
4.1 Node
The node is the smallest building block. It holds the entry and the two links.
No getters or setters.
Nodeis an internal detail, not public API. The list needs direct field access for fast pointer updates.The key is final. A node never changes which key it represents. Only its value and position change.
Pointers start empty. The list sets
prevandnextwhen the node is linked in.
4.2 DoublyLinkedList
This class owns the recency order. The node after head is the MRU entry, and the node before tail is the LRU entry.
How Each Method Works
Constructor – creates the two sentinels and links them, so an empty list is
HEAD ⇄ TAIL.addFirst(node)– sets the new node's own pointers first, then updates its neighbours. If we overwrotehead.nextfirst, we would lose the reference to the old first node.remove(node)– the neighbours are reachable through the node itself, so we link them to each other and the node drops out. No traversal is needed.moveToFront(node)– reusesremoveandaddFirstinstead of special-case code.removeLast()– the list is empty whentail.prev == head. Otherwise it detaches and returnstail.prev.
4.3 LRUCache
The cache class coordinates the map and the list. Every public method is guarded by a lock, so each call is atomic.
Walking Through the Logic
get(key)
Look up the node in the map. If it is missing, return
null(cache miss).Move the node to the front of the list, because reading counts as use.
Return the node's value.
put(key, value)
Key exists: overwrite the value and move the node to the front. The size does not change, so nothing is evicted.
Key is new and the cache is full: remove the last node from the list, then use
lru.keyto remove it from the map. Both structures must be updated.Then insert: create a node, add it to the front of the list, and register it in the map.
Common Mistake
Calling
map.containsKey(key)and thenmap.get(key)performs two lookups. Using onemap.get(key)and checking fornullis cleaner and does half the hashing work. Another frequent bug is evicting from the list but forgettingmap.remove(lru.key). The map then keeps pointing to a node that is no longer in the list.
4.4 Operation Flowcharts
The two flowcharts below summarise every path through get and put. Each box is a constant-time step, so every path is O(1).
get(key)
put(key, value)
4.5 Run and Test
The demo below replays the example from the beginning of the article and adds an update followed by another eviction:
Expected output
get(1) = A
get(2) = null
get(3) = C
get(4) = null
get(1) = A2
get(5) = E
Why is key 4 evicted and not key 3? After get(3), the order is [3, 4, 1]. Then put(1, "A2") moves key 1 to the front, giving [1, 3, 4]. Key 4 is now the least recently used entry, so put(5, "E") evicts it.
5. Complexity Analysis
| Operation | Time | Space | Why |
|---|---|---|---|
get(key) | O(1) average | O(1) | One hash lookup plus a constant number of pointer writes. |
put(key, value) – update | O(1) average | O(1) | One hash lookup plus moveToFront. |
put(key, value) – insert / evict | O(1) average | O(1) | removeLast, one map removal, one map insertion, one addFirst. |
| Whole cache | – | O(capacity) | One map entry and one node (with two pointers) per cached key, plus two sentinels. |
"Average" comes from the HashMap: lookups are O(1) on average and degrade only with pathological hash collisions.
6. Concurrency and Thread Safety
In a multi-threaded server, many request threads share one cache instance. The cache holds two structures that must always agree: the map and the list. If one thread sees them halfway through another thread's update, the cache breaks in subtle ways.
Concern 1: Corrupting the List and the Map (High Risk)
Methods like addFirst and remove rewrite three or four pointers one after another. If two threads interleave those writes, the list ends up pointing at nodes that have already moved.
Scenario: the cache is full with order [c, b, a]. Thread 1 calls get("a") and starts moving a to the front. At the same moment Thread 2 calls put("d", 4) and starts evicting the LRU node, which is also a.
Thread 1 begins unlinking
a.Thread 2 reads
tail.prevand still seesaas the last node.Thread 2 unlinks
aagain, using pointers Thread 1 is changing.Thread 1 re-inserts
aat the front.Thread 2 removes key
"a"from the map.
Result: node a is back in the list, but its key is gone from the map. The list and the map now disagree. Future evictions can remove the wrong entries, the cache can grow beyond capacity, and stale values can be returned.
Fix: wrap the whole get and the whole put in the same lock (synchronized in Java, a mutex in C++/Go, threading.Lock in Python). Each operation then sees and leaves the map and the list in a consistent state.
Why a Read-Write Lock Does Not Help
It is tempting to let many
getcalls share a read lock. Butgetis not a read-only operation in an LRU cache. Every hit callsmoveToFront, which rewrites list pointers. Two concurrentgetcalls are therefore two writers. Bothgetandputneed the same exclusive lock.
Concern 2: One Global Lock Becomes a Bottleneck (Medium Risk)
A single lock is correct but serialises every operation. With 16 threads working on thousands of unrelated keys, they all queue behind one lock, and adding CPU cores does not increase throughput.
Fix: striped (sharded) locking. Split the cache into N independent shards, each a full LRUCache with its own map, list and lock. A key always goes to shard hash(key) % N. Threads that touch different shards never block each other.
Trade-off: eviction becomes per shard instead of global. Each shard evicts its own LRU entry, which approximates true global LRU closely enough for most workloads. Production caches such as Guava and Caffeine use similar segmentation internally.
7. Extensions
Interviewers often finish with "how would you extend this?". Each extension below adds one capability without rewriting the core design.
7.1 Per-Entry TTL (Time-to-Live)
Scenario: session tokens or price quotes must expire after a fixed time, even if they are being read constantly. Store an expiry timestamp in each node and treat an expired entry as a miss inside get (lazy expiration). A background sweeper can also remove expired entries periodically if memory must be reclaimed quickly.
7.2 Size-Aware (Weighted) Eviction
Scenario: a 2 KB thumbnail and a 5 MB image should not count as "one entry" each. Give every node a weight, track the running total, and keep evicting from the tail until the total fits the budget. Reject any single entry that is larger than the whole budget.
7.3 Hit and Miss Metrics
Scenario: we need to know whether the cache is actually helping. Count hits and misses inside get. Because the counters change under the same lock, they stay accurate without extra synchronisation. A low hit ratio suggests raising capacity or caching different data.
7.4 The Built-In Shortcut (Java)
Java's LinkedHashMap is internally a hash map plus a doubly linked list, which is exactly our design. With accessOrder = true and an overridden removeEldestEntry, it becomes an LRU cache in a few lines. Mention it in interviews to show awareness, but expect to be asked to build it from scratch. It is also not thread-safe on its own.
8. Interview Tips
Start from the two questions ("where is this key?" and "who is the oldest?") and derive HashMap + Doubly Linked List from them. Interviewers value the reasoning more than the final answer.
Explain why each simpler option fails: HashMap alone (O(n) eviction), array (O(n) shifting), singly linked list (O(n) to find the predecessor).
Call out the key-in-node detail and the dummy sentinels before you start coding.
Update both structures together on eviction and insertion, and say so out loud.
Mention that
getmutates state, which is why a read-write lock does not work, and offer striping as the scaling step.Know the next questions: TTL, weighted eviction, metrics, LFU versus LRU, and
LinkedHashMap.