Eviction policies
What a cache should throw away when it is full, how LRU, LFU and their production approximations work, and how to match a policy to a workload.
The problem
A team caches rendered product data in a Redis node with 64 GB of memory. The full catalogue would take about 400 GB to cache. For the first few hours everything is a success: the hit ratio climbs and the database relaxes. Then memory fills.
What happens next depends on a setting nobody looked at. With no maxmemory limit, the process grows until the operating system swaps or kills it. With a limit and Redis’s default policy, noeviction, writes that need more memory start failing with an error. Either way the cache has turned from a help into an incident.
The team’s first fixes are the obvious ones. A bigger machine postpones the problem. Shorter TTLs free memory but throw away popular and unpopular entries alike, so the hit ratio falls. What they need is a rule for choosing which entry to give up when a new one arrives, and the ideal rule is easy to state: drop the entry that will not be needed for the longest time. László Bélády described that optimal policy in 1966. It needs knowledge of the future, so no real cache can run it, but it is the benchmark. Every practical eviction policy is a guess about future reads made from past reads.
Expiry is not eviction
Two different things remove entries, and they are often confused.
- Expiry removes an entry because its TTL has passed and the value may be wrong. It is about freshness.
- Eviction removes an entry because the cache is out of memory. The value may be perfectly good.
They interact. Redis deletes an expired key lazily, when something next touches it, and also runs a background cycle that samples keys with a TTL. So expired entries can occupy memory for a while, and a cache whose keys all have short TTLs may never need to evict.
The basic policies
| Policy | Evicts | Works well when | Works badly when |
|---|---|---|---|
| LRU | The entry unused for longest | Recent use predicts reuse, which is most request traffic | Scans touch every key once |
| LFU | The entry used least often | Popularity is stable and skewed | Popularity shifts quickly |
| FIFO | The oldest inserted entry | New data is the hot data | Old entries stay popular |
| Random | Any entry | Access is close to uniform | A small hot set matters |
| TTL-based | The entry closest to expiry | TTLs reflect how valuable entries are | TTLs were chosen for freshness alone |
Least recently used (LRU) is the usual default. Request traffic has temporal locality: something read a second ago is likely to be read again. Its weakness is that a single access counts as full evidence. A batch job that reads every key once makes cold keys look hot and flushes the real hot set.
Least frequently used (LFU) counts accesses and so is not fooled by a scan. Its problems are the mirror image. Yesterday’s viral post keeps a high count long after anyone reads it, and a new entry starts at one and may be evicted before it proves itself. Practical LFU decays its counters over time.
FIFO and random keep no per-read bookkeeping at all, which makes them fast and easy to make concurrent. They ignore what is popular, so their hit ratios are usually lower, though random gets close to LRU when access is nearly uniform.
How LRU is implemented
An exact LRU needs two operations to be O(1): find an entry by key, and reorder entries by recency. One structure cannot do both, so it uses two.
- A hash map from key to a list node.
- A doubly linked list of nodes ordered by recency, most recent at the head.
get(key) looks the node up in the map, unlinks it and reinserts it at the head. put(key, value) updates and moves an existing node, or adds a new node at the head. If the cache is now over capacity, it removes the tail node and deletes that key from the map.
The list is doubly linked because unlinking a node from the middle needs its predecessor, and walking from the head to find it would be O(n). Dummy head and tail nodes remove the special cases for an empty list.
Fill the cache, read the oldest key, then add a new key, and check that the key you just read survived while a different one was evicted.
The cost that matters in production is hidden in get. Every read modifies the list, so every read needs a lock, and on a machine with many cores that lock becomes the bottleneck. There is also a memory cost of two pointers per entry. This is why almost no large cache runs exact LRU.
What production caches do
Redis: sampled LRU and LFU. Redis keeps no list. Each object carries a 24-bit field with a coarse last-access time. When it must evict, Redis samples maxmemory-samples keys (5 by default), keeps the best candidates in a small pool, and evicts the one idle longest. Raising the sample size to 10 gets closer to true LRU for more CPU. Since version 4.0 the same 24 bits can instead hold an LFU counter: a small logarithmic counter that is incremented with decreasing probability and decays over time. Policies come in two families. allkeys-* may evict any key, and volatile-* only keys that have a TTL.
Memcached: segmented LRU. Memcached keeps an LRU per slab class, which is a group of items of similar size. Since version 1.5 the default splits each one into hot, warm and cold segments maintained by a background thread, so that most reads do not have to reorder anything.
CLOCK. Entries sit in a circle and each has a reference bit. A hit sets the bit, which needs no lock and no list update. To evict, a hand sweeps round the circle. An entry with the bit set has it cleared and is skipped, and an entry with the bit clear is evicted. Operating system page caches use variants of this, and PostgreSQL’s buffer pool uses a clock sweep with a small usage counter.
W-TinyLFU. Caffeine, the common Java cache library, puts new entries in a small LRU “window”. When an entry leaves the window it competes with the entry the main region would evict next, and the one with the higher estimated frequency stays. Frequencies live in a count-min sketch, a few bits per counter, halved periodically so history fades. The effect is LRU’s quick response to new items plus LFU’s resistance to scans.
Research keeps moving here. Recent papers such as S3-FIFO (2023) and SIEVE (2024) report that simple FIFO queues with lazy promotion can match or beat LRU on web cache traces.
Choosing a policy for a workload
- A general cache with skewed access. Use
allkeys-lru. It is the sensible default and what most interviewers expect to hear. - Stable popularity, plus scans or many keys read only once. Use
allkeys-lfu, or a W-TinyLFU cache in process. - One Redis holding both cache entries and data that must not vanish (locks, queues, sessions). A
volatile-*policy with TTLs on the cache keys only will work, but separate instances are safer. - Nearly uniform access. Random is as good as anything and costs nothing.
- Values of very different sizes. Remember that evicting one 1 MB value frees room for a thousand 1 KB values. CDNs and object caches often use size-aware policies for this reason.
When should you not lean on eviction at all? When the cache holds something you cannot recompute, eviction is data loss, and the data belongs in a database. And when evictions are constant and the hit ratio is still poor, the policy is not the problem. Either the cache is too small for the working set, or the keys are too fine-grained to be reused. Measure the hit ratio and the eviction rate before changing the policy.
In the interview
Mention eviction as soon as you size a cache smaller than the data it fronts, which is nearly always. One sentence is enough at first: “The cache holds the hot 20%, with allkeys-lru eviction and a TTL as the staleness bound.”
If the interviewer digs, show three things. You know expiry and eviction are separate mechanisms. You can describe the hash map and linked list and say why real systems approximate it. And you can name the workload that breaks your choice, such as a scan for LRU or shifting popularity for LFU, and what you would switch to.
Key takeaways
- Every eviction policy is a guess about future reads based on past reads. LRU bets on recency, LFU bets on frequency.
- Expiry and eviction are different. A TTL removes an entry because it may be wrong, eviction removes one because memory is full.
- Exact LRU is a hash map plus a doubly linked list, with O(1) get and put, but every read rewrites the list and needs a lock.
- Production caches approximate. Redis samples a few keys and evicts the best candidate, CLOCK uses a reference bit, and W-TinyLFU adds a frequency-based admission test.
- LRU is hurt by scans that touch every key once. LFU is hurt by popularity that changes, unless its counters decay.
- A high eviction rate with a low hit ratio is a sizing or key-design problem that no policy will fix.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is the difference between expiry and eviction?
Expiry removes an entry because its TTL says it may no longer be correct. Eviction removes an entry, possibly a perfectly good one, because the cache needs the memory.
Which two data structures make an O(1) LRU cache, and what does each do?
A hash map from key to list node for O(1) lookup, and a doubly linked list ordered by recency for O(1) move-to-head and remove-from-tail.
How does Redis approximate LRU?
Each object holds a 24-bit access clock. To evict, Redis samples maxmemory-samples keys (default 5) and removes the one idle longest, keeping a small pool of good candidates between rounds.
What is the weakness of LRU, and of LFU?
LRU is polluted by scans and one-off reads that make cold keys look recent. LFU clings to formerly popular keys and is slow to admit new ones unless counters decay.
How does the CLOCK algorithm work?
Entries sit in a circle, each with a reference bit that a hit sets. To evict, a hand sweeps round. A set bit is cleared and skipped (a second chance), and a clear bit is evicted.
What does W-TinyLFU add to LRU?
An admission test. A new entry leaving a small LRU window replaces the main region's victim only if a compact frequency sketch says it has been requested more often.