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.