Video in progress
What is the difference between LRU and LFU eviction, and which one fits a cache better?
LRU evicts the key that hasn't been accessed for the longest time, LFU evicts the one accessed least often. LFU keeps one-off bulk reads from pushing out popular keys, so under a mixed load it's often better.
📖 Answer
Here's an example. A product on the home page is read 100 thousand times a day. At night a batch job reads 500 thousand old products once each.
- With LRU: the keys the batch read become the "newest", and the home page product may get evicted. In the morning you get a wave of misses.
- With LFU: the batch keys have a counter of 1 and the popular key has a large one, so the one-timers go first.
Redis makes both approximate: it doesn't sort all the keys, it takes maxmemory-samples (default 5) random keys and picks a candidate among them. That's cheap and in practice comes close to true LRU.
In LFU the counter is logarithmic and decays over time (lfu-decay-time), otherwise yesterday's popular key would be kept forever.
I usually start with allkeys-lfu for a cache and watch the hit ratio. If accesses are fairly uniform, the difference between the two is barely noticeable.
Sign up to mark studied questions and save your progress.