Course contents

06. Caching Lesson 6 of 8

Cache Eviction Policies

How a full cache picks what to drop: LRU live, diminishing returns of size, scans that flush hot keys, and LFU, FIFO and TTL compared.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A full cache evicts one key for every new one; the policy decides which, and with it the hit ratio.
  • LRU evicts the key unused for longest: a good default when recent reads predict the next ones.
  • Under Zipf-like popularity the hit-ratio curve flattens fast: the first slots matter most.
  • LRU is not scan-resistant: a pass over many cold keys pushes the hot set out.
  • LFU keeps frequently read keys but needs counter ageing; FIFO is cheap but ignores use; TTL bounds staleness, not memory.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An eviction policy decides which key a full cache removes to make room for a new one. Caches hold a small, hot subset of the data; as soon as memory is full, every insert has to push something out. Common policies are LRU (least recently used), LFU (least frequently used), FIFO (first in, first out), random, and hybrids such as ARC, 2Q, W-TinyLFU and S3-FIFO. Expiry by TTL is related but different: it removes keys by age whether or not memory is full.

Why it exists

Memory costs money and a cache is only useful if the keys it keeps are the ones that will be read next. A bad victim choice turns future reads into misses, and every miss costs a database read and tail latency. The policy is a prediction about the access pattern: LRU predicts that recently read keys will be read again, LFU that frequently read keys will be, FIFO makes no prediction at all.

How it works

LRU. Keys sit in a list ordered by last access (in practice a hash map plus a doubly linked list, so both lookup and reordering are O(1)). A hit moves the key to the front; an insert goes to the front; the tail is evicted. Redis does not keep an exact list: with maxmemory-policy allkeys-lru it samples a few keys (maxmemory-samples, default 5) and evicts the oldest of the sample, an approximation that saves memory.

LFU. Each key has an access counter; the key with the smallest count is evicted. Plain counters never forget, so practical implementations age them: Redis’s allkeys-lfu uses a small logarithmic counter that decays over time (lfu-decay-time), and Caffeine’s W-TinyLFU keeps a compact frequency sketch that is periodically halved, plus a small LRU "window" so new keys get a chance to prove themselves.

FIFO. Keys are evicted in insertion order. Hits change nothing, so they need no write to shared state, which makes FIFO cheap and easy to make concurrent. On its own it evicts hot keys on schedule. CLOCK (a FIFO ring with a "referenced" bit) and S3-FIFO (published at SOSP 2023: a small probationary FIFO, a main FIFO and a ghost queue) add a reuse check and get close to, or beat, LRU on many traces.

TTL. Each key carries an expiry time; expired keys count as misses and are removed lazily on access or by a background sweep. Redis’s volatile-* policies only evict keys that have a TTL, and volatile-ttl evicts those nearest to expiry first. If keys expire before memory fills, the TTL, not the eviction policy, sets the hit ratio.

Hit ratio and size. With Zipf-like popularity a small fraction of keys gets most reads, so a cache holding 10–20% of the keys can serve most of them, and each further slot holds a colder key. In the lesson’s model, 40 → 400 slots (2% → 20% of the keys) raised the hit ratio from about 35% to about 70%; 400 → 1,200 slots only to about 85%.

When to use it

  • LRU: the default for most application caches, where recency predicts reuse (sessions, product pages, API responses).
  • LFU / W-TinyLFU: a stable hot set mixed with one-off reads, scans or crawlers; in-process caches where Caffeine or a similar library is available.
  • FIFO variants (CLOCK, S3-FIFO): very high request rates where updating an LRU list on every hit is a contention point.
  • TTL: whenever data changes and staleness must be bounded; combine it with an eviction policy, not instead of one.

When not to

  • Don’t rely on LRU when large scans or batch jobs share the cache with user traffic; route them elsewhere or use a scan-resistant policy.
  • Don’t use plain LFU without ageing for data whose popularity shifts (news, trending items).
  • Don’t buy memory to fix a TTL-limited hit ratio: if the cache never fills, more memory changes nothing.
  • Don’t tune policies before measuring: a hit-ratio curve from production traces beats intuition.

Trade-offs

Policy Evicts Strength Weakness
LRU Longest unused Simple, adapts quickly to shifts Scans and one-off reads flush the hot set
LFU (with ageing) Fewest recent reads Protects a stable hot set from scans Slower to adapt; counters cost memory
FIFO Oldest insert Hits are free and lock-free Evicts hot keys unless a reuse bit is added
Random Any No metadata at all Unpredictable; usually below LRU
TTL Expired keys Bounds staleness Not a capacity policy; short TTLs cap the hit ratio

Alternatives

  • Scan isolation: send exports, backfills and analytics to a read replica or a separate cache, or read without populating the cache.
  • Admission control: don’t insert a key on its first miss (TinyLFU’s admission filter, "cache on second hit" in CDNs).
  • Bigger or tiered caches: a small in-process cache in front of a shared one, each with its own policy.
  • No eviction (noeviction): for data that must not disappear (queues, locks), Redis can reject writes when full instead of evicting.

Failure modes

  • Scan pollution: a batch job reads many cold keys once; under LRU they push out the hot keys, the hit ratio drops and the database takes both the scan and the extra misses.
  • Eviction storms: memory fills faster than expected (bigger values, a new key pattern), evictions spike and the hit ratio collapses. Watch evictions per second, not just memory used.
  • Stale popularity: plain LFU keeps last week’s hot keys and starves new ones.
  • Synchronized expiry: keys filled together with the same TTL expire together and the database takes a burst (see Cache Stampede).
  • Unbounded caches: an in-process map with no eviction grows until the process runs out of memory.

In production

Set an explicit memory limit and policy (Redis defaults to noeviction, which makes writes fail when memory is full). For Redis, allkeys-lru is a sound default, allkeys-lfu when a stable hot set competes with long-tail reads; use volatile-* only if every cacheable key has a TTL. In the JVM, Caffeine’s W-TinyLFU is the common choice. Monitor hit ratio, evictions per second, memory and the database read rate together; if possible record a sample of keys and replay it against different sizes to draw a hit-ratio curve before buying memory.

Common misconceptions

  • "Doubling the cache doubles the hit ratio." Under skewed access, each extra slot holds a colder key; returns diminish quickly.
  • "TTL is an eviction policy." TTL bounds age; eviction handles a full cache. If TTL removes keys first, the eviction policy never runs.
  • "LFU is always better than LRU." It resists scans but adapts slowly; without ageing it can be worse.
  • "Caching everything is free." Keys read once cost memory and evict keys that would have been hits.

Interview angle

Expect "how would you implement an LRU cache?" (hash map + doubly linked list, O(1) get/put) and follow-ups: thread safety (sharded locks, or FIFO/CLOCK variants with cheap hits), approximate LRU in Redis, and which policy you would pick for a given workload. Strong answers connect the policy to the access pattern, mention scan resistance and admission (TinyLFU), separate TTL from eviction, and size the cache from a hit-ratio curve rather than a guess.

Model assumptions

The simulation is a simplified model, not a benchmark. Shoppers read 2,000 products with Zipf(1) popularity at 500 requests per second; only reads are modelled. The Catalog API (64 workers) asks the cache first and reads the database on a miss, then inserts the key (cache aside). The cache is an exact LRU answering in about 1 ms; with a TTL, an expired key counts as a miss. The database has 8 connections and a 20 ms mean read (lognormal), about 400 reads per second; waiting more than 300 ms for a connection fails the query. The nightly export reads 20,000 keys uniformly at random at 250 per second through the same cache. The engine implements only LRU eviction and TTL expiry: the LRU, LFU and FIFO slot animations are scripted illustrations, not simulated. The hit-ratio tile counts all lookups since the simulation started; the numbers in the steps are measured per client after warm-up. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A full cache has to throw something out

    Shoppers read 2,000 products at 500 requests per second; a few products are very popular, most are rarely viewed. The Catalog API asks the cache first and reads the database on a miss, then stores the value.

    The cache has room for only 40 keys. Once it is full, every miss that stores a new value must evict an old one. Which one it picks is the eviction policy, and it decides the hit ratio. Here only about a third of reads hit, and the database is around 80% busy with the rest.

    Scene: Shoppers call the Catalog API, which checks a 40-key LRU cache and reads the database on a miss. About a third of reads hit the cache; the database is around 80% busy.

    Key idea: Memory is finite: a full cache evicts a key for every new one, and the choice of victim sets the hit ratio.

  2. 2. Least recently used

    The cache uses LRU: it keeps keys ordered by when they were last read. A hit moves the key to the front. A miss loads the value from the database, inserts it at the front, and evicts the key at the tail, the one nobody has read for the longest time.

    The four slots on the right are a scripted illustration of that ordering (not simulated): product:42 is read and jumps to the front, then a missed product is loaded and the tail key falls out. Popular keys keep getting pushed back to the front, so they survive. The live traffic is the simulated 40-key LRU.

    Scene: An illustration next to the cache shows four slots ordered from most to least recently used. A read moves product:42 to the front; a miss loads a new key from the database into the front slot and the tail key moves to Evicted. Live traffic continues through the 40-key LRU cache.

    Key idea: LRU bets that what was used recently will be used again soon: hits move to the front, the tail is evicted.

  3. 3. Ten times the memory

    We give the cache room for 400 keys (20% of the catalogue). The popular products now stay resident and far fewer reads reach the database.

    The hit ratio climbs from about a third to roughly 70%, and the database drops from around 80% busy to about 40%. Ten times the memory bought about 35 points of hit ratio.

    Scene: The cache now holds 400 keys. About 70% of reads hit and the database is around 40% busy.

    Key idea: With skewed popularity, a cache holding a fifth of the keys can serve most reads.

  4. 4. Each extra gigabyte buys less

    Tripling again to 1,200 keys (60% of the catalogue) raises the hit ratio only to about 85%: around 15 more points for three times the memory, after 35 points for the first tenfold.

    The extra slots hold products that are rarely read, so each one adds little. Under Zipf-like popularity the hit-ratio curve flattens quickly. Size a cache from a measured hit-ratio curve, not by "as big as we can afford".

    Scene: The cache holds 1,200 keys. About 85% of reads hit, a smaller gain than the first tenfold increase. The database is lightly loaded.

    Key idea: Hit ratio grows roughly logarithmically with size under skewed access: the first keys matter most.

  5. 5. A scan flushes the hot keys

    The team settles on 400 keys to save memory. Then a nightly export starts reading through all 20,000 catalogue records (including archived ones) at 250 per second, through the same API and cache.

    Each export read is a miss that inserts a key nobody will read again, and under LRU a fresh key goes to the front, ahead of the shoppers’ hot products. The hot keys get evicted between reads, so the shoppers’ hit ratio drops from about 70% to about 60%. The database now takes the export’s misses plus the shoppers’ extra misses: it saturates and some requests fail.

    Scene: A nightly export reads 250 rarely used records per second through the same cache. Its keys fill the front of the LRU order and push the shoppers’ popular products out; the shoppers’ hit ratio falls and the database saturates, with some requests failing.

    Key idea: LRU is not scan-resistant: one pass over many cold keys pushes the hot set out.

  6. 6. Least frequently used

    We pause the export and look at another policy. LFU evicts the key with the fewest reads. A key the export touched once has a count of 1, so it is the next to go; product:1 with thousands of reads never moves.

    The slots are a scripted illustration (the simulated cache is still LRU): export keys keep cycling through the bottom slot while the hot keys stay. The catch is old popularity: a product that was hot last month keeps its big count and squats in memory. Real LFU caches age their counters (Redis’s allkeys-lfu decays them; Caffeine’s W-TinyLFU keeps a compact, periodically halved frequency sketch).

    Scene: The export is paused. The illustration shows four slots labelled with read counts; new export keys enter the bottom slot and are evicted again, while the frequently read products stay. The simulated cache behind it is still LRU.

    Key idea: LFU resists scans by keeping frequently read keys, but needs counter ageing or it clings to yesterday’s hits.

  7. 7. First in, first out

    FIFO evicts whatever was inserted first, regardless of how often it is read. It needs no bookkeeping on a hit, which makes it cheap and lock-friendly, but on its own it will evict product:1 just because it has been cached the longest, and the very next read misses and reloads it.

    This is a scripted illustration too. Plain FIFO usually loses to LRU on skewed traffic; designs such as S3-FIFO (2023) add a small probation queue and a "was it read again?" bit to close that gap while keeping FIFO’s cheap hits.

    Scene: The illustration shows slots in insertion order. A new key is added at the end and the oldest key, the popular product:1, moves to Evicted; the next read of product:1 goes to the database. The simulated cache is still LRU.

    Key idea: FIFO ignores use entirely: cheap, but it evicts hot keys on schedule unless combined with a reuse check.

  8. 8. Expiry is not eviction

    A TTL removes a key after a fixed time, whether or not the cache is full; eviction only happens when memory runs out. They answer different questions: TTL bounds staleness, eviction handles capacity.

    We give the cache room for all 5,000 keys it could ever need but a 1-second TTL. The hit ratio falls to about 55%, below the 400-key cache without a TTL, and a 400-key cache with the same TTL gets the same hit ratio: keys expire long before memory fills, so size no longer matters. Redis’s volatile-ttl policy is different again: when memory is full it evicts the keys closest to expiry first.

    Scene: The cache has room for 5,000 keys but every entry expires after 1 second. About 55% of reads hit, fewer than with 400 keys and no TTL; the cache never fills, so expiry, not eviction, limits the hit ratio.

    Key idea: If keys expire before they would be evicted, the TTL, not the cache size or policy, sets the hit ratio.

  9. 9. Choosing a policy

    The cache is back to 400 keys, LRU, no TTL. LRU is a good default for recency-heavy traffic; LFU-style policies (W-TinyLFU, Redis LFU with decay) protect a stable hot set from scans; FIFO variants trade a little hit ratio for very cheap hits; TTLs bound staleness, not memory.

    Whatever you pick: keep scans and batch jobs out of the shared cache (or read a replica), watch the eviction rate next to the hit ratio, and size from a hit-ratio curve.

    Scene: Shoppers read through the Catalog API and a 400-key LRU cache without TTL; the export is paused. About 70% of reads hit and nothing fails.

    Key idea: Pick the policy for your access pattern, and keep one-off scans out of the cache that serves your users.