Question: What are Redis Eviction Events and how can they be managed?

Answer

Redis Eviction events occur when the memory limit defined in your configuration (or default settings) is reached and newer data needs to be added. When this happens, Redis uses its eviction policy to evict existing keys to make room for new data.

There are several eviction policies that Redis supports:

  1. noeviction: No eviction is performed. If the max memory limit is hit, commands will return errors.
  2. allkeys-lru: Remove less recently used keys first.
  3. volatile-lru: Remove less recently used keys first where an expire set is present.
  4. allkeys-random: Remove random keys.
  5. volatile-random: Remove random keys where an expire set is present.
  6. volatile-ttl: Remove keys with a short time-to-live (TTL) first.

To set a specific eviction policy, you can update Redis configuration file redis.conf or use the CONFIG SET command as follows:

redis-cli CONFIG SET maxmemory-policy allkeys-lru

The choice of eviction policy greatly depends on what kind of data you're storing in Redis and how critical it is to preserve certain types of data over others.

You can monitor eviction events using Redis's INFO command. The evicted_keys field in the output shows the number of keys that have been evicted due to max memory limit:

redis-cli INFO

In the output, look for:

# Memory used_memory:832592 used_memory_human:813.07K used_memory_rss:9850880 used_memory_peak:842176 used_memory_peak_human:822.34K used_memory_lua:37888 mem_fragmentation_ratio:11.83 mem_allocator:jemalloc-3.6.0 evicted_keys:1000

Here, evicted_keys indicates the total keys evicted due to max memory limit.

By understanding Redis eviction events and setting appropriate eviction policies, you can efficiently manage your memory usage in Redis.

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.