AI Hints
Home›System Design Tutorial›Keeping Caches Healthy
System Design · Lesson 58 of 120

Eviction and LRU

What to throw out.

⏱ 2 min read▶ Video at 1:08:58🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

A cache lives in memory, and memory is limited. When it's full, and something new arrives, something old must go. The rule for choosing is called an eviction policy.

Eviction and LRU
From the video: Eviction and LRU
  • Memory is limited
  • Something must go
  • An eviction policy

Least recently used

The most popular policy is LRU, least recently used. Throw out whatever hasn't been touched for the longest time. Python's ordered dict makes it easy. Every access moves an item to the end, so the front is always the oldest. Run it. The cache holds three items. Reading A keeps it fresh, so when D arrives, B is evicted instead.

lru.pypython
from collections import OrderedDict

class LRUCache:
    def __init__(self, size):
        self.size, self.data = size, OrderedDict()
    def get(self, key):
        self.data.move_to_end(key)
        return self.data[key]
    def put(self, key, value):
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.size:
            print("evicted", self.data.popitem(last=False)[0])
c = LRUCache(3)
for k in "ABC":
    c.put(k, k.lower())
c.get("A")
c.put("D", "d")
print("now holds:", list(c.data))
Output
evicted B
now holds: ['C', 'A', 'D']

Other policies

There are other policies too. LFU, least frequently used, keeps popular items, even if they weren't used just now. First in, first out simply removes the oldest item added. And random eviction is surprisingly decent, and very cheap. LRU is the usual default.

PolicyRemoves
LRUleast recently used
LFUleast frequently used
FIFOoldest added
Randomany item

Summary

When a cache is full, an eviction policy decides what goes. LRU, least recently used, is the usual choice. Next, keeping cached data fresh.

Key takeaways
  • Memory is limited
  • LRU is the default
  • LFU keeps popular items
Next up: TTL and Invalidation — keeping caches fresh