LRU cache
A fixed-size cache that evicts the least recently used item, built from a hash table plus a doubly linked list so every operation is O(1).
Description
A cache keeps a limited number of results close at hand so you don't recompute or refetch them. When it's full and something new arrives, something must go. An LRU (least recently used) cache evicts the item that hasn't been used for the longest time, on the bet that recently used items are likely to be used again.
The classic implementation combines two structures. A hash table maps each key to its node, so lookups are O(1). A doubly linked list keeps nodes in order of use: the most recently used at the front, the least recently used at the back.
On every get or put, the item's node moves to the front, which is O(1) because the hash table gives you the node and the list can unlink and relink it in constant time. When the cache is full, the node at the back is evicted and removed from the hash table.
In JavaScript, a Map remembers insertion order, so deleting and re-inserting a key moves it to the end. That gives a compact LRU cache with the same O(1) behavior, which is what the example uses.
How it works
Usage order, most recent first. D was just used; B is next to be evicted.
- node 0: D, next A
- node 1: A, next C
- node 2: C, next B
- node 3: B, next null
The hash table maps each key to its list node
- bucket 0: D
- bucket 1: A
- bucket 2: B
- bucket 3: C
Complexity
| Operation | Average | Worst |
|---|---|---|
| GetHash lookup, then move the node to the front. | O(1) | O(1) |
| Put | O(1) | O(1) |
| Evict the least recently used | O(1) | O(1) |
Space: O(capacity)
The worst case assumes a well-behaved hash table. Real caches also need eviction by age (TTL), size-aware limits, and thread safety.
TypeScript implementation
An LRU cache using JavaScript's insertion-ordered Map, with hit and miss counters.
// An LRU cache using Map's insertion order: deleting and re-inserting a key
// moves it to the "most recent" end, and the first key is the least recent.
export class LRUCache<K, V> {
private map = new Map<K, V>();
private capacity: number;
hits = 0;
misses = 0;
constructor(capacity: number) {
this.capacity = capacity;
}
get(key: K): V | undefined {
if (!this.map.has(key)) {
this.misses++;
return undefined;
}
const value = this.map.get(key)!;
this.map.delete(key); // move to the most recent end
this.map.set(key, value);
this.hits++;
return value;
}
put(key: K, value: V): void {
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size >= this.capacity) {
const oldest = this.map.keys().next().value as K; // least recently used
this.map.delete(oldest);
}
this.map.set(key, value);
}
keysByRecency(): K[] {
return [...this.map.keys()].reverse(); // most recent first
}
}
export function demo(): string[] {
const cache = new LRUCache<string, number>(3);
cache.put("A", 1);
cache.put("B", 2);
cache.put("C", 3);
cache.get("A"); // A becomes most recent
cache.put("D", 4); // full: evicts B, the least recently used
return [
`recency (most recent first): ${cache.keysByRecency().join(", ")}`,
`get B → ${cache.get("B")} (evicted), get C → ${cache.get("C")}`,
`hits ${cache.hits}, misses ${cache.misses}`,
];
}When to use it
Use it when
- Caching expensive computations, database results or API responses with a memory limit.
- Recent items are more likely to be requested again: page caches, image caches, session data.
Avoid it when
- Some items are popular over long periods but used in bursts: an LFU (least frequently used) or adaptive policy may hit more often.
- A one-off scan through many items would flush the cache of genuinely popular entries (scan pollution). Consider segmented LRU or similar.
- The cache must be shared between processes: use Redis or Memcached, which offer LRU-like eviction.
Pitfalls
- Unbounded caches labeled LRU but never evicting, which become memory leaks.
- Caching mutable objects that callers then modify.
- Stale data: LRU says nothing about freshness. Add time-to-live where data changes.
- Concurrency: moving nodes on every read needs locking in multi-threaded code, which can become a bottleneck.
Alternatives
Plain hash table
Choose it when the data fits in memory and never needs evicting.
LFU or TinyLFU cache
Choose it when frequency of use predicts future use better than recency, as in many web workloads.
Cache-aside pattern
Choose it when you're designing caching between an application and a database across services.