LRU Cache Design

A fixed-size cache that evicts the least recently used entry, with O(1) get and put from a hash map and a doubly linked list.

Overview

An LRU cache holds at most capacity entries. When it is full and a new key arrives, it throws out the entry that was used longest ago. The bet is that recent use predicts future use, which holds for most caches in front of a database or an API.

The design question is one of the most common in low-level design interviews because it has a clean answer with a clear reason. Each operation must be O(1), and no single standard structure gives that: a hash map finds a key fast but keeps no order, and a list keeps order but finds a key slowly. The fix is to use both, pointing at the same nodes.

Why two structures

The cache does three things on every call. It finds a key (get(key)), it moves the key it touched to the most recent position, and, when full, it evicts the oldest key. Look at what each structure costs for those three jobs on its own.

  • A hash map alone: the lookup is O(1), but the map keeps no order, so there is nothing to move a key within and no way to know which key is oldest.
  • An array or a singly linked list: finding a key is an O(n) search, and finding and removing it to move it is O(n) too. Removing at one end is O(1).
  • A doubly linked list alone: finding a key is still an O(n) search. Once you hold the node, moving it is O(1), and removing the tail is O(1).
  • A hash map plus a doubly linked list: the map lookup is O(1). Moving a key is O(1): unlink the node and insert it at the head. Evicting is O(1): remove the tail node and its map entry.

The list has to be doubly linked because removing a node from the middle needs both its neighbors, and the map hands you the node directly, not its position. The figure shows how the two structures share the same nodes.

Interview questions

  • Walk through the O(1) design and show the shortest correct implementation.
  • How would you make the cache thread-safe, and why does a read-write lock not help?
  • Compare LRU, LFU and FIFO. When would you choose each?
  • How would you add TTL (expiry) to the cache?
  • How does this change when the cache is distributed across many machines?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio