LRU cache: hash map + doubly linked list
A cache that evicts the entry nobody has touched for the longest time, built from a hash map for O(1) lookup and a doubly linked list that keeps entries in order of last use. It exists because a cache must decide what to throw away when full, and "least recently used" is a cheap, good guess about what will not be needed soon.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Get | O(1): 1 hash lookup + 4 pointer swaps | Find the node via the map, unlink it, relink at the head (most recent). |
| Put (new key) | O(1): 1 map insert + list push at head | If the cache is full, first pop the tail node and remove its key from the map. |
| Put (existing key) | O(1) | Update the value and move the node to the head, same as a get. |
| Evict | O(1): unlink the tail | No scanning; the tail is always the least recently used entry. |
Memory: Per entry: the key and value, two list pointers (16 bytes) and a map slot (about 16 bytes). Caching 1M aliases of 7 bytes with 100-byte URLs costs roughly 1M × (107 + 32 + overhead) ≈ 160 MB.
Hash map pointing into an ordered doubly linked list
The map answers "where is this key" in one step; the list keeps entries ordered by last use. A get unlinks the node and relinks it after HEAD; eviction pops the node before TAIL.
How it works
- Keep a hash map from key to list node. The node holds the key, the value, and two pointers: prev and next.
- Keep a doubly linked list of those nodes with two sentinel nodes, HEAD and TAIL, so inserting and removing never has to special-case an empty list. The node right after HEAD is the most recently used; the node right before TAIL is the least.
- On get(key): look the node up in the map. If absent, return a miss. If present, unlink it (node.prev.next = node.next; node.next.prev = node.prev) and insert it right after HEAD. Return its value.
- On put(key, value) for a new key: if the cache is at capacity, take the node before TAIL, unlink it, and delete its key from the map. Then create the new node, insert it after HEAD, and add it to the map.
- On put for an existing key: update the value in the node and move it to the head exactly as a get would.
Why two structures and not one
- The map gives O(1) "is this key here and where is its node". The list gives O(1) "which entry is oldest" and O(1) "mark this one as newest". A list alone would need O(n) to find a key; a map alone has no notion of order.
- Redis does not keep the list. It samples 5 random keys and evicts the one with the oldest access clock (approximated LRU). That saves 16 bytes per key and is within a few percent of true LRU on hit rate.
Worked example
Hot aliases in the URL shortener
- The redirect service keeps an in-process LRU of 100K alias → URL entries per server as a first layer in front of Redis. 100K × roughly 160 bytes ≈ 16 MB per process.
- Request for alias aB3xZ9: map lookup finds the node (hit, about 50 ns), four pointer writes move it to the head, return the URL. No network call.
- Request for alias q7Lm2Pz, not in the map: a miss, so the service asks Redis. The cache is full, so it unlinks the node before TAIL (an alias last read 20 minutes ago), deletes that key from the map, creates a node for q7Lm2Pz at the head, and adds it to the map. Three operations, all constant time.
- A viral link is read 50,000 times a minute: every read moves its node to the head, so it never drifts toward TAIL and is never evicted while it stays popular. A link read once an hour drifts to TAIL within minutes and is evicted on the next miss.
- The 80/20 rule on the shortener’s traffic means this 100K-entry layer absorbs about 70% of reads on each server before Redis sees them.
When it is the wrong choice
- A one-off scan (a nightly batch reading every row once) flushes the whole cache because every new key becomes "most recent". Use LFU, which keeps genuinely hot keys, or a scan-resistant policy like ARC or W-TinyLFU.
- Entries have very different sizes: LRU counts entries, not bytes, so one 10 MB value can evict ten thousand small ones. Track bytes and evict until under budget.
- Access patterns are periodic with a period longer than the cache (a report read daily, a cache that holds an hour): LRU misses every time. Pin those keys or give them a TTL-based refresh instead.
Interviewer follow-ups
Answer out loud before you open each one.
Why does the list have to be doubly linked?
Removing a node from the middle needs its predecessor so that predecessor can point past it. With a singly linked list you would have to walk from the head to find it, which is O(n). The prev pointer makes unlinking a four-pointer, O(1) operation.
What are the sentinel HEAD and TAIL nodes for?
They are dummy nodes that never hold data, so every real node always has a prev and a next. Insert-after-HEAD and remove-before-TAIL then work the same whether the list has zero, one or a million entries, with no null checks.
Why does Redis use approximated LRU instead of the real thing?
True LRU costs two pointers per key, 16 bytes, which on a 100M-key node is 1.6 GB of pure bookkeeping, and every read mutates a shared list. Sampling five keys and evicting the one with the oldest 24-bit access clock needs 3 bytes per key and no list, and in tests evicts almost the same keys.
How would you make this safe for many threads?
A single lock around get and put works but serialises every access. The usual fix is to shard the cache into N independent LRUs by hashing the key, each with its own lock, so threads only contend when they touch the same shard. Libraries like Caffeine go further and batch the list updates asynchronously.