Eviction Policies in Redis: How They Work and When to Use
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.
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
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, andvolatile-lru. - They help Redis run smoothly as a cache by freeing space automatically.
- You set eviction policies in Redis configuration with
maxmemory-policy.