Eviction and LRU
What to throw out.
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.

- 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.
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))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.
| Policy | Removes |
|---|---|
| LRU | least recently used |
| LFU | least frequently used |
| FIFO | oldest added |
| Random | any 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