Field notes on the LRU cache. Short version: it is two data structures glued together, and the glue is the whole point.

What it promises

A cache has fixed capacity. When it is full and a new item arrives, something must go. LRU (least recently used) says: evict the item untouched for the longest time. The bet is that what you used recently, you will use again soon. Often true. Not always. More on that below.

The requirement that makes it interesting: get and put must both be O(1). Not “fast in practice”. Constant, regardless of capacity.

Why one structure fails

Try a hash map alone. Lookup is O(1). But a hash map has no order, so finding the least recently used key means scanning everything. O(n).

Try an array or list ordered by recency. The oldest is at one end, so eviction is cheap. But finding a key to refresh it means scanning. O(n) again. Moving it to the front of an array shifts everything. Also O(n).

Each structure solves half the problem. Combine them.

The combination

Keep a doubly linked list where the front is the most recently used and the back is the least. Keep a hash map from key to the list node that holds it.

  • get(key): look up the node in the map (O(1)). Unlink it from where it is and relink at the front (O(1), because a doubly linked list node knows both neighbours). Return the value.
  • put(key, value): if the key exists, update the value and move the node to the front. If not, create a node at the front and add it to the map. If the size now exceeds capacity, remove the node at the back and delete its key from the map.

Why doubly linked? Because to unlink a node from the middle you must fix the previous node’s pointer, and a singly linked list cannot reach backwards without walking from the head. That walk is the O(n) you were avoiding. Why store the key inside each node? Because when you evict the tail you must know which map entry to delete.

Trace it once by hand

Capacity 3, caching product names by ID. Front of the list is written first.

  1. put 101, 102, 103. List: 103, 102, 101.
  2. get 101. It moves to the front. List: 101, 103, 102.
  3. put 104. Size would be 4, so evict the back, which is 102. List: 104, 101, 103.
  4. get 102. Miss. It was evicted, though it was inserted after 101. Insertion order is not recency; the earlier get of 101 saved it.

Step 4 is where people get confused. That is FIFO behaviour versus LRU behaviour, and the difference is exactly the move-to-front on read.

Implementation notes

Opinion: do not hand-roll this in production. Java’s LinkedHashMap can be built in access-order mode and has a hook, removeEldestEntry, to evict past a size. Python’s OrderedDict has move_to_end and popitem. Python’s functools.lru_cache does the job for function results. These are the same two-structure design, tested.

Write it by hand once so you understand it. A common trick in hand-written versions is a pair of dummy head and tail nodes. They remove every “is the list empty” and “is this the only node” special case. Worth it.

Thread safety is not included. A get mutates the list, so even readers write. Two threads moving nodes at once will corrupt pointers. Either one lock around every operation (simple, becomes a bottleneck) or sharding into several smaller caches by key hash, each with its own lock. Caffeine, the Java library, takes a different approach with buffered reads, but that is a deeper topic.

Where LRU is the wrong answer

Three situations I would flag in a design review.

  • Scans. A nightly job reads a million rows once each. They all become “recent” and push out the hot items your users need. Databases deal with this using variants (InnoDB’s buffer pool splits its list into young and old regions for this reason).
  • Frequency matters more than recency. A product viewed 10,000 times a day but not in the last minute should not lose to something viewed once, a second ago. LFU or hybrid policies handle this better.
  • Huge scale. Maintaining an exact ordered list is costly. Redis does not do exact LRU; it samples a few keys and evicts the oldest of the sample. Approximate, and good enough.

Also remember that capacity counts entries, not bytes. If values vary from 200 bytes to 2 MB, an entry-count limit is a memory incident waiting for a bad Monday. Bound by size where it matters.

The general lesson beyond caches: when one structure gives you fast lookup and another gives you fast ordering, ask whether pointing one into the other solves it. This pattern shows up all over systems code.

Leave a Reply

Trending