0
0
RedisConceptBeginner · 3 min read

Eviction Policies in Redis: How They Work and When to Use

In Redis, eviction policies control how data is removed when memory limits are reached. They decide which keys to delete to free up space, ensuring Redis keeps running smoothly without errors.
⚙️

How It Works

Imagine Redis as a small closet with limited space. When the closet is full, you need to decide which items to remove to make room for new ones. Eviction policies in Redis work like rules for choosing what to throw out when memory is full.

Redis supports several eviction policies, such as removing the least recently used items or the keys that will expire soon. This helps Redis manage memory efficiently without crashing or refusing new data.

💻

Example

This example shows how to set an eviction policy in Redis configuration and test it by adding keys until memory is full.

bash
CONFIG SET maxmemory 100kb
CONFIG SET maxmemory-policy allkeys-lru

# Add keys in a loop (using redis-cli)
for i in {1..1000}; do redis-cli SET key$i value$i; done

# Check memory usage
redis-cli INFO memory

# Check keys count
redis-cli DBSIZE
Output
OK OK ... # Memory info shows usage near 100kb # DBSIZE shows number of keys less than 1000 due to eviction
🎯

When to Use

Use eviction policies when you want Redis to act as a cache with limited memory. They help keep Redis responsive by automatically removing old or less important data.

For example, in a web app caching user sessions or API responses, eviction policies prevent Redis from running out of memory and crashing your app.

Key Points

  • Eviction policies decide which keys Redis removes when memory is full.
  • Common policies include noeviction, allkeys-lru, and volatile-lru.
  • They help Redis run smoothly as a cache by freeing space automatically.
  • You set eviction policies in Redis configuration with maxmemory-policy.

Key Takeaways

Eviction policies control how Redis frees memory when limits are reached.
They help keep Redis stable by removing keys based on rules like least recently used.
Set eviction policies in Redis config using the maxmemory-policy option.
Use eviction policies to make Redis a reliable cache with limited memory.