Video in progress
When the cache is full, which entry gets evicted — what are LRU and LFU?
A cache has limited size, and when it fills up, something is evicted according to the eviction policy. LRU evicts the entry that hasn't been accessed for the longest time, LFU evicts the entry accessed least often.
📖 Answer
The logic of LRU (Least Recently Used) is: "what was used recently will be needed again". It works right in most cases and is simple.
LRU's weak spot is a one-off scan. Say someone reads 100,000 old products once for a report. They go into the cache and push out the popular products.
LFU (Least Frequently Used) handles this better: an entry read once can't push out one that was read many times. But an entry that was popular yesterday and is useless today can stay for a long time.
In practice you use ready-made libraries:
- Caffeine — W-TinyLFU, which combines the good sides of both;
- Redis — through
maxmemory-policy:allkeys-lru,allkeys-lfu,volatile-ttland others.
In Redis the default is noeviction — when memory is full, writes fail with an error. If you use it as a cache, definitely change this.
Sign up to mark studied questions and save your progress.