What are the common cache eviction policies, and how is LRU implemented?
MediumConceptCaching
Answer
When a cache is full, an eviction policy decides which entry to remove. LRU (least recently used) is the most common, because recent access is a good predictor of future access.
- LRU: evicts the entry unused for the longest time. Implement it with a hash map from key to node plus a doubly linked list ordered by recency, giving
O(1)get and put. - LFU: evicts the least frequently used entry; good for stable popularity, but slow to adapt when popularity shifts.
- FIFO and random: simple, but usually with lower hit ratios.
- TTL: entries expire after a fixed time regardless of use, which bounds staleness; it is often combined with an eviction policy, as in Redis, which offers an approximated LRU.