0
0
Redisquery~5 mins

Eviction policies (LRU, LFU, random) in Redis

Choose your learning style9 modes available
Introduction

Eviction policies help Redis decide which data to remove when memory is full. This keeps Redis fast and avoids crashes.

When your Redis memory is limited and you want to keep it running smoothly.
When you want to keep the most useful data and remove less important data automatically.
When you want to control how Redis frees up space without manual cleanup.
When you want to test different ways Redis removes old data to find the best for your app.
Syntax
Redis
maxmemory-policy <policy_name>

Set this in your Redis configuration file or at runtime with the CONFIG SET command.

Common policies: allkeys-lru, allkeys-lfu, volatile-lru, volatile-lfu, volatile-random, allkeys-random, noeviction.

Examples
Evicts least recently used keys from all keys when memory is full.
Redis
CONFIG SET maxmemory-policy allkeys-lru
Evicts least frequently used keys but only those with an expiration set.
Redis
CONFIG SET maxmemory-policy volatile-lfu
Evicts random keys from all keys when memory is full.
Redis
CONFIG SET maxmemory-policy allkeys-random
Sample Program

This example sets Redis to use 100 MB max memory and the allkeys-lru eviction policy. When memory is full, Redis removes the least recently used keys from all keys.

Redis
CONFIG SET maxmemory 100mb
CONFIG SET maxmemory-policy allkeys-lru

SET key1 value1
SET key2 value2

# Simulate memory full by adding many keys
# Redis will evict least recently used keys automatically

GET key1
GET key2
OutputSuccess
Important Notes

LRU means Least Recently Used: Redis removes keys not used recently.

LFU means Least Frequently Used: Redis removes keys used less often.

Random eviction removes any key randomly, which is simple but less efficient.

Summary

Eviction policies control how Redis frees memory when full.

LRU and LFU keep the most useful data by usage patterns.

Random eviction removes keys without pattern, simpler but less smart.