TExcelTAD
Home › System Design › Cache Eviction: LRU and LFU

Cache Eviction: LRU and LFU

A cache is smaller than the data behind it, so when it is full and a new item arrives, something must go. The eviction policy chooses the victim. A good policy keeps the items most likely to be requested again; a bad one throws them out and the hit ratio collapses.

Policy Evicts Good for Weakness
FIFO The oldest inserted item Simplicity Evicts popular items just because they are old
LRU (least recently used) The item not used for the longest time Most workloads with "recent = likely" behaviour A single scan of many one-off keys flushes the cache
LFU (least frequently used) The item used the fewest times Stable popularity (top products, hot config) Old favourites stay forever unless counts decay
TTL-based Expired items first Data with known freshness Not a full policy by itself
Random A random item Very cheap, surprisingly decent Unpredictable

Redis offers allkeys-lru, allkeys-lfu, volatile-ttl and others through maxmemory-policy, all approximations of the policies above.

LRU in O(1)

An LRU cache needs two operations to be fast: find a key (a hash map) and move a key to the "most recent" end or remove the oldest one (a doubly linked list). Python's OrderedDict is exactly that combination:

python · try it yourself
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity, self.items = capacity, OrderedDict()

    def get(self, key):
        if key not in self.items:
            return None
        self.items.move_to_end(key)          # mark as most recently used
        return self.items[key]

    def put(self, key, value):
        if key in self.items:
            self.items.move_to_end(key)
        self.items[key] = value
        if len(self.items) > self.capacity:
            evicted, _ = self.items.popitem(last=False)   # least recent is first
            print(f"  evict {evicted}")

cache = LRUCache(3)
for key in ["a", "b", "c"]:
    cache.put(key, key.upper())
cache.get("a")                               # a is now the most recent
cache.put("d", "D")                          # evicts b
cache.get("c")
cache.put("e", "E")                          # evicts a
print("order (old -> new):", list(cache.items))
  evict b
  evict a
order (old -> new): ['d', 'c', 'e']

LFU with frequency buckets

LFU counts how many times each key was used and evicts the lowest count; ties are broken by recency (the least recently used among the least frequent). Keeping keys grouped by count makes every operation O(1):

python · try it yourself
from collections import defaultdict, OrderedDict

class LFUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.values, self.counts = {}, {}
        self.buckets = defaultdict(OrderedDict)    # count -> keys in recency order
        self.min_count = 0

    def _touch(self, key):
        c = self.counts[key]
        del self.buckets[c][key]
        if not self.buckets[c] and self.min_count == c:
            self.min_count += 1
        self.counts[key] = c + 1
        self.buckets[c + 1][key] = None

    def get(self, key):
        if key not in self.values:
            return None
        self._touch(key)
        return self.values[key]

    def put(self, key, value):
        if key in self.values:
            self.values[key] = value
            self._touch(key)
            return
        if len(self.values) >= self.capacity:
            victim, _ = self.buckets[self.min_count].popitem(last=False)
            del self.values[victim], self.counts[victim]
            print(f"  evict {victim}")
        self.values[key], self.counts[key] = value, 1
        self.buckets[1][key] = None
        self.min_count = 1

cache = LFUCache(3)
for key in ["home", "about", "pricing"]:
    cache.put(key, f"<{key}>")
for _ in range(3):
    cache.get("home")
cache.get("pricing")
cache.put("blog", "<blog>")                  # about has count 1 -> evicted
cache.put("careers", "<careers>")            # blog has count 1 -> evicted
print({k: cache.counts[k] for k in cache.values})
  evict about
  evict blog
{'home': 4, 'pricing': 2, 'careers': 1}

Comparing policies on a workload

The best policy depends on the access pattern, so measure. This workload mixes a set of popular keys (80% of requests go to 20 keys) with a periodic scan that reads 100 one-off keys, like a nightly report:

python · try it yourself
import random
from collections import OrderedDict, Counter

def workload(seed=42):
    rng = random.Random(seed)
    for i in range(20_000):
        if i % 2_000 < 100:
            yield f"scan:{i}"                   # one-off keys
        elif rng.random() < 0.8:
            yield f"hot:{rng.randrange(20)}"
        else:
            yield f"cold:{rng.randrange(2_000)}"

def run(policy, capacity=50):
    cache, uses, hits = OrderedDict(), Counter(), 0
    for key in workload():
        uses[key] += 1
        if key in cache:
            hits += 1
            if policy == "LRU":
                cache.move_to_end(key)
            continue
        if len(cache) >= capacity:
            if policy == "LFU":
                victim = min(cache, key=lambda k: uses[k])
                del cache[victim]
            else:                               # FIFO and LRU both pop the front
                cache.popitem(last=False)
        cache[key] = True
    return hits / 20_000

for policy in ["FIFO", "LRU", "LFU"]:
    print(f"{policy:<5} hit ratio {run(policy):.1%}")
FIFO  hit ratio 66.3%
LRU   hit ratio 75.2%
LFU   hit ratio 76.4%

FIFO is clearly worst: it evicts hot keys just because they were inserted long ago. LFU edges out LRU because it remembers that the hot keys are hot even after a scan has passed through (this model keeps counts for evicted keys too, so a returning hot key is recognised immediately). On workloads where popularity shifts quickly (news, trending posts), LRU usually wins, because LFU keeps yesterday's stars. Modern caches use hybrids such as W-TinyLFU (Caffeine) or ARC, which keep both a recency and a frequency signal.

Tip: The cheapest way to improve a hit ratio is often a bigger cache, not a cleverer policy. Measure the hit ratio at a few cache sizes before tuning the algorithm.

Test yourself

Which two data structures give an LRU cache O(1) get and put?

  1. A heap and an array
  2. A hash map and a doubly linked list
  3. Two stacks
  4. A binary search tree and a queue

LRU cache with capacity 2: put a, put b, get a, put c. Which key is evicted?

  1. a
  2. b
  3. c
  4. Nothing

Why can a one-time scan of many keys hurt an LRU cache?

  1. Scans are slower than gets
  2. Each scanned key becomes 'most recent' and pushes out the genuinely popular keys
  3. LRU can't store more than 100 keys
  4. Scans clear the TTLs