What is LFU in Redis: Explanation and Usage
LFU stands for "Least Frequently Used" and is a cache eviction policy that removes keys used least often when memory is full. It helps keep frequently accessed data in memory by tracking usage frequency and evicting the least used keys first.How It Works
Imagine you have a small shelf where you keep your favorite books, but the shelf can only hold a limited number. When the shelf is full and you want to add a new book, you decide to remove the book you read the least often. This is similar to how Redis's LFU eviction policy works.
Redis tracks how often each key is accessed. When memory is full, it removes the keys that have been used the least frequently to make space for new data. This way, the most popular or frequently used data stays in memory, improving performance.
LFU is different from other policies like LRU (Least Recently Used), which removes keys based on how recently they were accessed rather than how often. LFU focuses on long-term usage frequency, making it useful when you want to keep data that is consistently popular.
Example
This example shows how to configure Redis to use the LFU eviction policy and how it affects key eviction.
CONFIG SET maxmemory 100kb CONFIG SET maxmemory-policy allkeys-lfu SET key1 "value1" SET key2 "value2" # Access key1 multiple times to increase its frequency GET key1 GET key1 GET key1 # Add many keys to fill memory and trigger eviction for i in {3..1000}; do redis-cli SET key$i "value$i"; done # Check if key1 still exists (likely yes because it is frequently used) EXISTS key1 # Check if key2 still exists (likely no because it was used less) EXISTS key2
When to Use
Use LFU eviction in Redis when you want to keep data that is frequently accessed over time, even if it was not accessed recently. This is helpful for caching scenarios where some data is consistently popular, like user session data, product information, or frequently requested API results.
LFU is ideal when you want to avoid evicting data that is important but might not have been accessed very recently. It helps maintain a cache that favors long-term popularity rather than just recent usage.
Key Points
- LFU stands for Least Frequently Used eviction policy in Redis.
- It removes keys that are used least often when memory is full.
- LFU tracks usage frequency, not just recent access.
- Useful for caching data with consistent popularity over time.
- Configured with
maxmemory-policy allkeys-lfuin Redis.