Question: What is an eviction strategy in Redis and how can it be configured?
Answer
Redis Eviction Strategy controls how keys are removed when the memory limit has been reached. This is especially important when Redis is used as a cache, and you need to decide which items should be removed first.
There are several eviction strategies available in Redis:
noeviction
: Returns an error if the memory limit is reached and the client tries to execute commands that could result in more memory usage.allkeys-lru
: Removes any key trying to use the least recently used (LRU) algorithm when making room for new data.volatile-lru
: Removes the least recently used (LRU) keys with anexpire
set.allkeys-random
: Removes a random key when making room for new data.volatile-random
: Removes a random key with anexpire
set when making room for new data.volatile-ttl
: Removes the shortest time-to-live (TTL) or expire set keys first.
To configure the Redis eviction strategy, use the maxmemory-policy
configuration directive. For example, if you want to set the policy to allkeys-lru, you would use:
redis-cli config set maxmemory-policy allkeys-lru
Remember to make this change persistent across Redis restarts by adding the directive to your redis.conf
file:
# inside redis.conf maxmemory-policy allkeys-lru
Please ensure to choose an eviction strategy that makes sense for your specific use-case as different applications might benefit from different strategies.
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