Cache eviction and invalidation explained: LRU vs LFU, TTL and the thundering herd problem

A cache is small and data keeps changing. Eviction decides what to throw out when memory is full. Invalidation removes data that's no longer true. Learn LRU, LFU, FIFO and TTL, the four ways to invalidate a cache, and how to stop a thundering herd from flattening your database.

A small fridge, labelled cache, is full. On the left, a jar of jam is taken out to make room, labelled 'Eviction: full, so something must go', with LRU, LFU and FIFO underneath. On the right, a milk carton with an old expiry date is crossed out and thrown away, labelled 'Invalidation: no longer true, so it must go', with TTL, delete on write and events underneath. A banner reads 'What leaves the cache, and when?'
Fig. 1 — Eviction makes room. Invalidation removes what's wrong. A healthy cache needs both.

Think of a cache as a small fridge. Two things can make you take something out of it:

  • It’s full, and you need space for something new. That’s eviction.
  • It’s gone off. The milk is past its date, so you throw it away even if there’s room. That’s invalidation.

Caches have exactly these two problems. A typical cache might have 16 GB of memory in front of a 10 TB database, so it can hold less than 0.2% of the data. And the database keeps changing, so some of what’s cached is no longer true.

“Eviction answers “what do we throw out to make room?” Invalidation answers “what’s no longer true?””

Skip eviction and the cache grows until the server runs out of memory. Skip invalidation and users see old prices forever. Let’s take each in turn.

Cache eviction policies

When the cache is full and a new item arrives, an eviction policy picks which old item to remove. The goal is always the same: keep the items most likely to be asked for again, so the hit rate stays high.

LRU: least recently used

Remove the item that hasn’t been used for the longest time.

Picture a stack of books on your desk. Every time you read one, it goes back on top. When the stack is too tall, you take one off the bottom: the book you haven’t touched in the longest time.

  • Good for: most everyday data. Recently used things tend to be used again soon (sessions, news, product pages).
  • Weak spot: a single big scan. A report or a bot that reads thousands of items once pushes out your genuinely popular items.

LFU: least frequently used

Remove the item that’s been used the fewest times. Each read is a vote, and the item with the fewest votes goes.

  • Good for: stable favourites, like best-selling products or common static files.
  • Weak spot: new things struggle to get in. A product that’s trending today has few votes yet, while last month’s hit sits there on old votes.
The same cache with room for three items, and the same history of reads: A is read 50 times early on, then B, then C, then D arrives and something must go. Left, LRU: items are lined up by when they were last used. A was used longest ago, so LRU evicts A, even though it's the most popular. Right, LFU: items are lined up by how often they were used. A has 50 reads, B has 3 and C has 1, so LFU evicts C and keeps A.
Same reads, different victims. LRU looks at when an item was last used. LFU looks at how often it's been used.

FIFO: first in, first out

Remove the item that was added first, like a queue. It doesn’t care whether an item is popular. It’s simple, and it works for data where newer simply means more useful, such as recent log lines. For most caches it gives a lower hit rate than LRU.

TTL: time to live

Each item gets an expiry time, and it’s removed when the time is up, popular or not. Strictly, a TTL is about freshness, not memory, but in practice it’s the most common way entries leave a cache. You’ll almost always combine it with LRU or LFU.

Set the TTL by how fresh the data must be:

Kind of data Example TTL
Rarely changes logos, country lists days
Changes daily product descriptions hours
Changes often prices, stock levels minutes
Near real-time live scores seconds
Security limits login tokens fixed, by policy

Which eviction policy to use

Policy Removes Best for Watch out for
LRU Least recently used Most apps; a safe default Big one-off scans
LFU Least often used Stable popular items New items can’t get in
FIFO Oldest added Logs, simple queues Ignores popularity
TTL Expired items Freshness, security Many items expiring together

In Redis, you choose with two settings: a memory limit and a policy.

# redis.conf
maxmemory 2gb
maxmemory-policy allkeys-lru     # or allkeys-lfu

The default, noeviction, doesn’t evict at all: once memory is full, Redis rejects new writes. That’s right for a database, and usually wrong for a cache. (Redis’s LRU and LFU are close approximations: it checks a small sample of keys rather than all of them, which keeps it fast.)

For a cache inside your Java app, never use a plain HashMap. It never removes anything, and one day you get an OutOfMemoryError. Use a bounded cache like Caffeine:

// Java · an in-memory cache that can't grow forever
Cache<Long, Product> products = Caffeine.newBuilder()
    .maximumSize(10_000)                       // evict when full
    .expireAfterWrite(Duration.ofHours(1))     // and expire after an hour
    .recordStats()                             // so you can watch the hit rate
    .build();

Caffeine’s eviction mixes recency and frequency, so it avoids the weak spots of both plain LRU and plain LFU.

Cache invalidation

Phil Karlton’s well-known line says the two hard things in computer science are cache invalidation and naming things. Invalidation is hard because the cache doesn’t know when the database changed. Something has to tell it, or it has to guess.

There are four ways to do it, from simplest to most powerful:

Four panels. 1, TTL: an entry carries a timer and is removed when the timer ends. Simple, but the data can be wrong until then. 2, delete on write: the service updates the database and then deletes the cache key straight away. Fresh, but every write path must remember to do it. 3, events: the service publishes a 'product updated' event, and a separate listener deletes the product, its category list and the search results. Decoupled, but the events must be delivered reliably. 4, tags: each cached item is tagged, for example category 7, and one call deletes every entry with that tag. Great for bulk changes, at the cost of storing the tags.
From simplest to most flexible. Most systems use a TTL everywhere, plus delete-on-write for data that changes.
  1. TTL (passive). Do nothing, and let entries expire. No invalidation code to forget, but data can be stale for the whole TTL.
  2. Delete on write (active). When you update the database, delete the cache key right away. Fresh, but every place that writes must remember it.
  3. Events. The service publishes a “product updated” event. A listener deletes everything affected: the product, its category page, search results. Writers don’t need to know every cache, but the events must not get lost.
  4. Tags. Store which entries belong together, like “everything in category 7”. Then one call clears the whole group, which is handy for “10% off all shoes”.

A good default: a TTL on everything, plus delete-on-write for data that changes. The TTL is your safety net for the times a delete goes missing.

The thundering herd problem

A popular item, say the home page’s product list, expires at exactly 12:00:00. At that moment, 10,000 requests arrive. All of them miss, and all of them go to the database for the same data at once.

This is the thundering herd, also called a cache stampede. The database slows down, requests pile up, and it can fall over, all because of one expired key.

Top half, the problem: a popular cache key expires at 12:00:00. A crowd of 10,000 requests misses at the same moment, and every arrow goes to the database, which turns red and overloads. Bottom half, the fix with a lock: the same 10,000 requests miss, but only one request gets the lock and rebuilds the value from the database. The other requests wait a few milliseconds and then read the fresh value from the cache. The database sees one query instead of 10,000.
Without protection, one expired key can send thousands of identical queries to the database. With a lock, the database sees one.

Three fixes, often used together:

  • Let only one request rebuild it. The first request to miss takes a short lock (Redis SET key value NX EX 10). It reloads the data and refills the cache. Everyone else waits a few milliseconds and reads the fresh copy. You can also serve the old value while one request refreshes it.
  • Refresh a little early. As an entry gets close to its expiry, let a request now and then refresh it in the background, before it actually expires. Users never see the miss. This is called probabilistic early expiration.
  • Add jitter to TTLs. If you load 10,000 products at once, all with a TTL of exactly one hour, they’ll all expire together an hour later. Add a small random amount to each TTL so they spread out:
// Java · 1 hour, plus or minus up to 5 minutes
long ttl = 3600 + ThreadLocalRandom.current().nextLong(-300, 300);
redis.opsForValue().set(key, product, Duration.ofSeconds(ttl));

What breaks, and how to fix it

What breaks What you see The fix
Everything expires at once A deploy clears the cache, or a bulk load expires all together, and the database is flooded Warm the cache with the top items before taking traffic, and use TTL jitter
An invalidation silently fails The database is updated, but the delete threw an error that was swallowed. Users see old data Retry the delete. If it still fails, put it on a queue to retry later, and alert. Keep the TTL as a backstop
An unbounded in-app cache Memory slowly grows for weeks, then OutOfMemoryError Use a bounded cache (Caffeine with maximumSize), and watch its size
Hit rate suddenly drops 90% hits fall to 10%, and the database load jumps Check for: a cache restart, TTLs set too short, a memory limit that’s too small, a traffic change, or a bot scanning lots of rarely used items

Puzzle 1: the key that came back

Another request was already in the middle of loading that user:

  1. Request A misses the cache and starts a slow database read. It gets the old name.
  2. Your update saves the new name and deletes user:123.
  3. Request A finishes and saves what it read, the old name, into the cache.

The delete happened, but a slower request put old data back afterwards. It’s the same race as in caching strategies.

Fixes: a short TTL so the damage can’t last long; a second delete shortly after the update; or version numbers. Store a version with each cached value, and only allow a write to the cache if its version is newer than the one already there.

Puzzle 2: pick the eviction policy

  • (A) Video view counters → LFU. Popular videos are read constantly. Keep the busy counters in memory.
  • (B) Login tokens → TTL. A token must expire at a fixed time for security, however often it’s used.
  • (C) News articles → LRU. Recent news is what people read. Yesterday’s story can go.
  • (D) Search results → LRU plus a TTL. Recent searches tend to repeat, but the catalog changes, so results must also expire.

The rule of thumb: “used a lot” → LFU, “used recently” → LRU, “must expire on time” → TTL.

Key takeaways

  1. Eviction makes room; invalidation removes what’s no longer true. You need both.
  2. LRU removes the least recently used item, and is the safe default. LFU keeps long-term favourites, but new items struggle.
  3. Set a memory limit and a policy (maxmemory plus allkeys-lru in Redis), and never use an unbounded HashMap as a cache.
  4. Invalidate with a TTL everywhere, plus delete-on-write for data that changes. Use events or tags when one change affects many entries.
  5. Stop thundering herds with a rebuild lock, early refresh and TTL jitter.
  6. Watch the hit rate. A sudden drop is often the first sign that something’s wrong.

That completes the Performance & caching (deep) thread: why we cache, how to keep a cache in step with the database, and what to remove and when. Next comes Part 8, load, traffic and protection, starting with load balancing.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.