Skip to the guide

Eviction: LRU, LFU and TTL

BeginnerConcept3 pages

A cache is smaller than the data behind it, so something has to go when it fills up. Two questions get mixed up here: which key leaves when memory is full (eviction), and how long a key may live before it's too old (TTL). Interviewers want both, with numbers.

The fridge

A fridge has two reasons to throw food out. The use-by date: yoghurt past it goes in the bin even when there's plenty of room. And space: after a big shop, something has to come out so the new things fit. You might take out whatever nobody has touched for the longest time, or whatever the family eats least often. The date is about freshness, the full shelf about space, and they're separate decisions.

  • the use-by date → TTL, a lifetime set on each key
  • a full fridge → the cache's memory limit (maxmemory in Redis)
  • out goes what nobody touched for longest → LRU, least recently used
  • out goes what the family eats least → LFU, least frequently used
  • the big shop → new keys, stored after misses
  • the family → the readers, whose reads decide what counts as popular