Eviction is sampled, not exact
When maxmemory is exceeded Redis picks maxmemory-samples random keys and evicts the worst — so 'LRU' is approximate and tunable, not a doubly-linked list.
Persistence keeps data across crashes. But while the process is RUNNING and used_memory rises past maxmemory, someone has to go — and Redis doesn't actually keep a perfect LRU list.
Scene 05
Eviction is sampled, not exact
- Watch
- Try it
- Predict
- Capture
Hot keys (top row) get touched repeatedly while a stream of cold writes pushes used memory past maxmemory. When that happens Redis picks maxmemory-samples random keys, highlights them, and evicts the worst one — most hot keys survive, but not all.
Highlighted lines are the ones running in the diagram right now.
def freeMemoryIfNeeded():if policy == 'noeviction':return OK # caller checks separatelywhile used_memory() > maxmemory:victim = pickVictim()if victim is None:return Error('cannot free memory')evict(victim) # del + propagate to AOF/replicasused_memory_subtract(sizeof(victim))return OK
def pickVictim():pool = candidate_pool # carries near-misses across passessamples = random_sample(keyspace, maxmemory_samples)for k in samples:pool.insert(k, score=lru_or_lfu(k))# worst = highest idle time (LRU) or lowest counter (LFU)return pool.pop_worst()
def handleWrite(cmd, value):if used_memory() + sizeof(value) > maxmemory:return Error('OOM command not allowed when used ''memory > maxmemory')# reads (GET, EXISTS, ...) keep serving normallyapply(cmd, value)return OK
Where this sits in Build Redis
Scene 05 of 10, in the Memory act — Persistence, eviction, TTL — what makes RAM disappear.. maxmemory + sampled LRU/LFU — Redis only inspects N keys per pass; tunable via `maxmemory-samples`.
Up next. TTL & cleanup — eviction fires under memory pressure. The OTHER cleanup path is the clock: TTLs expire whether you're full or not.
Designs that use this
- URL ShortenerShorten a long URL. Read-heavy. Don't collide.
- Distributed Rate LimiterEnforce a per-key request limit across a fleet of enforcers — accurately, in under a millisecond, without becoming the outage.
- Twitter / X TimelinePush or pull? Both. The canonical fanout problem.
- Uber / Lyft — Match Drivers and RidersMatch a rider to the closest acceptable driver in under 3 s. Geohash, S2, surge.