← The Ledger
Vol. I, No. 26 · Cache Structures

The LRU Cache

A hash map to find each entry and a linked list to remember which one was used last.

Written by Khushal Agrawal

loading…

Recency Eviction

A cache holds at most c entries. When a new key arrives and the cache is full, something must leave, and a least-recently-used (LRU) cache evicts the entry whose last access is oldest. With capacity 4 and the accesses A, B, C, D, A, E, the arrival of E evicts B: A was touched again after B, so B is now the oldest.

The policy bets on temporal locality, the observation that a key used recently is likely to be used again soon. It needs no frequency counts and no knowledge of the future, and it is the baseline every other replacement policy is measured against. The engineering problem is maintaining the recency order at constant cost per access.

Hash Map Plus Linked List

Two structures share each entry. A hash table maps a key to its entry in O(1) expected time, and a doubly linked list orders the entries by recency, most recent at the head and least recent at the tail.

typedef struct entry {
    key_t         key;
    value_t       val;
    struct entry *prev, *next;   // recency list
} entry;

typedef struct {
    size_t  cap, size;
    map_t  *index;               // key -> entry*
    entry   head;                // sentinel: head.next is most recent,
} lru;                           //           head.prev is least recent

The map answers "where is this key"; the list answers "who is oldest". Neither does both: a list alone needs a linear scan to find a key, and a map alone has no order.

Get

A lookup finds the entry through the map, then moves it to the head of the list, because it is now the most recently used.

value_t *get(lru *c, key_t k) {
    entry *e = map_get(c->index, k);
    if (!e) return NULL;          // miss
    unlink(e);
    push_front(c, e);             // now the most recent
    return &e->val;
}

Every hit is therefore a write to shared state. Two pointer splices are cheap, but in a multi-threaded cache they need a lock, and that is the cost the later cards in this chapter work to remove. The read side, finding the entry, never touches the list at all.

Put And Eviction

An insert of an existing key updates the value and promotes the entry. A new key, when the cache is full, first evicts the tail, which is by construction the least recently used entry, from both the list and the map.

void put(lru *c, key_t k, value_t v) {
    entry *e = map_get(c->index, k);
    if (e) { e->val = v; unlink(e); push_front(c, e); return; }
    if (c->size == c->cap) {
        entry *victim = c->head.prev;      // least recently used
        unlink(victim);
        map_del(c->index, victim->key);    // why the entry stores its key
        free(victim);
        c->size--;
    }
    e = new_entry(k, v);
    map_put(c->index, k, e);
    push_front(c, e);
    c->size++;
}

The entry stores its own key so that eviction, which starts from the list, can remove the matching map slot. Every path through the function touches a bounded number of entries, so put is O(1) expected regardless of capacity, and capacity can be counted in entries or in bytes by evicting in a loop until the new value fits.

Constant-Time Unlinking

The list is doubly linked so that an entry found through the map can be removed without searching for its predecessor. A circular list with one sentinel node removes every empty-list and end-of-list special case.

static void unlink(entry *e) {
    e->prev->next = e->next;
    e->next->prev = e->prev;
}

static void push_front(lru *c, entry *e) {
    e->next = c->head.next;
    e->prev = &c->head;
    c->head.next->prev = e;
    c->head.next = e;
}

With the sentinel, an empty cache is head.next == head.prev == &head, and neither function branches. A singly linked list would need the predecessor, which costs a scan. Get, put, and evict are all O(1) expected, the expectation coming only from the hash map; the list operations are O(1) worst-case, as in a linked deque.

Stack Distance

LRU has a property most policies lack: a larger cache always holds a superset of what a smaller one holds. Mattson and colleagues showed in 1970 that this lets one pass over a trace compute the hit rate for every capacity at once, using each access's stack distance.

trace      A  B  C  A  D  B  A
distance   -  -  -  3  -  4  3
// distinct keys touched since this key's last use, counting itself
// capacity c hits exactly the accesses with distance <= c

At capacity 3 this trace hits twice; at capacity 4, three times. The distribution of stack distances is the cache's miss-ratio curve, which is how storage systems size caches without running one experiment per size.

Where LRU Fails

Recency is the wrong signal for two common patterns. A loop over c + 1 keys through a cache of capacity c misses on every access, because each key is evicted exactly one access before it returns. A large sequential scan, such as a full table scan, a backup, or an LSM tree compaction reading through a block cache, fills the cache with entries that will never be read again and evicts every hot entry on the way through.

capacity 3, loop over 4 keys
A B C D A B C D A ...     every access is a miss

1,000-page cache, scan of 10,000 pages
every hot page evicted; no scanned page reused

Both failures share a cause: one access is enough to enter at the head. The next three cards change what admission or promotion requires.

Two-Queue Admission

Johnson and Shasha's 1994 2Q admits a key to the main LRU only on its second access. First-time keys wait in a small FIFO; when they leave it, only their identifiers are remembered in a ghost list.

// A1in: FIFO of first-time keys
// A1out: ghost list, keys only, no values
// Am: LRU of keys seen at least twice
on access(k):
    if (k in Am)         move k to head of Am;     // hit
    else if (k in A1in)  ;                          // hit, no promotion
    else if (k in A1out) insert k at head of Am;    // second touch
    else                 insert k at tail of A1in;  // first touch

A scan passes through A1in and never reaches Am, so hot keys survive it. The ghost list costs a few bytes per remembered key and lets a key returning soon after its first touch be promoted. O'Neil's earlier LRU-K generalises the idea to the k-th most recent access.

Midpoint Insertion

InnoDB's buffer pool, which caches the 16 KB pages of its B+ tree indexes, gets scan resistance from one list by inserting new pages in the middle instead of at the head. The list is split into a new sublist of about 5/8 and an old sublist of 3/8.

[ new sublist 5/8        |  old sublist 3/8 ]
  head                   midpoint            tail

page read from disk     -> insert at the midpoint
accessed again in old   -> move to the head of new, but only after
                           innodb_old_blocks_time (1000 ms) in old
eviction                -> from the tail of old

A page touched once by a scan ages out of the old sublist without displacing anything in the new one. The time threshold handles the scan that reads each page several times in quick succession, which would otherwise count as reuse. The Linux page cache applies the same principle with separate active and inactive lists.

CLOCK Approximation

Exact LRU writes the list on every hit. CLOCK drops the list: entries sit in a circular array like a ring buffer, a hit only sets a reference bit, and eviction sweeps a hand around the array.

entry *evict(clock_t *c) {
    for (;;) {
        entry *e = c->slot[c->hand];
        c->hand = (c->hand + 1) % c->n;
        if (!e->ref) return e;     // unused since the last sweep
        e->ref = 0;                // second chance
    }
}

The hit path is one store to a bit, with no lock and no pointer movement, and the order is approximate: CLOCK distinguishes only "used since the hand last passed" from "not used". PostgreSQL's buffer manager runs a generalised clock sweep, with a usage count per buffer capped at 5 and decremented on each pass.

Lazy Promotion

Exact LRU can be kept while bounding list writes, by refusing to promote an entry that was promoted recently. A popular key stays near the head anyway, so moving it again on each of thousands of hits per second changes nothing but lock traffic.

value_t *get(lru *c, key_t k) {
    entry *e = map_get(c->index, k);
    if (!e) return NULL;
    if (now() - e->bumped > BUMP_INTERVAL) {   // memcached: 60 s
        lock(&c->list_lock);
        unlink(e); push_front(c, e);
        e->bumped = now();
        unlock(&c->list_lock);
    }
    return &e->val;
}

Memcached bumps an item at most once every 60 seconds. Other caches shard the list by key hash, or record hits in a buffer and apply them in batches under the lock.

Sampled Eviction

Redis does not keep a recency list at all. Each object carries a 24-bit LRU clock, and when memory runs out Redis samples a few keys at random and evicts the one idle longest.

robj *pick_victim(dict *keys) {
    robj *best = NULL;
    for (int i = 0; i < maxmemory_samples; i++) {   // default 5
        robj *o = random_key(keys);
        if (!best || idle(o) > idle(best)) best = o;
    }
    return best;
}

The saving is two pointers per key across a keyspace of millions. The cost is accuracy, which Redis recovers partly with a pool of 16 best candidates kept across rounds; raising the sample count to 10 brings the result close to true LRU at more CPU per eviction.

Engineering Trade-offs

An LRU cache gives O(1) expected get, put, and eviction, a single tunable parameter, and the inclusion property that makes its hit rate predictable from a trace. Sleator and Tarjan showed, with an amortized argument, that it is c-competitive: on any sequence it incurs at most c times the misses of Belady's offline optimum with the same capacity, and no deterministic online policy does better in that model.

The costs are two pointers and a map slot per entry, a shared write on every hit, and no defence against scans or loops slightly larger than the cache. Practical caches therefore approximate it: CLOCK and sampling remove the per-hit write, and 2Q or midpoint insertion add the admission test that pure recency lacks.

Applications

The Linux kernel reclaims page-cache memory from per-memory-cgroup LRU lists: a page enters the inactive list on first access and is promoted to the active list on a second, so a streamed file does not evict the working set. Since 6.1 the kernel can instead use the multi-generational LRU, which groups pages into age generations scanned through page-table accessed bits.

CPU caches use pseudo-LRU within each set: an 8-way set keeps seven bits arranged as a binary tree, each pointing away from the more recently used half, which approximates LRU without storing a full order. Varnish evicts cached HTTP objects in LRU order when its storage fills, and memcached's segmented hot, warm, and cold LRUs decide which items are reclaimed for new writes.

Summary

An LRU cache pairs a hash map, which finds an entry by key, with a doubly linked list, which orders entries by last use. A hit unlinks the entry and pushes it to the head; a miss on a full cache evicts the tail; both are O(1) expected. Because a larger LRU cache always contains a smaller one, one pass of stack distances gives the hit rate at every capacity.

The costs are a pointer pair per entry, a shared write per hit, and total failure on loops and scans just larger than the cache. Production systems keep the recency idea and change the mechanics: 2Q and midpoint insertion for scan resistance, CLOCK and sampling to remove per-hit writes, and lazy promotion to bound lock traffic.

The LRU Cache: A hash map to find each entry and a linked list to remember which one was used last
The LRU Cache — A hash map to find each entry and a linked list to remember which one was used last.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Belady, L. A. (1966). A study of replacement algorithms for a virtual-storage computer. IBM Systems Journal, 5(2), 78–101. doi.org/10.1147/sj.52.0078
  2. Mattson, R. L., Gecsei, J., Slutz, D. R., & Traiger, I. L. (1970). Evaluation techniques for storage hierarchies. IBM Systems Journal, 9(2), 78–117. doi.org/10.1147/sj.92.0078
  3. Sleator, D. D., & Tarjan, R. E. (1985). Amortized efficiency of list update and paging rules. Communications of the ACM, 28(2), 202–208. doi.org/10.1145/2786.2793
  4. O'Neil, E. J., O'Neil, P. E., & Weikum, G. (1993). The LRU-K page replacement algorithm for database disk buffering. SIGMOD 1993, 297–306. doi.org/10.1145/170035.170081
  5. Johnson, T., & Shasha, D. (1994). 2Q: A low overhead high performance buffer management replacement algorithm. VLDB 1994, 439–450. www.vldb.org/conf/1994/P439.PDF

Applications and implementations

  1. MySQL. InnoDB buffer pool: midpoint insertion strategy. dev.mysql.com/doc/refman/8.0/en/innodb-buffer-pool.html
  2. PostgreSQL Global Development Group. src/backend/storage/buffer/freelist.c — clock-sweep replacement. github.com/postgres/postgres/blob/master/src/backend/storage/buffer/freelist.c
  3. Redis. Key eviction: approximated LRU algorithm. redis.io/docs/latest/develop/reference/eviction/
  4. Memcached. Replacing the cache replacement algorithm in memcached — segmented LRU and bump interval. memcached.org/blog/modern-lru/
  5. The Linux Kernel. Multi-Gen LRU. docs.kernel.org/admin-guide/mm/multigen_lru.html
  6. Varnish Software. Storage backends — LRU eviction. varnish-cache.org/docs/trunk/users-guide/storage-backends.html

Enjoyed this chapter? Support The Ledger.