Question: How can you set the eviction policy in Redis?
Answer
Redis allows setting different types of eviction policies to control how data is removed from memory when it reaches its maximum limit. This is done by adjusting the maxmemory-policy
configuration directive.
Here are the supported eviction methods:
noeviction
: Returns an error when the memory limit is reached and the client tries to execute commands that could result in more memory being used.allkeys-lru
: Evicts the least recently used keys out of all keys.volatile-lru
: Evicts the least recently used keys among those set to have an expire set.allkeys-random
: Evicts random keys out of all keys.volatile-random
: Evicts random keys among those set to have an expire set.volatile-ttl
: Evicts the shortest time-to-live keys among those set to have an expire set.
To set the eviction policy, you can add or modify the maxmemory-policy
directive in your redis.conf
file, like so:
maxmemory-policy volatile-lru
You can also set this configuration at runtime using the CONFIG SET
command:
127.0.0.1:6379> CONFIG SET maxmemory-policy volatile-lru OK
Remember to replace volatile-lru
with your preferred eviction policy.
Note: The lru
, random
and ttl
eviction policies only evict keys with an expiration set if the maxmemory
directive is also set to a value other than 0.
Was this content helpful?
Other Common Redis Questions (and Answers)
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost