Dragonfly

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 policies:

  1. noeviction: The server returns an error when you try to execute commands that cache new data. Commands that only read existing data still work as normal.
  2. allkeys-lru: Evicts the least recently used keys out of all keys.
  3. allkeys-lfu: Evicts the least frequently used keys out of all keys.
  4. allkeys-random: Evict keys at random.
  5. volatile-lru: Evicts the least recently used keys among those having expirations.
  6. volatile-lfu: Evicts the least frequently used keys among those having expirations.
  7. volatile-random: Evicts random keys among those having expirations.
  8. volatile-ttl: Evicts the shortest time-to-live keys among those having expirations.

To set the eviction policy, you can add or modify the maxmemory-policy directive in your redis.conf file. Note that a server restart is required for the changes to take effect.

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.

Redis triggers its eviction policy once the used memory size hits the configured maxmemory limit, removing items to prevent further memory usage growth.

Was this content helpful?

Help us improve by giving us your feedback.

Other Common Redis Questions (and Answers)

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.

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