Sub topic 10
Eviction Policies: LRU, LFU, and FIFO
This chapter assumes you know what a cache is, how hits and misses work, and basic Python. A cache has limited space. When it is full and a new entry arrives, an eviction policy decides which existing entry to remove. A good policy removes entries you are least likely to need again, which keeps the hit ratio high.
Eviction versus expiration
TTL expiration removes entries because they are old. Eviction removes entries because there is no room. A cache can use both. An entry may be evicted long before its TTL runs out, and a cache that is not full can still expire entries.
The three common policies
| Policy | Evicts | Tracks | Works well when | Weak spot |
|---|---|---|---|---|
| FIFO (first in, first out) | The oldest inserted entry | Insertion order | Access patterns are uniform or unknown | Evicts hot entries just because they are old |
| LRU (least recently used) | The entry unused for the longest time | Recency of access | Recent use predicts future use | A one-time scan can push out hot entries |
| LFU (least frequently used) | The entry with the fewest accesses | Access counts | A stable set of popular items | Slow to drop items that were popular once |
FIFO
FIFO ignores how often or how recently an entry was read. It is simple and cheap, but a popular entry inserted early will be evicted first.
LRU
LRU assumes that data used recently will be used again soon. This is the temporal locality idea from the fundamentals chapter. Every read moves the entry to the "most recent" end, and the entry at the other end is evicted.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.items = OrderedDict()
def get(self, key, default=None):
if key not in self.items:
return default
self.items.move_to_end(key) # mark as most recently used
return self.items[key]
def put(self, key, value):
self.items[key] = value
self.items.move_to_end(key)
if len(self.items) > self.capacity:
self.items.popitem(last=False) # evict least recently usedBoth get and put run in constant time because OrderedDict is backed by a hash table and a linked list. If you remove the move_to_end call in get, this class becomes a FIFO cache.
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a") # "a" is now the most recent
cache.put("c", 3) # over capacity: evicts "b"
print(cache.get("b")) # None
print(cache.get("a")) # 1LFU
LFU keeps a counter per entry and evicts the lowest count. It protects entries that are requested often over a long period. It has two known problems. An entry with a high count from an old burst of traffic can stay forever, so real implementations decay or age the counts. A new entry starts with a low count and can be evicted before it has a chance to build one.
Common errors
- Choosing LRU for a workload that scans a large dataset once. The scan fills the cache with entries that are never read again and evicts the useful ones.
- Sizing the cache by item count when entries vary a lot in size. A few large values can use most of the memory. Many caches let you set a byte limit instead.
- Judging a policy by reasoning alone. Compare policies on real traffic by measuring the hit ratio and eviction rate, as covered in the monitoring chapter.
Exercise
A nightly job reads every row of a large table once, and the application cache uses LRU. Why does the hit ratio drop during the job, and what would you change?
Show answer
Each row read by the job enters the cache and counts as recently used, so the job pushes out the entries that normal traffic needs. Because the job never reads those rows again, they only waste space. You can have the job bypass the cache, or use a policy that resists scans, such as LFU or an LRU variant that separates new entries from proven ones.