Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Systems · Caching

Who to Evict?

A cache that’s full has to throw something out to make room — and which thing it evicts is the whole game. Race three classic policies on the exact same access stream, same size: FIFO evicts whatever was inserted longest ago (ignoring how it’s used), LRU evicts the item that hasn’t been touched for the longest time (recency), and LFU evicts the item accessed the fewest times (frequency). On a workload with one hot key surrounded by a rotating scan, LFU protects the hot key while LRU and FIFO keep evicting it during each scan — so their hit rates pull apart. Step the stream and watch three caches disagree.

FIFO (oldest) · LRU (least recently used) · LFU (least frequently used) — same stream, different evictions
capacity

How many items the cache can hold. When full, an access to a new key forces an eviction.

FIFO

Evict the item inserted longest ago — ignores whether it’s still being used.

LRU

Evict the least-recently-used item — recency-aware; the classic default.

LFU

Evict the least-frequently-used item — frequency-aware; protects hot keys from scans.

eviction.js — three policies, one stream
Ready
Same access stream, three caches of size 3: FIFO, LRU, LFU. Each step feeds the next key to all three; they hit or evict differently. Watch the hit counts diverge on this hot-key-plus-scan workload. Step to race.
0
FIFO hits
0
LRU hits
0
LFU hits

How it works

The three policies differ only in what they call “least valuable,” and that choice interacts with the workload. This stream is a hot key A accessed repeatedly, interleaved with a rotating scan B, C, D that alone would fill the cache. FIFO and LRU both let the scan push A out: FIFO because A was inserted early, LRU because during a scan A becomes the least-recently-touched. So every time the scan comes around, they’ve evicted A and miss on the next A. LFU instead remembers that A has been accessed far more often than any scan key, so it evicts a scan key and keeps A — turning those repeated A accesses into hits. This is exactly the “scan-resistance” problem, and it’s why real systems reach for ARC (Adaptive Replacement Cache): ARC keeps two lists — one for recency (LRU-like) and one for frequency (LFU-like) — plus “ghost” entries of recently-evicted keys, and adaptively shifts the balance between them based on which kind of miss it’s seeing. It gets LRU’s responsiveness and LFU’s scan-resistance without you tuning anything.

1

On a hit, just record it

If the accessed key is already in the cache, it’s a hit. LRU also marks it most-recently-used; LFU bumps its frequency count. FIFO leaves its insertion order untouched.

2

On a miss with room, insert

If the key isn’t cached and there’s free space, insert it. No eviction is needed yet.

3

On a miss when full, evict by policy

FIFO drops the oldest-inserted key; LRU drops the least-recently-used; LFU drops the least-frequently-used (ties broken by age). This is where the policies diverge.

✓

Match the policy to the workload

LRU suits recency-heavy access; LFU suits stable frequency and resists scans; FIFO is simplest but ignores usage. ARC adapts between recency and frequency automatically, capturing the best of both.

FIFO
oldest out
LRU
least recent out
LFU
least frequent out
ARC
adapts LRU↔LFU

The code

# three eviction policies, same interface def access(key): if key in cache: on_hit(key) # LRU: mark recent; LFU: freq += 1 return HIT if full(): victim = choose_victim() # the policy's whole identity: evict(victim) # FIFO -> oldest inserted # LRU -> least recently used # LFU -> least frequently used insert(key) return MISS

The picture: the moment LRU and LFU split

stream A A A B C D A B C D A B C D A · capacity 3 after step 5step 6: D arrivesstep 7: A arrives A B C B C D C D A A least recentmiss, evicts Amiss, evicts B A3 B1 C1 A3 C1 D1 A4 C1 D1 count beside keymiss, evicts BHIT on A 15 accesses: FIFO 2 hits · LRU 2 · LFU 5 LRULFU
Dashed boxes are the next victim. LRU keeps its keys oldest-touched first, so after the scan B, C the hot key A sits at the front and D pushes it out. LFU ranks by count instead: A has 3, B and C have 1, so D evicts B (the older of the two count-1 keys) and A survives to hit on step 7.

Worked example: all 15 steps of the race

The lab’s exact stream, capacity 3. FIFO is left out of the table because on this stream it makes the same choice as LRU at every step: its only hits come on steps 2 and 3, before order matters. LRU lists keys oldest-touched first; LFU shows each key with its count.

StepKeyLRU afterLRULFU afterLFU
1AAmissA1miss
2AAhitA2hit
3AAhitA3hit
4BA BmissA3 B1miss
5CA B CmissA3 B1 C1miss
6DB C Dmiss, evict AA3 C1 D1miss, evict B
7AC D Amiss, evict BA4 C1 D1hit
8BD A Bmiss, evict CA4 D1 B1miss, evict C
9CA B Cmiss, evict DA4 B1 C1miss, evict D
10DB C Dmiss, evict AA4 C1 D1miss, evict B
11AC D Amiss, evict BA5 C1 D1hit
12–14B C Dsame cycle3 missessame cycle3 misses
15AC D Amiss, evict BA6 C1 D1hit

Totals: LRU 2 hits, LFU 5, out of 15. Two things stand out. After step 3, LRU never hits again: four keys cycle through three slots, so each key is always evicted just before it comes back. And LFU is not perfect either: the scan keys B, C and D never score a single hit, because each newcomer starts at count 1 and evicts the newcomer before it. LFU wins only because A is worth protecting.

Cost and trade-offs: what each policy keeps per key

Here Time is the work per access, Space is the bookkeeping per cached key.

CaseTimeSpaceWhy
FIFOO(1): hash map + queueone queue slotA hit changes nothing, so reads never write. Cheapest under heavy concurrency.
LRUO(1): hash map + doubly linked listtwo list pointersEvery hit moves the key to the front, so every read is a write to shared state.
LFU, as in this labO(capacity) per evictiona count and a timestampThe lab scans every key to find the lowest count. Fine for 3 slots, not for 3 million.
LFU, productionO(1) with one list per count; O(log n) with a heapa count, plus agingCounts must decay or a once-hot key camps in the cache forever.
ARCO(1)up to c ghost keys on top of c cachedGhosts are keys only, no values. They tell ARC which kind of eviction was a mistake.
Sampled LRUO(k) for k sampled keysa last-access timeRedis evicts the best of a small random sample instead of keeping a list at all.

The LRU row explains why big systems rarely run exact LRU. A list that every read must lock and reorder becomes the bottleneck long before memory does, so they approximate it: CLOCK (a reference bit per slot and a sweeping hand) or sampling.

Common mistakes

  • Using LRU when the loop is bigger than the cache

    A cycle over c + 1 keys gives LRU zero hits after warm-up. That is steps 4 to 15 above: four keys, three slots, no LRU hits. Batch jobs that re-read a table slightly larger than the cache hit this exactly.

  • LFU without aging

    Counts only go up, so a key that was hot last week keeps its high count and can never be evicted. Real LFU caches decay counts over time or halve them periodically.

  • Forgetting that newcomers are LFU’s first victims

    A new key starts at count 1, the lowest possible. In the trace, every scan key evicted the scan key before it and none ever hit. If your workload’s new keys are the valuable ones (a news feed, a deploy), plain LFU fights it.

  • Treating an LRU hit as a free read

    Exact LRU writes to a shared list on every hit. Under many threads that list, not the hash map, sets the throughput ceiling. Shard the cache or use an approximation.

  • Counting hits instead of cost

    All three policies treat every miss as equal. If one key is 1 MB and slow to rebuild while others are 1 KB, hit rate can rise while latency gets worse. Benchmark on a replay of real traffic, not a toy stream like this one.

Where this shows up in production and interviews

  • Redis

    maxmemory-policy picks the policy: allkeys-lru, allkeys-lfu, their volatile-* variants, or random. Both LRU and LFU are approximated by sampling a few keys, and the LFU mode uses a small counter that decays over time.

  • Databases and file systems

    ZFS caches with ARC, the policy the page describes. PostgreSQL’s buffer pool uses a clock sweep with usage counts. The Linux page cache keeps active and inactive lists, so a page read once has to be touched again before it is protected.

  • Application caches

    Caffeine, the common Java cache, uses W-TinyLFU: a small LRU window for newcomers plus a compact frequency sketch that admits a new key only if it looks more popular than the victim. That fixes both LFU mistakes above.

  • Interviews

    “Design an LRU cache” (LeetCode 146) wants a hash map plus a doubly linked list for O(1) get and put. The harder follow-up, LFU (LeetCode 460), wants one list per count and a pointer to the minimum count. Expect to be asked why LRU fails on a scan.

Quick check

1. Which item does LRU evict when the cache is full?

2. Why does LFU beat LRU on a hot-key-plus-scan workload?

3. What does ARC (Adaptive Replacement Cache) do?

FAQ

What is a cache eviction policy?

When a full cache must store a new item, the eviction policy decides which existing item to remove. Common ones: FIFO (oldest inserted), LRU (least recently used), LFU (least frequently used), and adaptive schemes like ARC. The best choice depends on the access pattern — recency-heavy favors LRU, stable-frequency favors LFU.

When is LRU better than LFU, and vice versa?

LRU wins on recency-dominated access and shifting working sets. LFU wins when some items are persistently popular and must survive bursts/scans — but naive LFU can cling to once-popular items (needs aging). ARC and LRU-K aim to capture both.

What is scan resistance?

A cache’s ability to keep its hot items when a big one-time scan of many distinct keys passes through. Plain LRU isn’t scan-resistant (a scan evicts hot items); LFU and ARC are, because they weigh frequency, so a single scan pass can’t displace long-accessed items.

How does ARC work?

ARC splits the cache into two LRU lists — T1 (seen once, recency) and T2 (seen ≥ twice, frequency) — plus ghost lists B1/B2 of recently-evicted keys. A miss on a ghost entry tells ARC it evicted too eagerly, so it adjusts a target size p that shifts capacity between T1 and T2 — self-tuning between recency and frequency with no manual parameters.

Keep going

Finished this one? 0 / 61 Labs done
NextBackpressure: The Bounded Queue Next on the “Storage, caching and backpressure” ladder · rung 4 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs