The cache is full. Which item do we throw out? LRU, LFU, FIFO and more.
A cache has a limited size. When it is full and a new item arrives, we must remove one item. The rule that picks the item is the eviction policy.
Memory is limited. A cache that is full must evict (throw out) something to make room. The best choice is the item that will not be asked for again soon. We cannot see the future, so each policy makes a guess from the past.
| Word | Why an item leaves | Who decides |
|---|---|---|
| Eviction | The cache is full and needs space | The cache's policy |
| Expiry (TTL) | The item is too old | The clock |
| Invalidation | The real data changed | Your code or an event |
| Where | Policy you will often meet |
|---|---|
| Redis | Choose with maxmemory-policy: allkeys-lru, allkeys-lfu, volatile-ttl, noeviction and more (Redis uses an approximate LRU/LFU, not an exact one) |
| Memcached | LRU-style eviction per slab class |
| Browser and CDN caches | LRU-like removal plus expiry by Cache-Control headers |
| Operating system page cache | A form of LRU (approximated) |
| Databases | Buffer pools use LRU variants to decide which pages stay in memory |
| CPU caches | Hardware picks lines to remove, often an approximate LRU |
| Name | Idea |
|---|---|
| TTL-based | Remove items that expire first (or are already expired) |
| MRU (Most Recently Used) | Remove the newest. Odd, but fits some scans |
| LRU-K, 2Q, ARC, TinyLFU | Smarter versions that mix recency and frequency and resist scans |
| Optimal (Belady) | Remove the item needed furthest in the future. Needs the future, so it is only a yardstick |
get(key):
if key not in map: return MISS
move node(key) to the front of the list
return node.value
put(key, value):
if key in map: update value, move to front
else:
if cache is full: remove node at the BACK and its map entry
add a new node at the FRONT and put it in the map| Term | Meaning in easy words |
|---|---|
| Eviction | Removing an item to make space |
| LRU | Least Recently Used: remove the item unused for the longest time |
| LFU | Least Frequently Used: remove the item used the fewest times |
| FIFO | First In, First Out: remove the oldest arrival |
| Cache pollution | Useless data pushing out useful data |
| Cache thrashing | Items are evicted just before they are needed again, so almost everything misses |
| Working set | The data a program is using right now. If the cache is smaller than it, hits drop |
| Hit ratio | Share of requests answered from the cache |
| Belady's optimal | The best possible policy, which needs knowledge of the future |
| Capacity | How many items or bytes the cache can hold |
| Policy | Strength | Weakness | Cost |
|---|---|---|---|
| LRU | Great for recent-use patterns | Hurt by scans | Medium (list and map) |
| LFU | Keeps long-term favourites | Slow to forget, hard on new items | Higher (counters) |
| FIFO | Very simple | Ignores usage | Low |
| Random | Almost free | Unlucky evictions | Lowest |