How to Set Eviction Policy in Redis: Simple Guide
To set the eviction policy in Redis, use the
maxmemory-policy configuration directive in the redis.conf file or via the CONFIG SET maxmemory-policy command. This policy controls how Redis removes keys when it reaches its memory limit, with options like noeviction, allkeys-lru, and volatile-lru.Syntax
The eviction policy in Redis is set using the maxmemory-policy configuration. You can set it in the redis.conf file or dynamically with the CONFIG SET command.
maxmemory-policy <policy>: Sets the eviction policy in the config file.CONFIG SET maxmemory-policy <policy>: Sets the eviction policy at runtime.
Common policies include noeviction, allkeys-lru, volatile-lru, allkeys-random, volatile-random, and volatile-ttl.
redis
maxmemory-policy noeviction # Or at runtime: CONFIG SET maxmemory-policy allkeys-lru
Example
This example shows how to set the eviction policy to allkeys-lru at runtime and verify it.
redis
127.0.0.1:6379> CONFIG SET maxmemory-policy allkeys-lru OK 127.0.0.1:6379> CONFIG GET maxmemory-policy 1) "maxmemory-policy" 2) "allkeys-lru"
Output
OK
1) "maxmemory-policy"
2) "allkeys-lru"
Common Pitfalls
Common mistakes when setting eviction policy include:
- Not setting a
maxmemorylimit, so eviction never triggers. - Choosing
noevictionwhich causes writes to fail when memory is full. - Confusing
allkeys-*policies withvolatile-*policies; the latter only evict keys with expiration set.
Always ensure maxmemory is configured to enable eviction.
redis
127.0.0.1:6379> CONFIG SET maxmemory-policy noeviction OK # If maxmemory is reached, writes will fail instead of evicting keys. # Correct approach: 127.0.0.1:6379> CONFIG SET maxmemory 100mb OK 127.0.0.1:6379> CONFIG SET maxmemory-policy allkeys-lru OK
Output
OK
OK
OK
Quick Reference
| Eviction Policy | Description |
|---|---|
| noeviction | No keys are evicted; writes fail when memory limit is reached. |
| allkeys-lru | Evicts least recently used keys from all keys. |
| volatile-lru | Evicts least recently used keys with expiration set. |
| allkeys-random | Evicts random keys from all keys. |
| volatile-random | Evicts random keys with expiration set. |
| volatile-ttl | Evicts keys with shortest time to live first. |
Key Takeaways
Set the eviction policy using the maxmemory-policy directive in redis.conf or CONFIG SET.
Eviction only works if maxmemory is set to limit Redis memory usage.
Choose the right policy based on whether you want to evict all keys or only keys with expiration.
Avoid noeviction if you want Redis to free memory automatically.
Use CONFIG GET maxmemory-policy to verify the current eviction policy.