← Lessons

quiz vs the machine

Gold1420

Databases

Cache Eviction Policies in Redis

What Redis throws away when memory fills up.

5 min read · core · beat Gold to climb

When Memory Runs Out

Redis lives in RAM. When data approaches the maxmemory limit, Redis must decide whether to reject writes or evict existing keys. The maxmemory policy sets that behavior.

The Main Policies

  • noeviction: reject writes with an error once full. Safe for a primary data store you cannot lose.
  • allkeys lru: evict the least recently used key among all keys. The default cache choice.
  • allkeys lfu: evict the least frequently used key, favoring keys that are rarely accessed over merely old ones.
  • volatile lru and volatile lfu: same idea but only among keys that have an expiry set.
  • allkeys random and volatile ttl: evict at random or evict the key nearest expiry.

LRU Versus LFU

LRU assumes recently used means soon needed, but a single scan can flush hot keys. LFU tracks access frequency with a decaying counter, so a burst of one time reads does not evict a key that is popular over time. For many caches LFU gives better hit rates.

Note that Redis uses an approximate LRU and LFU by sampling a few keys rather than scanning all of them, trading perfect accuracy for speed.

Key idea

When memory fills, the maxmemory policy decides what to drop, with noeviction protecting data and approximate LRU or LFU evicting cold keys for cache workloads.

Check yourself

Answer to earn rating on the learn ladder.

1. Which policy fits a cache where you want cold keys dropped by access frequency?

2. Why might LFU give a better hit rate than LRU?

3. What does noeviction do when memory is full?