LFU sounds ideal, since it keeps the most popular keys. What goes wrong with it in practice?
Sketch your own answer first, then compare it with the one below.
A strong answer
LFU evicts the key with the lowest hit count. If popularity is stable, counts identify the genuinely popular keys and LFU does very well.
Two problems:
- Staleness. A key that was popular keeps its high count after it stops being requested, so it occupies a slot long after it stopped earning one. When the workload shifts to new keys, those start with low counts and get evicted again before they can build up. The cache can stay full of keys nobody asks for.
- Cost. Exact counts for every key take memory and bookkeeping, and finding the lowest count needs a suitable data structure.
The usual fixes are aging, where counts decay or are periodically halved, and keeping approximate counts in a compact sketch. TinyLFU does both and uses the counts to decide whether a new key deserves to enter at all.
Contrast with LRU, which forgets quickly and needs no counters, but is easily polluted by scans.
Sources
- Gil Einziger, Roy Friedman, Ben Manes (2017). TinyLFU: A Highly Efficient Cache Admission Policy.