Sub topic 10
Eviction policies: LRU, LFU, and FIFO
A cache has a fixed capacity. When it is full and a new entry arrives, the cache must remove something. The rule that picks the victim is the eviction policy. This chapter assumes you know what a hit and a miss are, and that you have seen the cache-aside pattern and TTL expiration from earlier chapters.
Eviction versus expiration
Expiration and eviction are different mechanisms, and mixing them up causes confusion in production.
- Expiration removes an entry because it is too old. A TTL decides this, and it works even when the cache has plenty of free space.
- Eviction removes an entry because the cache is out of room. The policy decides this, and it works even when entries are still fresh.
Most real caches use both. A TTL bounds staleness, and an eviction policy bounds memory. The goal of any eviction policy is to keep the entries most likely to be requested again, so that the hit ratio stays high within the memory budget.
Why the choice matters
Every policy is a guess about the future based on the past. A good guess keeps hot entries and drops cold ones. A bad guess throws away an entry just before it is needed again. The ideal policy would evict the entry whose next use is farthest in the future. Nobody can know that in advance, so practical policies use signals such as recency, frequency, or arrival order.
The signals you can use depend on your access pattern. Workloads with temporal locality (an item used now is likely to be used again soon) favor recency. Workloads with a stable set of popular items favor frequency. Workloads with neither gain little from a smart policy.
FIFO: first in, first out
FIFO evicts the entry that has been in the cache longest, regardless of how often or how recently it was read.
- Cost: very cheap. A queue of keys is enough. Reads change nothing.
- Strength: simple, predictable, and fast, with no bookkeeping on hits.
- Weakness: a popular entry that was inserted early gets evicted on schedule, even if it is read constantly. It then causes a miss and is reloaded at the back of the queue.
FIFO fits when entries have a natural short lifespan that matches arrival order, or when the bookkeeping cost of other policies is not worth it. For most general-purpose caches it is a weak default.
LRU: least recently used
LRU evicts the entry that has gone unread for the longest time. Every access moves the entry to the "most recent" end. When the cache is full, the entry at the "least recent" end is removed.
LRU works well when recent use predicts near-future use, which is true for many user-facing workloads: sessions, recently viewed pages, and working sets that drift slowly.
A standard implementation combines a hash map with a doubly linked list so that get and put both run in O(1) time. In Python, OrderedDict provides this structure:
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 usedHere move_to_end runs on every read, and popitem(last=False) removes the oldest entry. Both are constant time.
LRU gotchas
- Scan pollution. A one-time sequential scan, such as a report that reads every row once, pushes every key to the "recent" end. It evicts the genuinely hot entries and replaces them with data that will never be read again.
- Write cost on reads. Every hit modifies the ordering structure. In a multi-threaded cache this means a lock or atomic update on the read path, which can become a contention point.
- Weak with cyclic access. If a loop reads N+1 keys repeatedly and the capacity is N, LRU evicts each key right before it is needed, and the hit ratio drops to zero.
Production systems often use approximations. Redis, for example, samples a small number of keys and evicts the least recently used among the sample, which avoids maintaining a full ordering.
LFU: least frequently used
LFU evicts the entry with the fewest accesses. Each entry carries a counter that increments on every hit. The lowest counter loses.
LFU works well when popularity is stable. A small set of hot keys, such as a product catalog's bestsellers, stays resident even if a burst of other traffic passes through. It resists scan pollution, because a scanned key has a count of one.
LFU gotchas
- Stale popularity. An entry that was very popular last week keeps a high counter and survives long after nobody reads it. New entries start at a low count and are the first to be evicted, so the cache can fail to adapt.
- Counter overhead. Counters cost memory and update time. Finding the minimum efficiently needs a more complex structure than LRU.
- Ties. Many entries share a low count, so the policy needs a tie-breaker, usually recency.
Real implementations reduce these problems with aging. They decay counters over time, or they use small approximate counters. Redis's LFU mode uses a logarithmic counter with a decay period, and admission-based designs such as TinyLFU only admit a new entry if it looks more popular than the one it would displace.
Comparing the policies
| Policy | Evicts | Tracks | Good for | Weak spot |
|---|---|---|---|---|
| FIFO | Oldest inserted | Insertion order | Simple, short-lived data | Ignores popularity entirely |
| LRU | Least recently read | Recency | Drifting working sets | Scans and cyclic access |
| LFU | Least often read | Frequency | Stable popular items | Slow to forget old favorites |
Seeing the difference with a trace
The same access sequence can produce different results under different policies. The following script replays a trace against a FIFO and an LRU cache of capacity 3 and counts hits.
from collections import OrderedDict
def run(trace, capacity, policy):
items = OrderedDict()
hits = 0
for key in trace:
if key in items:
hits += 1
if policy == "lru":
items.move_to_end(key) # only LRU reorders on a hit
else:
items[key] = True
if len(items) > capacity:
items.popitem(last=False)
return hits
trace = ["a", "b", "c", "a", "a", "d", "a", "b", "a", "c"]
print("FIFO hits:", run(trace, 3, "fifo"))
print("LRU hits:", run(trace, 3, "lru"))The key a is hot. Under FIFO it was inserted first, so it is evicted when d arrives, even though it was just read. Under LRU the repeated reads keep a near the recent end, so it survives. Running the script prints FIFO hits: 2 and LRU hits: 4.
Other considerations
Entry size
Policies above treat every entry as equal. In practice entries differ in size, and evicting one large entry may free room for many small ones. Some caches weight eviction by size or by the cost to recompute. A cheap-to-rebuild entry is a better victim than an expensive one with the same recency.
Random eviction
Random eviction removes an arbitrary entry. It needs no bookkeeping and avoids pathological patterns such as cyclic scans. It is a reasonable baseline when you want to know whether a sophisticated policy actually earns its cost.
Interaction with TTL
When an entry has a TTL, many systems prefer to evict expired or soon-to-expire entries first. Redis offers policies such as volatile-lru, which only evicts keys that have a TTL, and allkeys-lru, which considers every key. If you choose a volatile- policy and no keys have a TTL, the cache cannot free memory and writes fail with an out-of-memory error.
Eviction in a distributed cache
Each node runs its own policy on its own memory. A node holding a hot partition evicts more than its neighbors. Watch per-node eviction rates, not only the cluster average.
Choosing and verifying
- Start with LRU. It handles the widest range of workloads and is well understood.
- Switch to LFU, or an LFU variant with aging, if popularity is stable and scans or bursts evict your hot keys.
- Use FIFO or random when simplicity and low overhead matter more than hit ratio.
- Replay a real access log against candidate policies and compare hit ratios, as the trace script does. Do not decide from theory alone.
- After deployment, track the eviction rate. A steadily rising eviction count with a falling hit ratio means the cache is too small for the working set, and no policy will fix that.
Exercise
A nightly job reads every row of a large table exactly once through your LRU cache, and the next morning your hit ratio is low. Explain the cause and name two ways to reduce the damage.
Show answer
The scan marks every row as recently used, which pushes the hot entries out of the cache and fills it with rows that will not be read again (scan pollution). Two fixes: make the job bypass the cache (a write-around style read straight from the database), or use a policy resistant to scans, such as LFU with aging or an admission policy like TinyLFU. A separate, small cache for the batch job also works.
Exercise
A cache uses LFU without any aging. Last month a product was extremely popular, and it is now rarely requested. Why might it still occupy space, and what would you change?
Show answer
Its counter is still high, so it ranks above newer entries with low counts, and LFU evicts the newer entries first. Add aging so counters decay over time, or use a policy that combines frequency with recency.