Why you need it

A cache lives in memory, and memory is small and expensive. When it is full and a new copy needs a place, something has to go. Throw out the wrong thing and the next visitor gets a slow miss; throw out the right thing and nobody notices.

Think of it like this

A small fridge. When it is full and you bring home milk, you take out whatever you have not touched for the longest time, not the butter you used this morning.

Where you’ll find it

  • Redis: Lets you choose how it frees memory, including LRU and LFU, with one setting.
  • Caffeine: The Java cache inside many big apps uses a smarter mix of recency and frequency (W-TinyLFU).
  • Your computer: Your CPU's caches and your operating system's file cache use LRU-like rules all the time.

What to know first

Eviction. Throwing a copy out of the cache to make room.

Recency and frequency. Recency: how long ago something was last used. Frequency: how often it is used.

How it works

  1. LRU: least recently used goes first. Every time a copy is used, move it to the "just used" end. When space runs out, throw out the one at the other end. This is the line in the animation.
  2. Why LRU works. What was used recently is likely to be used again soon. Most real traffic behaves like this, so LRU is the default almost everywhere.
  3. Where LRU fails. One big scan, like a report reading every product once, pushes out all the popular copies even though it will never ask again.
  4. LFU and mixes. LFU (least frequently used) throws out what is used least often, which survives scans but is slow to forget old favourites. Modern caches mix the two, like Caffeine's W-TinyLFU.
  5. Fast enough to use on every request. Real caches do not keep a perfect line. Redis, for example, picks a few random keys and evicts the oldest of them: nearly as good as true LRU and much cheaper.

An example

A cache holds 3 items: hats, shoes, bags. Order of last use: bags (oldest), hats, shoes (newest).

Someone asks for coats. The cache is full, so bags goes, and coats joins at the newest end.

Next someone asks for shoes: a hit, and shoes moves to the newest end. Now hats is the oldest, and it will go next.

Further reading

  • Key eviction, Redis docs. Each policy Redis offers, and how its approximate LRU works. Start with this one.
  • Cache replacement policies, Wikipedia. A tour of every common policy, with small examples.
  • Caffeine, Ben Manes. A real cache with links to the research behind its policy.