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.
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:
- TTL (passive). Do nothing, and let entries expire. No invalidation code to forget, but data can be stale for the whole TTL.
- Delete on write (active). When you update the database, delete the cache key right away. Fresh, but every place that writes must remember it.
- 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.
- 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.
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:
- Request A misses the cache and starts a slow database read. It gets the old name.
- Your update saves the new name and deletes
user:123. - 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
- Eviction makes room; invalidation removes what’s no longer true. You need both.
- LRU removes the least recently used item, and is the safe default. LFU keeps long-term favourites, but new items struggle.
- Set a memory limit and a policy (
maxmemoryplusallkeys-lruin Redis), and never use an unboundedHashMapas a cache. - Invalidate with a TTL everywhere, plus delete-on-write for data that changes. Use events or tags when one change affects many entries.
- Stop thundering herds with a rebuild lock, early refresh and TTL jitter.
- 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