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_cache in 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.

LRU Cache walkthrough (capacity = 3)OperationCache order: MRU → LRUput(1, A)1:Aput(2, B)2:B1:Aput(3, C)3:C2:B1:Aget(1) → A1:A3:C2:B1 moves to frontput(4, D)4:D1:A3:Cevict 2:B
Green = most recently used entry after the operation; Red = entry removed by eviction.

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

  1. Support a get(key) operation that returns the value if the key exists, otherwise null.

  2. Support a put(key, value) operation that inserts a new entry or updates an existing one.

  3. When inserting a new key into a full cache, evict the least recently used entry first.

  4. Both get and put must refresh the recency of the key they touch.

  5. Keys and values must be generic (<K, V>), with hashable keys.

Non-Functional Requirements

  1. Performance: get and put run in O(1) average time, including eviction.

  2. Thread Safety: concurrent calls must never corrupt the cache or return stale data.

  3. Memory: overhead per entry should be a small constant (a few pointers), and total size is bounded by capacity.

  4. 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:

  1. Where is this key? Find the entry for a key instantly (lookup).

  2. 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.

Problem 1: a HashMap alone has no notion of recencyHashMap<K, V>"user_7"Diana"user_2"Bob"user_9"Eve"user_1"Aliceget("user_2") → O(1)hash the key, jump straight to the bucketevict LRU entry → O(n)Which key was used least recently?The map does not remember access order,so we must scan every entry (plus timestamps).

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):

OperationWhen it happensWhat must happen
Insert at frontput with a new keyThe new entry becomes the MRU entry.
Move to frontget hit, or put on an existing keyAn entry anywhere in the order jumps to the MRU position.
Remove from backput on a full cacheThe LRU entry is removed.
Remove from middlePart 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 prev and next: 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).

Problem 2: which structure can move or remove an entry in O(1)?Array / ArrayList: moving index 1 to the front shifts every element in betweenCABDEA jumps to index 0move / remove = O(n)elements must be shiftedSingly linked list: to unlink A we need its predecessor, so we walk from the headheadCABtraverse to find prev of Afind predecessor = O(n)even when we hold a ref to ADoubly linked list: every node knows prev AND next, so unlinking is pure pointer surgeryHEADCABA.prev.next = A.next ; A.next.prev = A.prevremove / move = O(1)only if we already hold a ref to A

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:

moveToFront(B) = remove(B) + addFirst(B), all in O(1)Step 0: initial listHEADdummyABCTAILdummyStep 1: remove(B) – neighbours bypass BHEADdummyACTAILdummyBdetachedA.next = C ; C.prev = AStep 2: addFirst(B) – B is now MRUHEADdummyBACTAILdummyB.next = HEAD.next ; B.prev = HEAD ; HEAD.next.prev = B ; HEAD.next = B

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:

StructureGood atBad at
HashMapFinding an entry by key in O(1)Knowing which entry is least recently used
Doubly Linked ListReordering and evicting in O(1) once a node is in handFinding 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 before tail). This is our O(1) "who is the oldest?" answer.

  • Node – lives in the list and holds the key, the value, and the prev/next pointers.

HashMap gives the direct reference, Doubly Linked List gives the orderHashMap<K, Node>key: 'B'→ Node refkey: 'A'→ Node refkey: 'C'→ Node refHEADdummyNodekey='C'val=3Nodekey='A'val=1Nodekey='B'val=2TAILdummyMRULRU (evicted first)Doubly Linked List (MRU → LRU)
get / put: map lookup O(1) → pointer to node → moveToFront O(1). Eviction: removeLast() O(1) → map.remove(node.key) O(1).

With both structures working together, every operation becomes a short sequence of O(1) steps:

OperationStepsCost
get(key) – hitmap.get(key) → node; list.moveToFront(node); return node.valueO(1)
get(key) – missmap.get(key) returns nothing; return nullO(1)
put(key, value) – updatemap.get(key) → node; set node.value; list.moveToFront(node)O(1)
put(key, value) – insertIf 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:

Entity overviewLRUCache<K, V>capacity, map, listHashMap<K, Node<K, V>>key → node referenceDoublyLinkedList<K, V>head, tail (dummies)Node<K, V>key, value, prev, nextownsownsmaps tocontains 0..n

Core Entities

EntityTypeResponsibility
Node<K, V>Data ClassStores one key-value pair and the prev/next pointers for the list.
DoublyLinkedList<K, V>Utility ClassMaintains MRU → LRU order with O(1) addFirst, remove, moveToFront and removeLast.
HashMap<K, Node<K, V>>Standard LibraryGives O(1) key → node lookup.
LRUCache<K, V>Core ClassExposes 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 get and put. 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

AttributeTypeDescriptionMutable?
keyKThe cache key. Needed to remove the map entry during eviction.No
valueVThe cached value. Replaced when put updates an existing key.Yes
prevNode<K, V>The neighbour closer to the MRU end (head).Yes
nextNode<K, V>The neighbour closer to the LRU end (tail).Yes

Methods

MethodDescription
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

AttributeTypeDescriptionMutable?
headNode<K, V>Dummy sentinel before the first real node. Never holds data.No (pointer fields change)
tailNode<K, V>Dummy sentinel after the last real node. Never holds data.No (pointer fields change)

Methods

MethodDescription
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: get and put.

  • 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

AttributeTypeDescriptionMutable?
capacityintMaximum number of entries.No
mapMap<K, Node<K, V>>Key → node lookup in O(1).Yes (contents)
listDoublyLinkedList<K, V>Recency order of all nodes.Yes (contents)

Methods

MethodDescription
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

Class diagramLRUCache<K, V>- capacity: int- map: Map<K, Node<K, V>>- list: DoublyLinkedList<K, V>+ LRUCache(capacity: int)+ get(key: K): V+ put(key: K, value: V): voidDoublyLinkedList<K, V>- head: Node<K, V> (dummy)- tail: Node<K, V> (dummy)+ addFirst(node): void+ remove(node): void+ moveToFront(node): void+ removeLast(): Node<K, V>Node<K, V>~ key: K~ value: V~ prev: Node<K, V>~ next: Node<K, V>+ Node(key: K, value: V)owns 1map values (Node refs)contains 0..n

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. Node is 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 prev and next when 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 overwrote head.next first, 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) – reuses remove and addFirst instead of special-case code.

  • removeLast() – the list is empty when tail.prev == head. Otherwise it detaches and returns tail.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)

  1. Look up the node in the map. If it is missing, return null (cache miss).

  2. Move the node to the front of the list, because reading counts as use.

  3. 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.key to 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 then map.get(key) performs two lookups. Using one map.get(key) and checking for null is cleaner and does half the hashing work. Another frequent bug is evicting from the list but forgetting map.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)

get(key)acquire lockkey presentin map?NoCache MISSreturn nullYesnode = map.get(key)list.moveToFront(node)(mark as MRU)Cache HITreturn node.value
Every path releases the lock before returning. Total cost: O(1).

put(key, value)

put(key, value)acquire lockkey alreadyin map?Yes (update)node = map.get(key)node.value = valuelist.moveToFront(node)(update counts as use)No (insert)map.size()== capacity?Yeslru = list.removeLast()map.remove(lru.key)NonewNode = new Node(key, value)list.addFirst(newNode)map.put(key, newNode)release lock, return
Update and insert paths both finish in O(1); eviction happens only when the cache is full.

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

OperationTimeSpaceWhy
get(key)O(1) averageO(1)One hash lookup plus a constant number of pointer writes.
put(key, value) – updateO(1) averageO(1)One hash lookup plus moveToFront.
put(key, value) – insert / evictO(1) averageO(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.

  1. Thread 1 begins unlinking a.

  2. Thread 2 reads tail.prev and still sees a as the last node.

  3. Thread 2 unlinks a again, using pointers Thread 1 is changing.

  4. Thread 1 re-inserts a at the front.

  5. 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 get calls share a read lock. But get is not a read-only operation in an LRU cache. Every hit calls moveToFront, which rewrites list pointers. Two concurrent get calls are therefore two writers. Both get and put need 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.

Striped locking: shard = hash(key) % NStripedLRUCacheget / puthash(key) % 4Shard 0own lockown map + listShard 1own lockown map + listShard 2own lockown map + listShard 3own lockown map + list
Keys in different shards never wait for each other; each shard evicts its own LRU entry.

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 get mutates 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.