# LRU cache and eviction policies (https://layerscache.com/docs/learn/lru-cache)

> An LRU cache evicts the least recently used key when full. Implement one in TypeScript with a Map and a linked list, then compare LFU, FIFO, SIEVE and S3-FIFO.



An **LRU cache** (least recently used cache) is a cache with a fixed size that, when it is full, removes the entry that has gone unused the longest to make room for a new one. Every read or write counts as a use. LRU is the idea behind most in-memory caches and a classic interview question.

**Level:** zero to one · &#x2A;*You need:** [What is caching?](/docs/learn/what-is-caching) and [the cache-aside pattern](/docs/learn/cache-aside-pattern)

## How does an LRU cache work? [#how-does-an-lru-cache-work]

An LRU cache keeps its keys in order from most to least recently used. A hit moves the key to the front. A new key goes in at the front. When the cache is over capacity, the key at the back leaves.

```mermaid
flowchart LR
  R["get or put a key"] --> F["Move it to the front"]
  F --> O["Order runs from newest to oldest"]
  N["put a new key<br/>cache is full"] --> E["Evict the key at the back"]
  E --> F
```

The bet behind LRU is that a key used recently will be used again soon. That holds for many workloads, which is why LRU is the default teaching example for cache eviction.

## Implement an LRU cache in TypeScript with a Map [#implement-an-lru-cache-in-typescript-with-a-map]

A JavaScript `Map` returns its keys in insertion order. If you delete a key and set it again, it moves to the end. So the first key in the `Map` is always the least recently used one, and `map.keys().next().value` returns it in constant time.

```ts title="lru-map.ts"
export class LRUCache<K, V> {
  #capacity: number
  #entries = new Map<K, V>()

  constructor(capacity: number) {
    if (capacity < 1) throw new RangeError('capacity must be at least 1')
    this.#capacity = capacity
  }

  get(key: K): V | undefined {
    if (!this.#entries.has(key)) return undefined
    const value = this.#entries.get(key) as V
    this.#entries.delete(key) // delete and set again to make it the newest
    this.#entries.set(key, value)
    return value
  }

  put(key: K, value: V): void {
    if (this.#entries.has(key)) {
      this.#entries.delete(key)
    } else if (this.#entries.size >= this.#capacity) {
      const oldest = this.#entries.keys().next().value as K
      this.#entries.delete(oldest)
    }
    this.#entries.set(key, value)
  }
}
```

The delete before the set matters: setting a key that already exists keeps its old position. This runs with `node lru-map.ts` on Node.js 22.18 or later. It is the same shape as LeetCode 146, "LRU Cache", where `get` returns `-1` for a miss instead of `undefined`.

## Design an LRU cache with a hash map and a linked list [#design-an-lru-cache-with-a-hash-map-and-a-linked-list]

Interviewers often want the structure underneath, because in most languages a hash map has no order. The standard answer pairs two structures. A **hash map** finds a node by key in O(1). A **doubly linked list** keeps the recency order, and a node can be unlinked and moved to the front in O(1) because it knows both of its neighbours.

Two sentinel nodes, `head` and `tail`, remove the empty-list special cases. The node after `head` is the newest, and the node before `tail` is the oldest.

```mermaid
flowchart LR
  subgraph before["Before get of C, capacity 3"]
    direction LR
    H1["head"] <--> A1["A"] <--> B1["B"] <--> C1["C"] <--> T1["tail"]
  end
  subgraph after["After get of C, then put of D"]
    direction LR
    H2["head"] <--> D2["D"] <--> C2["C"] <--> A2["A"] <--> T2["tail"]
  end
```

The `get` of C moves it next to `head`. The `put` of D finds the cache full, unlinks B from the tail side, and inserts D at the front.

```ts title="lru-list.ts"
class ListNode<K, V> {
  key: K
  value: V
  prev: ListNode<K, V> | undefined
  next: ListNode<K, V> | undefined

  constructor(key: K, value: V) {
    this.key = key
    this.value = value
  }
}

export class LRUCache<K, V> {
  #capacity: number
  #nodes = new Map<K, ListNode<K, V>>()
  #head: ListNode<K, V> // sentinel: head.next is the most recently used
  #tail: ListNode<K, V> // sentinel: tail.prev is the least recently used

  constructor(capacity: number) {
    if (capacity < 1) throw new RangeError('capacity must be at least 1')
    this.#capacity = capacity
    this.#head = new ListNode(undefined as K, undefined as V)
    this.#tail = new ListNode(undefined as K, undefined as V)
    this.#head.next = this.#tail
    this.#tail.prev = this.#head
  }

  #unlink(node: ListNode<K, V>): void {
    node.prev!.next = node.next
    node.next!.prev = node.prev
  }

  #pushFront(node: ListNode<K, V>): void {
    node.prev = this.#head
    node.next = this.#head.next
    this.#head.next!.prev = node
    this.#head.next = node
  }

  get(key: K): V | undefined {
    const node = this.#nodes.get(key)
    if (!node) return undefined
    this.#unlink(node)
    this.#pushFront(node)
    return node.value
  }

  put(key: K, value: V): void {
    const existing = this.#nodes.get(key)
    if (existing) {
      existing.value = value
      this.#unlink(existing)
      this.#pushFront(existing)
      return
    }
    if (this.#nodes.size >= this.#capacity) {
      const victim = this.#tail.prev!
      this.#unlink(victim)
      this.#nodes.delete(victim.key)
    }
    const node = new ListNode(key, value)
    this.#nodes.set(key, node)
    this.#pushFront(node)
  }
}
```

Both versions give the same answers. With capacity 2, `put(1, 1)`, `put(2, 2)`, `get(1)` returns `1`, `put(3, 3)` evicts key 2, and `get(2)` returns `undefined`. If the interviewer asks about thread safety, note that Node.js runs your JavaScript on one thread, so these methods cannot interleave. In a multi-threaded language, wrap each method in a lock.

## Why does LRU fail on scans and one-hit wonders? [#why-does-lru-fail-on-scans-and-one-hit-wonders]

LRU assumes that "used recently" means "will be used again". Two common workloads break that.

* **A scan** reads many keys once, such as a report that walks a whole table. Every scanned key becomes the newest, so the scan pushes out the popular keys that were in the cache.
* **One-hit wonders** are keys requested once and never again, such as crawler traffic or a unique search. Each one takes a slot and ejects a key that might have been worth keeping.

```ts title="scan.ts"
import { LRUCache } from './lru-map.ts'

const cache = new LRUCache<string, string>(3)
for (const hot of ['a', 'b', 'c']) cache.put(hot, 'popular')

// A report reads 10 rows once each. None of them is read again.
for (let i = 0; i < 10; i++) cache.put(`row:${i}`, 'one-time')

console.log(cache.get('a')) // undefined: the popular keys are gone
```

A hit also has a cost. LRU rewrites its list on every read, which is a write in the hottest path. Newer policies avoid that.

## LFU, FIFO, SIEVE and S3-FIFO: cache replacement policies compared [#lfu-fifo-sieve-and-s3-fifo-cache-replacement-policies-compared]

A **cache replacement policy** (or eviction policy) is the rule that picks the entry to remove. LRU is one of several.

| Policy  | Tracks                          | A hit                       | Evicts                                                | Weak spot                                              |
| ------- | ------------------------------- | --------------------------- | ----------------------------------------------------- | ------------------------------------------------------ |
| FIFO    | Insertion order                 | Nothing                     | The oldest key                                        | Ignores how often a key is used                        |
| LRU     | Recency                         | Moves the key to the front  | The least recently used key                           | Scans and one-hit wonders                              |
| LFU     | Use count                       | Adds one to the count       | The least frequently used key                         | Keys that were popular long ago stay unless counts age |
| SIEVE   | A visited bit                   | Sets the bit                | The oldest key not visited since the hand last passed | A popular set replaced all at once                     |
| S3-FIFO | Three FIFO queues and a counter | Adds one to a small counter | One-time keys from a small probation queue first      | A popular set replaced all at once                     |

**SIEVE** (Zhang et al., [NSDI 2024](https://www.usenix.org/conference/nsdi24/presentation/zhang-yazhuo)) keeps keys in insertion order. A hand moves from the oldest key toward the newest, clears visited bits, and evicts the first key it finds unvisited. A hit changes one bit and moves nothing.

**S3-FIFO** (Yang et al., [SOSP 2023](https://dl.acm.org/doi/10.1145/3600006.3613147)) uses a small queue for new keys, a main queue, and a ghost queue that remembers the hashes of keys it recently dropped. A key read again while on probation moves to the main queue. A key never read again leaves quickly without touching the main queue. That is what protects popular keys from scans.

## Which cache eviction policy should you choose? [#which-cache-eviction-policy-should-you-choose]

For a stable, skewed workload where a few keys get most of the reads, a frequency-aware or lazy-promotion policy such as S3-FIFO or SIEVE usually misses less than LRU. LFU suits data whose popularity changes slowly, such as a catalogue. Choose LRU when your popular keys are replaced all at once and the new set fits in the cache, and when you want the policy every engineer already knows. Use FIFO as a baseline to compare against.

For a deeper tour of one library's choices, see [eviction and value modes](/docs/concepts/eviction).

## Where the hand-written version breaks [#where-the-hand-written-version-breaks]

The classes above are fine for learning. In a service, a few gaps show up fast.

* **Capacity counts entries, not bytes.** Ten thousand 50 KB values and ten thousand 50 byte values use very different memory.
* **There is no expiry.** A cached value never goes stale on its own, and you still need a TTL.
* **There is no protection from stampedes.** Many callers missing one key all call the loader. See [cache stampede](/docs/learn/cache-stampede).
* **It lives in one process.** Each server has its own copy, and a delete on one does not reach the others.

You can fix these one at a time, or use a package such as `lru-cache` or `quick-lru`. They cover size limits and, in most cases, expiry, but not stampedes or the other servers.

## The same idea with getOrSet [#the-same-idea-with-getorset]

lazy-layers-cache keeps L1, the in-memory layer, bounded by entries and by bytes. The eviction policy is one option. It defaults to S3-FIFO, and `policy: 'lru'` switches it.

```ts title="cache.ts"
import { setupCache } from 'lazy-layers-cache'
import { db, type Product } from './db.ts'

const cache = await setupCache<string, Product>({
  namespace: 'catalog',
  redis: false, // memory only, no Redis needed
  levels: {
    L1: { policy: 'lru', maxEntries: 5_000, maxMemory: '256MiB' },
  },
})

export function getProduct(id: string): Promise<Product | undefined> {
  return cache.getOrSet(`product:${id}`, () => db.products.find(id))
}
```

`policy` accepts `'s3fifo'` (the default), `'lru'`, `'lfu'`, `'sieve'` and `'fifo'`. `maxEntries` caps the count, and `maxMemory` caps the bytes all caches in the process may hold together. When either limit is reached, the policy picks what to evict. You can also register your own policy.

On skewed traffic, the library measured a 78.2% hit ratio with S3-FIFO in a recorded run: Zipf traffic over 100,000 keys, with room for 10% of them. Keep the default unless your popular keys are replaced wholesale, in which case choose `lru`. The [eviction guide](/docs/concepts/eviction) has the full policy matrix, and the [configuration reference](/docs/reference/configuration) lists every L1 option.

Next lesson: [Redis cache in Node.js](/docs/learn/redis-cache-nodejs).

## Further reading [#further-reading]

* [Yang et al., FIFO queues are all you need for cache eviction (S3-FIFO), SOSP 2023](https://jasony.me/publication/sosp23-s3fifo.pdf): the paper behind the S3-FIFO policy, with its evaluation against LRU.
* [Zhang et al., SIEVE is Simpler than LRU, NSDI 2024](https://www.usenix.org/conference/nsdi24/presentation/zhang-yazhuo): an eviction algorithm that needs no lock on a cache hit.
* [Einziger, Friedman and Manes, TinyLFU](https://arxiv.org/abs/1512.00727): a frequency-based admission policy, and the paper that presents W-TinyLFU.
* [Caffeine](https://github.com/ben-manes/caffeine): a Java cache whose README lists size-based eviction based on frequency and recency.
* [lru-cache for Node.js](https://github.com/isaacs/node-lru-cache): a bounded LRU cache for JavaScript, with TTL and `fetchMethod` options.


## Questions

### What is an LRU cache?

An LRU cache is a fixed-size cache that removes the least recently used entry when it needs room. Each read or write marks the key as the newest, so the key that has gone longest without use sits at the back and is the next one evicted.

### How do you implement an LRU cache?

Use a hash map for lookups and a doubly linked list for recency order. A get moves the node to the front, and a put inserts at the front and, when full, removes the node at the tail. Both operations are O(1). In JavaScript, a Map does both jobs because it keeps insertion order.

### What is the difference between LFU and LRU?

LRU evicts the key unused for the longest time. LFU evicts the key used the fewest times. LRU adapts quickly when popularity shifts but a big scan can flush it. LFU keeps stable favourites but, without aging, holds on to keys that were popular long ago.

### Is there an npm package for an LRU cache?

Yes. The lru-cache and quick-lru packages are common choices, and lazy-layers-cache includes LRU as one of its built-in L1 policies, next to S3-FIFO, LFU, SIEVE and FIFO. Write your own to learn it or to answer an interview question, and use a package in production.

### Why is LRU not always the best cache eviction policy?

LRU treats every access as proof a key will be used again. A scan that reads many keys once, or a stream of one-hit wonders, pushes out keys that are genuinely popular. Newer policies such as SIEVE and S3-FIFO remove one-time keys faster and often miss less.

### What are cache replacement policies?

A cache replacement policy, also called an eviction policy, decides which entry to remove when the cache is full. Common ones are FIFO, LRU, LFU, SIEVE and S3-FIFO. They differ in what they track about each key and how much work a hit costs.