AlgoViz

Cache eviction policies

easy 22 min

A cache has a memory limit.

Chapter mnemonic

Three cache eviction policies

First through the door. Longest since a visit. Fewest visits.

Maya arrived first, Leo last visited longest ago, and Jo visited least. Who leaves under each policy?

FIFO evicts Maya, LRU evicts Leo, and LFU evicts Jo.

Video lesson · Chapter 1 of 5

Three shelves and a recency list

0:00 / 5:17

Cache eviction in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A cache keeps copies of values in fast, limited memory. Sooner or later it is full. Eviction is the removal of a value to make room, and the eviction policy is the rule that chooses which one.

Evicting is not data loss. The value still exists in the database, so the only price is a slower read if somebody asks for it again. A good policy evicts values nobody asks for again.

Why it exists

Nobody knows the future, so a policy must guess from the past: what was used recently, what was used often, what is oldest, or what expires soonest. Real traffic is uneven, and a small share of keys usually receives most of the reads.

The guess matters more than it looks. If the hit rate rises from 90% to 95%, the share of reads that reach the database falls from 10% to 5%. Half of the database load disappears without buying any memory.

A short history

  1. 1993

    The LRU-K paper proposes ranking database pages by their K-th most recent use, so that one lucky read does not make a page look hot.

  2. 2003

    The Adaptive Replacement Cache (ARC) is presented at USENIX FAST. It keeps re-balancing between recency and frequency by itself.

  3. 2015

    The TinyLFU paper describes a compact frequency sketch that decides whether a new value deserves a place at all.

  4. October 2018

    The memcached project describes its segmented LRU (hot, warm, cold), the default since version 1.5.0.

Words to know

Hit
The value was in the cache.
Miss
It was not, so it must be fetched from the source.
Capacity
The most entries or bytes the cache may hold.
Victim
The value chosen to leave.
Recency
How long ago a value was last used.
Frequency
How often a value has been used.
Scan
A read of many keys once each, such as a nightly export.
Admission
Deciding whether a new value may enter at all.

How it works

Step through the idea, or press Play.

Step 1 of 3

The cache fills up. Every miss adds a value until the memory limit is reached

Understand it

Start here

The toy shelf

Imagine a small toy shelf with four places. All four are taken, and a child gets a new toy. One toy must leave. Which one? That question is cache eviction.

One toy must leave
AWAY BOXFour places, four toys

No rule is always right. A good rule makes few trips to the box.

The problem

Why caches must forget

Memory is limited and the data is not. At 70% full there is still room and no decision to make. At 100% every new value forces one.

A small cache beside a big database

Users send requests to one app server. The app server reads from and fills a cache on one machine with a memory limit of 8 GB. Only on a miss does it query the database, which holds all 100 GB.
The cache machine holds 8 GB of the 100 GB. The database keeps every value, so an eviction costs time, not data.

Storing a value

Why one hit-rate point matters

T=h⋅tc+(1−h)(tc+td)h=0.90:6 msh=0.95:3.5 msT = h \cdot t_c + (1-h)(t_c + t_d) \qquad \begin{aligned} h=0.90 &: 6\text{ ms}\\ h=0.95 &: 3.5\text{ ms}\end{aligned}
With an assumed cache time of 1 ms and database time of 50 ms. Going from 90% to 95% also halves the queries that reach the database.

Four common policies

  • LRU

    Least recently used: evict the entry not accessed for the longest time.

  • LFU

    Least frequently used: evict the entry with the lowest access count.

  • FIFO

    First in, first out: evict the entry that was inserted first.

  • TTL

    Time to live: evict the entry that is closest to expiry.

Recency

LRU: least recently used

LRU assumes that something used recently will be used again soon. This property of real programs is called temporal locality.

How it works

  1. 1

    Remember the order of use

    Keep the entries in a list, most recent at one end. No clock is needed.

  2. 2

    On each access

    Move the entry to the recent end.

  3. 3

    When full

    Remove the entry at the other end. With A, B, C, D, E from newest to oldest, E leaves next.

Best for

  • Web page caching
  • Database query results
  • General purpose caching

Limitations

  • A sequential scan pushes out hot entries
  • It ignores how often an entry is used

Frequency

LFU: least frequently used

LFU assumes that popular entries stay popular. Each entry has a counter. The lowest counter leaves, and ties are usually broken by recency.

Who leaves next?

EntryAccessesDecision
A15stays
B8stays
C3stays
D1leaves next
E5stays

Best for

  • A CDN with clearly popular content
  • Finding hot data
  • Stable access patterns

Limitations

  • Yesterday's star keeps its high count
  • New entries start low and leave quickly
  • More complex than LRU

Age

FIFO: first in, first out

FIFO is a queue. New entries join at the back and the front leaves, however often it was read. A hit changes nothing, which makes reads cheap and easy to run in parallel.

FIFO is a line

A entered first, so A leaves first, even if it is the most popular entry.

Best for

  • Simple implementations
  • Streams, where age is importance
  • Building blocks inside newer policies

Limitations

  • Ignores access patterns
  • Can evict hot data
  • Often a lower hit rate than LRU

Expiry

TTL: two different jobs

A time to live makes an entry invalid after a while. That is expiry: it happens even when the cache is half empty. A TTL can also choose a victim when the cache is full: take the entry with the shortest remaining time. That is eviction.

Remaining time

EntrySeconds leftState
A300fresh
B120fresh
C10leaves next
D60low
E180fresh

Best for

  • Session tokens
  • Data that changes in real time
  • Rate-limit counters
  • DNS answers

Limitations

  • The right TTL is hard to choose
  • A useful entry may leave
  • Absolute expiry times need clocks that agree

The steps are simple: set an expiry when storing, treat an expired entry as a miss, sweep old entries in the background, and optionally renew the time on access. Choosing the time is a topic of its own: cache TTL.

Compare

The same requests, four answers

Three places. The requests are A B C A A D A E A B. The last row is the best possible result: Bélády's algorithm evicts the entry whose next use is furthest away. It needs the future, so it is only a yardstick.

PolicyHits of 10Evicted, in order
FIFO3A, B, C, D
LRU4B, C, D
LFU, LRU on ties4B, C, D
Best possible5C, D
FIFO threw out A, the busiest entry, because it arrived first.

When to use which

PolicyUse whenAvoid when
LRURecently used means likely used againSequential scans and one-time reads
LFUHot and cold data are clearly differentAccess patterns change often
FIFOOlder data is naturally less relevantThe same entries are read again and again
TTLData has a natural expiryExpiry time is unpredictable

Choosing a policy

Trouble

Scans, and the policies that survive them

A nightly export reads a million rows once. LRU treats each as the newest and pushes every hot entry out. In a small trace, A A B B C D A B E A B with three places, LRU and FIFO get 4 hits, while LFU gets 6, which is the best possible here.

Common answers

  1. 1

    Segmented LRU

    New entries wait on probation. Only a second use promotes them. memcached uses hot, warm and cold parts.

  2. 2

    LRU-K

    Rank by the K-th last access instead of the last one.

  3. 3

    Admission filter

    Compare the newcomer's estimated frequency with the victim's and refuse the weaker one. Caffeine uses Window TinyLFU.

  4. 4

    Skip the cache

    Let batch jobs read without storing. Often the simplest fix.

A probation area protects hot keys

In products

What Redis really does

Redis does not keep a perfect LRU list. It samples a few keys and evicts the best candidate; maxmemory-samples is 5 in the documented example. That is close enough to LRU and cheaper in memory.

Redis policies by family

FamilyCandidatesNote
noevictionnoneCommands that add data fail when memory is full
allkeys-lru, -lfu, -randomevery keyNormal choice for a pure cache
volatile-lru, -lfu, -randomkeys with a TTLBehaves like noeviction if no key has a TTL
volatile-ttlkeys with a TTLShortest remaining time first
On 64-bit systems the default is no memory limit, so set maxmemory yourself.

Numbers

How many entries fit?

Capacity

N=memory for datakey+value+overhead=8×10950+850+100=8,000,000N = \frac{\text{memory for data}}{\text{key} + \text{value} + \text{overhead}} = \frac{8 \times 10^{9}}{50 + 850 + 100} = 8{,}000{,}000
8 GB and assumed sizes in bytes. Measure the overhead of your product. Leave headroom for replication buffers and fragmentation.

What to watch

  1. 1

    Hit rate

    Hits divided by hits plus misses, per key group if you can.

  2. 2

    Evictions per second

    A steady few are normal. A jump means a scan, a traffic shift or too little memory.

  3. 3

    Age of the victim

    If evicted entries were used seconds ago, the cache is too small.

  4. 4

    Expired versus evicted

    Many expiries and few evictions mean memory is not your limit; the TTL is.

Common combinations

PairWhat it gives
LRU + TTLRecency with automatic expiry: the usual start
LFU + TTLFrequency with time-based clean-up
LRU-KRecency of the K-th last access, a mix of both

Eviction is one half of keeping a cache useful. The other half is filling it: see cache-aside, and distributed caching for more memory than one machine has.

Summary

The whole topic in one minute.

A full cache must drop something. LRU drops what was used longest ago, LFU what was used least often, FIFO what arrived first, and TTL-based eviction what would expire soonest. Each is a guess about the future.

Start with LRU plus a TTL. Move to a frequency-aware policy when scans or one-time reads push out hot keys. Measure the hit rate and the eviction rate, and remember that the largest gain may be a bigger cache or fewer useless entries.

  • Eviction removes a copy, never the source.
  • LRU guesses by recency, LFU by frequency, FIFO by age, TTL by expiry.
  • Expiry happens because of time; eviction happens because of space.
  • Scans break plain LRU: use probation, admission or skip the cache.
  • Start with LRU plus TTL, then let the hit rate decide.

Sources