LRU vs LFU in depth

Difficulty: Intermediate

Question

How do LRU and LFU eviction work in Redis, and when would you prefer LFU over LRU?

Answer

LRU (Least Recently Used) evicts keys that have not been accessed for the longest time, while LFU (Least Frequently Used) evicts keys that are accessed the least often. Prefer LFU when your workload has keys that are consistently popular over long periods, because LRU can throw out a hot key just because a burst of one-time reads touched many other keys more recently. Prefer LRU when recency is the best predictor of future access, such as session data or recently viewed items.

How Redis picks eviction victims

Eviction only happens when maxmemory is set and reached. The maxmemory-policy setting decides what to remove:

  • noeviction (the default): writes fail with an OOM error.
  • allkeys-lru / volatile-lru: approximated LRU over all keys, or only keys with a TTL.
  • allkeys-lfu / volatile-lfu: approximated LFU, available since Redis 4.0.
  • allkeys-random, volatile-random, volatile-ttl: simpler strategies.

Redis does not keep a perfect LRU linked list, since that would cost memory per key. Instead it samples maxmemory-samples keys (default 5) and evicts the best candidate from a small pool. Raising the sample count to 10 gets closer to true LRU at a small CPU cost.

How the LFU counter works

Each key has 24 bits in its object header that are used for eviction metadata. Under LFU, 8 bits store a logarithmic access counter and 16 bits store the last decrement time.

  • The counter is probabilistic. The more hits a key already has, the less likely each new hit increments it. lfu-log-factor (default 10) controls how fast it saturates, so 8 bits can represent roughly a million hits.
  • New keys start at a small value (5), so they are not evicted the instant they are created.
  • lfu-decay-time (default 1, in minutes) decrements the counter over time, so a key that was hot yesterday but cold today eventually becomes evictable.

LRU vs LFU side by side

AspectLRULFU
Signal usedTime since last accessAccess frequency with decay
Handles a one-time scanPoorly, scan pollutes the cacheWell, scanned keys have low counts
Reacts to new trendsInstantlySlower, new keys must build up counts
Inspect a keyOBJECT IDLETIME keyOBJECT FREQ key
Typical fitSessions, recent itemsProduct catalog, config, trending content

When LFU clearly wins

Imagine Flipkart caching product pages. A few thousand bestsellers get hit constantly. A nightly analytics job then reads 2 million long-tail products once each. Under LRU, those one-off reads are now the "most recent", and bestseller pages get evicted, causing a burst of database load in the morning. Under LFU, the long-tail keys have a counter of about 5 and get evicted first, while bestsellers with high counts survive.

Gotchas

  • Switching to LFU at runtime with CONFIG SET maxmemory-policy allkeys-lfu works, but existing keys need time to build meaningful counters.
  • OBJECT FREQ errors unless an LFU policy is active, and OBJECT IDLETIME is not meaningful under LFU.
  • volatile-* policies only consider keys with a TTL. If none have a TTL, they behave like noeviction.
  • redis-cli --hotkeys relies on LFU counters, so it only works with an LFU policy.
  • Eviction is a safety net. Check evicted_keys in INFO stats; a constantly rising number means the cache is undersized.
Which key gets evicted?. After a one-time scan, LRU evicts the popular key while LFU keeps it.
LRULFU
Bestseller key, 5000 hits, idle 30sEvicted firstKept
Scanned key, 1 hit, idle 1sKeptEvicted first
Brand new key, 1 hitKeptProtected by initial count
Key hot last week, cold nowEvictedEvicted after decay

Code examples

Switching to LFU and inspecting counters

# Cap memory and switch to LFU across all keys
redis-cli CONFIG SET maxmemory 2gb
redis-cli CONFIG SET maxmemory-policy allkeys-lfu

# Optional tuning (defaults shown)
redis-cli CONFIG SET lfu-log-factor 10
redis-cli CONFIG SET lfu-decay-time 1

# Access frequency counter for a key (LFU only)
redis-cli OBJECT FREQ product:1001

# Find hot keys using LFU counters
redis-cli --hotkeys

# Watch eviction pressure
redis-cli INFO stats | grep evicted_keys

OBJECT FREQ shows the logarithmic counter, not a raw hit count. A rising evicted_keys value means the cache is too small for the working set.

Key points

  • Default policy is noeviction; you must set maxmemory and a policy to get cache behaviour.
  • Redis LRU and LFU are approximations based on sampling (maxmemory-samples, default 5).
  • LFU uses an 8-bit logarithmic counter with time-based decay.
  • LFU resists cache pollution from one-off scans; LRU reacts faster to new trends.
  • Use OBJECT FREQ under LFU and OBJECT IDLETIME under LRU.

Common follow-up questions

  • Why does Redis approximate LRU instead of implementing it exactly?
  • What happens when a volatile-* policy is set but no keys have a TTL?
  • How would you detect that your cache is too small?
  • How do lfu-log-factor and lfu-decay-time change behaviour?

Interview tips

  • Give a concrete scenario, like a batch scan polluting the cache, rather than just definitions.
  • Mentioning sampling and maxmemory-samples shows you know how Redis actually implements this.
  • Point out that LFU needs warm-up and adapts slower to sudden trends; trade-offs impress more than a one-sided answer.

Concepts covered

maxmemory-policy, Approximated LRU, LFU Counter, lfu-decay-time, Hot Keys

More Redis & Caching questions