How does Redis Eviction work ?

Vedant Kekan
2 min readJan 12, 2025

--

Redis eviction is the process of removing keys from the database when it reaches its memory limit, ensuring that new data can be added without exceeding the allocated memory.

This memory management is necessary when Redis is used as cache.

Redis Memory Model

Redis memory allocarion

Redis allow setting maximum memory for usage using maxmemory configuration.Once this memory limit is reached Redis decide on handling data based on eviction policy.

Eviction policy can be configured using maxmemory-policy configuration.

maxmemory 100mb
maxmemory-policy allkeys-lru

Lets take look at Eviction Policies in Redis

A) Volatile : Applicable only if key have expiry = true

  1. volatile-lru : Evict the least recently used (LRU) keys with TTL
    Usage: Cases were recently accessed data is reused, like latest trending news
  2. volatile-lfu : Evict the least frequently used (LFU) keys with TTL
    Usage: Data that is used frequently, like popular products on ecommerce
  3. volatile-random : Evict random keys with TTL
    Usage: Cases where data could be accessed randomly, app that read data in cycles
  4. volatile-ttl : Evict keys with the shortest TTL first
    Usage: Cases were we can predict how long we need cache

B) All-Key Eviction: Applicable on all keys

  1. allkeys-lru : Evict the least recently used keys
  2. allkeys-lfu : Evict the least frequently used keys
  3. allkeys-random : Evict random keys

Similar to above explanation just works on all keys

C) No Eviction : Redis returns an error for write operations
Usage: When Redis is used as persistent store

Lets review all Configuration and fine-tuning once again,

maxmemory: Specifies the memory limit.
Example: maxmemory 512mb.

maxmemory-policy: Specifies the eviction policy.
Example: maxmemory-policy allkeys-lru.

maxmemory-samples: Defines the number of keys sampled when applying eviction algorithms.
Higher values provide more accuracy but increase CPU usage. Default is 5.

You can get below commands to inspect evictions configuration,

CONFIG GET maxmemory
CONFIG GET maxmemory-policy

Finally, you should always monitor and check how your cache is behaving.
You can use INFO memory command which will tell you cache hit ratio.

keyspace_hits / (keyspace_hits + keyspace_misses) * 100

--

--

Vedant Kekan
Vedant Kekan

Written by Vedant Kekan

Exploring this beautiful world.

No responses yet