Reading — step 1 of 3
Memory Management
LRU Eviction — Memory Management
Redis lives in RAM, and RAM is finite. What happens when you run out? Redis uses eviction policies to automatically remove keys.
Eviction Policies
| Policy | Description |
|---|---|
noeviction | Return errors when memory limit is reached |
allkeys-lru | Evict least recently used key (most common) |
allkeys-lfu | Evict least frequently used key |
volatile-lru | Only evict keys with TTL set |
allkeys-random | Evict random keys |
LRU — Least Recently Used
The idea: keys that haven't been accessed recently are less likely to be needed. When memory is full, evict the stalest key.
Real Redis doesn't use a true LRU (too expensive — requires a linked list of all keys). Instead, it uses approximated LRU: sample 5 random keys and evict the one with the oldest access time. This is O(1) and surprisingly accurate.
What You'll Build
MAXKEYS <n>— set the key limit- Track last-access time for every key
- When at capacity, evict the LRU key before adding new ones
INFO memory— report current state
This is the same concept used in CPU caches, page replacement (OS), and CDN caches. Understanding LRU here transfers to every layer of the stack.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…