LRU and friends: what a cache throws out
Your cache is full and a new key arrives. Something has to go. Here is how LRU, LFU and TTLs decide, drawn on a cache that holds three keys.
01 A full cache has to choose
A cache has a fixed amount of memory. While there is room, every new key just goes in. Once it is full, storing one more key means throwing one out, and the rule that picks which one is the eviction policy.
A good policy throws out the key you will not ask for again soon. Nobody knows the future, so each policy bets on a clue from the past: LRU bets on recent use, LFU on frequent use. To compare them, we will run the same nine requests through a cache that holds three keys.
A and B are the popular keys. C, D and E are asked for once each, like a report job reading old rows. A good policy keeps A and B.
02 LRU: throw out the least recently used
LRU keeps the keys in order of last use. Every hit moves a key to the front; when room is needed, the key at the back goes. The bet: what you used a moment ago, you will use again soon.
- miss
- hit
- just added
- not arrived yet
The cache is empty and holds three keys. Nine requests are about to arrive.
03 LRU in a dozen lines
LRU must find a key and move it to the front in constant time. The usual build is a hash map that points into a doubly linked list: the map finds the node, the list moves it in O(1). Python's OrderedDict is exactly that pair, so a working LRU is short.
The output matches the trace: four evictions and two hits. OrderedDict lists the oldest first, so the order is the trace's list read backwards.
04 LFU: throw out the least frequently used
LFU keeps a count of uses per key and throws out the lowest count. When two keys tie, it throws out the one used least recently. The bet: a key that has been popular will stay popular.
- miss
- hit
- just added
- thrown out
- not arrived yet
The same empty cache and the same nine requests. This time each key keeps a count of how often it was used.
A and B from keys used once.05 Where LFU loses
Plain counts only grow. Try A A A A B C D B C D: A was hot early and is never asked for again, but with a count of 4 it holds its slot for good. B, C and D keep throwing each other out of the two slots left, and every one of the last six requests misses. LRU drops A as soon as D arrives, then hits on B, C and D: 6 hits against LFU's 3.
Real LFU caches make counts fade. Redis's allkeys-lfu, for example, keeps a small logarithmic counter per key and lowers it as time passes without use (lfu-decay-time), so yesterday's star loses its place. Both policies also need memory for their bookkeeping: a list position or a counter on every key.
| Policy | Throws out | Good at | Bad at |
|---|---|---|---|
| LRU | the key unused for longest | recent working sets, sessions | one-off scans push out hot keys |
| LFU | the key with the fewest uses | stable favourites, scans | old favourites linger without decay |
| FIFO | the oldest key stored | simple, no work on hits | throws out hot keys just for age |
| Random | any key | almost free to run | no sense of what matters |
06 TTLs: expiry is not eviction
A TTL (time to live) says how long a key is valid. It is about freshness, not space: a key expires when its time is up, even if the cache is nearly empty. Eviction happens only when memory runs out. Most caches use both.
- just set
- expired, still stored
- deleted
An empty cache at t = 0. Each key will get its own time to live.
So an expired key can still take memory until someone reads it or the sweep finds it. In Redis the sweep runs about ten times a second by default (hz 10) and samples a few keys with a TTL each time, so expired keys go quickly but not instantly.
07 Choosing a policy in Redis
Redis evicts only once you set maxmemory. The policy then decides what goes. allkeys-* policies may evict any key; volatile-* policies only evict keys that have a TTL.
The default policy is noeviction. When memory is full, Redis keeps every key and fails writes with an OOM error. If you use Redis as a cache, set a policy on purpose.
SCAN every key onceA batch job flushes an LRU cacheA report that reads every key once makes each of them the most recent. The keys real users need are pushed out, and hit rate drops until they come back.EX 3600 on every keyEverything expires at onceKeys cached together with the same TTL expire together, and the database takes all the misses in one burst. Add a little random jitter to each TTL.maxmemory-samples 5Redis LRU is approximateRedis does not keep one big list. It samples a few keys (5 by default) and evicts the least recently used of those. Close to LRU, much cheaper, but not exact.volatile-lruNo TTLs, nothing to evictA volatile-* policy only considers keys with a TTL. If none have one, it behaves like noeviction and writes start failing.