Video in progress
Why is LRU in Redis called "approximate", and what does `maxmemory-samples` affect?
Redis doesn't keep a true LRU list, since that would need extra pointers on every key. It takes a few random keys and evicts the oldest; maxmemory-samples is that sample size, and a larger value is more accurate but costs more CPU.
📖 Answer
Classic LRU needs a doubly linked list: on every access the element moves to the head. With hundreds of millions of keys, that costs both memory and time.
Instead, Redis stores a 24-bit "last access time" in each object. When eviction is needed:
maxmemory-samples(default 5) random keys are picked.- They are added to the eviction pool, a small sorted array that also holds the candidates left over from earlier samples.
- The oldest key in the pool is evicted.
Thanks to the pool, even 5 samples give a result very close to true LRU. If you set it to 10, it barely makes a difference, but eviction gets a bit more expensive.
maxmemory 4gb
maxmemory-policy allkeys-lru
maxmemory-samples 5
LFU uses the same 24 bits differently: an 8-bit logarithmic counter and 16 bits for the last decrement time. The counter drops over time according to lfu-decay-time, so yesterday's popular key doesn't stay forever.
In practice you rarely touch these settings. But if you answer "how does Redis LRU work?" with "it sorts all the keys", the interviewer will catch it right away.
Sign up to mark studied questions and save your progress.