Skip to main content
03

Design an LRU cache

MediumHash mapLinked listTTLThread safety

Design an LRU (least recently used) cache: a fixed-capacity key-value store where get and put run in O(1), and when the cache is full, the entry that was used least recently is evicted.

A typical framing: "Implement the class, explain the data structures, then tell me how you'd add expiration (TTL), make it safe for many threads, and what changes if the cache has to be shared across servers."

TL;DR

Combine a hash map (key → node) for O(1) lookup with a doubly linked list that keeps entries in usage order: most recent at the head, least recent at the tail. get moves the node to the head; put inserts at the head and, if over capacity, removes the tail. Both are O(1) because a doubly linked list can unlink any node given a pointer to it, and sentinel head and tail nodes remove the edge cases.

Extensions the interviewer usually asks about: TTL (store an expiry per entry, check it lazily on get plus a periodic sweep), thread safety (one lock is simplest; sharding into N independently locked caches scales better), and distributed caching (Redis or Memcached with consistent hashing; Redis uses an approximate LRU that samples keys).

1. Requirements

Questions worth asking:

  • Is capacity a number of entries or a total size in bytes?
  • What does get return on a miss?
  • Do entries expire after a time (TTL)?
  • Single thread or many threads? In one process or shared between servers?
  • Do we need hit-rate metrics or an eviction callback?

Functional

  • get(key) returns the value or a miss, and marks the key as recently used.
  • put(key, value) inserts or updates, and evicts the least recently used entry when full.
  • Optional: delete(key), TTL per entry.

Non-functional

  • O(1) time for get and put.
  • O(capacity) memory.
  • Correct under concurrent access when required.

2. Entities and classes

Loading diagram...
  • Node: key, value, prev, next (and expiresAt for TTL). The node stores its key so that evicting the tail can also delete it from the map.
  • LRUCache: capacity, the map, and the two sentinels.

Why not other structures? A plain array or singly linked list needs O(n) to remove from the middle. A priority queue by timestamp makes get O(log n). In JavaScript a Map keeps insertion order, so deleting and re-inserting a key is a valid shortcut, but interviewers usually want to see the linked list.

3. API

ts
interface Cache<K, V> {
  get(key: K): V | undefined
  put(key: K, value: V, ttlMs?: number): void
  delete(key: K): boolean
  readonly size: number
}

4. Core logic

ts
class Node<K, V> {
  prev: Node<K, V> | null = null
  next: Node<K, V> | null = null
  constructor(
    public key: K,
    public value: V,
    public expiresAt = Infinity,
  ) {}
}

class LRUCache<K, V> implements Cache<K, V> {
  private map = new Map<K, Node<K, V>>()
  // Sentinels: real nodes always have a prev and a next, so no null checks.
  private head = new Node<K, V>(null as K, null as V)
  private tail = new Node<K, V>(null as K, null as V)

  constructor(
    private capacity: number,
    private now = () => Date.now(),
  ) {
    if (capacity < 1) throw new RangeError('capacity must be at least 1')
    this.head.next = this.tail
    this.tail.prev = this.head
  }

  get size() {
    return this.map.size
  }

  get(key: K): V | undefined {
    const node = this.map.get(key)
    if (!node) return undefined
    if (node.expiresAt <= this.now()) {
      this.remove(node)
      return undefined
    }
    this.moveToFront(node)
    return node.value
  }

  put(key: K, value: V, ttlMs?: number): void {
    const expiresAt = ttlMs === undefined ? Infinity : this.now() + ttlMs
    const existing = this.map.get(key)
    if (existing) {
      existing.value = value
      existing.expiresAt = expiresAt
      this.moveToFront(existing)
      return
    }
    if (this.map.size === this.capacity) this.remove(this.tail.prev!) // evict LRU
    const node = new Node(key, value, expiresAt)
    this.map.set(key, node)
    this.insertAfterHead(node)
  }

  delete(key: K): boolean {
    const node = this.map.get(key)
    if (!node) return false
    this.remove(node)
    return true
  }

  private remove(node: Node<K, V>) {
    node.prev!.next = node.next
    node.next!.prev = node.prev
    this.map.delete(node.key)
  }

  private insertAfterHead(node: Node<K, V>) {
    node.prev = this.head
    node.next = this.head.next
    this.head.next!.prev = node
    this.head.next = node
  }

  private moveToFront(node: Node<K, V>) {
    node.prev!.next = node.next
    node.next!.prev = node.prev
    this.insertAfterHead(node)
  }
}

The clock is injected (now) so TTL can be tested without waiting.

5. Edge cases and extensions

  • Capacity 0 or negative: reject in the constructor.
  • Updating an existing key counts as a use: it moves to the front and doesn't evict anything.
  • TTL: lazy expiration on get is O(1), but expired entries that are never read still use memory. Add a periodic sweep from the tail, or keep a min-heap of expiry times.
  • Size in bytes: track the total size and evict from the tail in a loop until the new entry fits.
  • Thread safety:
    • One mutex around get and put. Note that even get writes (it moves a node), so a read-write lock doesn't help much.
    • Better throughput: shard by hash(key) % N into N caches, each with its own lock.
    • Production libraries (Caffeine in Java) buffer the "was used" updates and apply them in batches to avoid lock contention.
  • Other eviction policies: LFU (least frequently used) protects popular keys from a one-time scan; TinyLFU and W-TinyLFU combine both and get better hit rates.
  • Distributed cache: Redis or Memcached, with keys spread by consistent hashing. Redis's allkeys-lru policy is approximate: it samples a few keys and evicts the oldest among them, which saves the memory of a full linked list.

Common follow-ups

  • "Why a doubly linked list and not singly?" To unlink a node in O(1) you need its predecessor. With a singly linked list you'd have to search for it.
  • "How would you avoid a cache stampede?" When a popular key expires, many requests miss at once and all hit the database. Let only one request recompute the value (a lock per key, or "single flight") while the others wait or get the stale value.
  • "Write-through or write-back?" Write-through updates the cache and the database together (simpler, consistent). Write-back writes to the cache and flushes later (faster writes, but data can be lost on a crash).

What interviewers look for

  • The hash map + doubly linked list combination, and why each part is needed.
  • Clean pointer handling, ideally with sentinel nodes.
  • Correct handling of updates, eviction and capacity edge cases.
  • Sensible TTL and concurrency extensions (locking, sharding).
  • Knowing how real systems (Redis, Caffeine) approximate LRU.

Was this helpful?