Cache eviction policies
easy 22 minA cache has a memory limit.
See it run
The same requests, different rules: watch who is marked NEXT, who leaves, and what it costs.
Operations
LRU
Evict the entry that was used longest ago.
Step 1 of 11
Empty cache
| place 1 | place 2 | place 3 | |
|---|---|---|---|
| key | - | - | - |
| last used | - | - | - |
| uses | - | - | - |
| stored at | - | - | - |
| next out | - | - | - |
hits 0
3 places. The requests are A B C A A D A E A B.
Step 1: Empty cache
def get(key): if key not in data: return None data.move_to_end(key) # newest return data[key]def put(key, value): if len(data) >= capacity: data.popitem(last=False) # oldest use data[key] = value- Per operation
- O(1)
- Keeps
- order of use
- Best possible
- 5 hits of 10
A map plus a linked list: no clock is needed, only the order.
In the real world
The same cache eviction policies doing real jobs. Pick one and step through it.
C, D and E are read once each. A and B are the keys people want.
Step 1 of 12
Empty cache
| place 1 | place 2 | place 3 | |
|---|---|---|---|
| key | - | - | - |
| last used | - | - | - |
| uses | - | - | - |
| stored at | - | - | - |
| next out | - | - | - |
hits 0
3 places. The requests are A A B B C D A B E A B.
Step 1: Empty cache
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No memory limit
criticalWithout a limit the cache grows until the machine runs out of memory, and the operating system kills the process.
Wrongcache = {} # grows foreverRightcache = LRUCache(10_000) # a limit and a ruleCache and sessions in one store
criticalUnder an all-keys policy a busy product page can push out a login session.
Wrongredis.set("session:7", token)redis.set("page:home", html) # allkeys-lruRightsessions.set("session:7", token) # noevictionpages.set("page:home", html) # allkeys-lruLFU without decay
majorLast month's star has a count nobody can beat and stays for weeks.
Wrongcount[key] += 1 # only ever upRightif minutes_idle(key) >= 1: count[key] -= 1 # old fame fadescount[key] += 1Batch jobs fill the cache
majorA scan stores a million values that nobody reads again.
Wrongfor pid in all_products(): get_cached(pid)Rightfor pid in all_products(): read_replica(pid) # never stored
Interview tips
How to explain it
- A full cache must drop one copy.
- The policy guesses what will not be wanted.
- A wrong guess costs one slow read.
Memory trick: LIFE
- L: last used, LRU.
- I: in demand, LFU.
- F: first in, FIFO. E: expiry, TTL.
Good defaults
- LRU plus TTL.
- A memory limit, with headroom.
- Frequency-aware when scans appear.
Watch
- Hit rate and evictions per second.
- How long victims were idle.
- Expired versus evicted keys.