CodePark/ questions / TTL & eviction policies
START PRACTICINGPRACTICE
Backend question · Redis & caching › TTL & eviction policies

What eviction policies does Redis offer, and which would you choose for a pure cache?

For a pure cache, choose allkeys-lru, or allkeys-lfu when some keys stay popular for a long time.

Eviction means Redis deletes keys to free memory. It starts when memory use reaches the maxmemory setting. The policies are:

  • noeviction: the default. Redis evicts nothing, and writes fail with an OOM (out of memory) error.
  • allkeys-lru: evicts the least recently used keys, from all keys.
  • allkeys-lfu: evicts the least frequently used keys, from all keys.
  • allkeys-random: evicts random keys, from all keys.
  • volatile-lru, volatile-lfu and volatile-random: the same rules, but only for keys that have an expiry.
  • volatile-ttl: evicts the keys with an expiry that are closest to expiring.

A pure cache means every key can be rebuilt from the real data source. That is why allkeys-lru is the usual choice there. allkeys-lfu is often better when some keys stay popular for a long time.

Use a volatile-* policy when the same instance also holds data that must not be evicted. Give TTLs only to the cache keys. Keep noeviction for instances that store primary data, such as queues.

Redis does not track LRU and LFU exactly. It approximates them by sampling a few keys. You can tune the sample size with maxmemory-samples.

  • Eviction starts at maxmemory, and the default policy is noeviction.
  • allkeys-* policies consider every key, and volatile-* policies consider only keys with a TTL.
  • Use allkeys-lru or allkeys-lfu for a pure cache.
  • Use a volatile-* policy when the cache shares an instance with data you must keep.
  • Redis approximates LRU and LFU by sampling a few keys.