Introducing Dragonfly Cloud! Learn More

Question: What is the Redis eviction policy and how can you configure it?

Answer

Redis Eviction Policy determines how Redis handles memory shortage when its limit is reached. There are several policies that control which keys Redis will remove first. Here are the available policies:

  1. noeviction: Returns an error if the memory limit has been reached when trying to insert more data.
  2. allkeys-lru: Evicts the least recently used keys out of all keys.
  3. volatile-lru: Evicts the least recently used keys among those that have an expire set.
  4. allkeys-random: Evicts random keys out of all keys.
  5. volatile-random: Evicts random keys among the ones with an expire set.
  6. volatile-ttl: Evicts the keys with an expire set, starting with the ones that have less time to live.

To configure Redis to follow a specific eviction policy, you need to update the redis.conf file or set the policy at runtime using the CONFIG SET command.

Here's a code snippet on how you can set the eviction policy using the CONFIG SET command:

redis-cli CONFIG SET maxmemory-policy volatile-lru

Remember, it's important to choose the eviction policy that best suits your application's needs in order to prevent unforeseen data loss or performance issues. For instance, if you know that some keys will be accessed infrequently but should not be evicted, you'll want to avoid the allkeys-lru policy. Conversely, if you're using Redis as a cache where every key has an expiration, you might want to use the volatile-lru or volatile-ttl policy.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.