What is LRU in Redis: Explanation and Usage
LRU stands for Least Recently Used, a memory eviction policy that removes the keys that have not been accessed for the longest time when Redis runs out of memory. It helps Redis manage limited memory by automatically deleting old or unused data to make space for new data.How It Works
Imagine your Redis memory as a small closet where you can only keep a limited number of items. When the closet is full and you want to add a new item, you need to remove something old to make space. The LRU (Least Recently Used) policy helps decide which item to remove by choosing the one you haven't used for the longest time.
In Redis, each key has a timestamp of when it was last accessed. When memory is full, Redis looks for keys that were used least recently and removes them first. This way, Redis keeps the most active data available and clears out the old, unused data automatically.
Example
This example shows how to configure Redis to use the LRU eviction policy and how it removes keys when memory is full.
CONFIG SET maxmemory 100kb CONFIG SET maxmemory-policy allkeys-lru SET key1 "value1" SET key2 "value2" GET key1 # Add many keys to exceed memory and trigger eviction for i in {3..1000}; do redis-cli SET key$i "value$i"; done # Check if key2 still exists EXISTS key2
When to Use
Use the LRU eviction policy in Redis when you have limited memory and want Redis to automatically remove old or unused data to keep your cache fresh. This is especially useful for caching systems where recent data is more important than old data.
For example, in a web application caching user sessions or frequently accessed pages, LRU helps keep the most relevant data in memory and removes stale sessions or pages that haven't been accessed recently.
Key Points
- LRU means removing the least recently used keys first when memory is full.
- It helps Redis manage memory automatically without manual cleanup.
- Useful for caching scenarios where recent data is more valuable.
- Configured via
maxmemory-policysetting in Redis.