Difficulty: Intermediate
What happens when Redis reaches its memory limit? Explain the available eviction policies.
When used memory crosses the maxmemory limit, Redis applies the configured maxmemory-policy before executing a command that may add data. With the default noeviction, writes that need more memory fail with an OOM command not allowed error while reads still work; with any other policy Redis evicts keys until it is back under the limit. For a pure cache the usual choice is allkeys-lru or allkeys-lfu.
| Policy | Candidate keys | How it picks |
|---|---|---|
noeviction | None | Rejects writes with an OOM error (default) |
allkeys-lru | All keys | Least recently used |
allkeys-lfu | All keys | Least frequently used |
allkeys-random | All keys | Random |
volatile-lru | Keys with a TTL | Least recently used |
volatile-lfu | Keys with a TTL | Least frequently used |
volatile-random | Keys with a TTL | Random |
volatile-ttl | Keys with a TTL | Shortest remaining TTL first |
The volatile-* policies behave like noeviction if no key has an expiry, which surprises people when Redis suddenly starts rejecting writes.
maxmemory-samples keys (default 5) and evicts the best candidate from a small pool, which approximates true LRU closely while using little memory. Raising samples to 10 gets closer to exact LRU at some CPU cost.lazyfree-lazy-eviction yes frees evicted values in a background thread.maxmemory is 0 (the default on 64-bit builds) there is no limit, and the OS may kill Redis instead.allkeys-lru.allkeys-lfu keeps them even if they were not touched in the last second.volatile-lru, so keys without a TTL (sessions, queues) are never evicted. Running two separate instances is often cleaner.noeviction, plus alerts on memory usage.maxmemory counts dataset memory, not replication or AOF buffers, and fragmentation means RSS can be well above it. Leave headroom (commonly 20-30 percent of RAM) for fork copy-on-write during BGSAVE.evicted_keys in INFO stats. A steadily rising number on a store that should not evict is an incident waiting to happen.# redis.conf (or CONFIG SET at runtime)
maxmemory 2gb
maxmemory-policy allkeys-lfu
maxmemory-samples 10
lazyfree-lazy-eviction yes
# At runtime
redis-cli CONFIG SET maxmemory-policy allkeys-lru
# How close are we, and are we evicting?
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|maxmemory_policy'
redis-cli INFO stats | grep -E 'evicted_keys|keyspace_hits|keyspace_misses'
Pick the policy to match what the instance stores, and monitor evicted_keys alongside the hit ratio to see whether the cache is undersized.
maxmemory, maxmemory-policy, allkeys-lru, volatile-ttl, noeviction, Approximated LRU