Caching: strategies, eviction, invalidation, stampedes

A cache is a fast copy of data kept close to where it is used. It is the cheapest way to make a read-heavy system faster. It also brings the classic problems: stale data, a full cache, and many requests hitting the database at once. This lesson covers where to cache, how the cache and the database work together, what to remove when the cache is full, how to keep data fresh, and how to survive a stampede.

1. Why Caching Works

Real traffic is uneven. A small part of the data gets most of the reads: a few popular movies, trending posts, the home page. Caching keeps that hot part in fast memory. You do not need to cache everything. You need to cache the working set (see the estimation lesson).

What matters is the hit rate, the share of reads served by the cache. A small drop in hit rate means a big rise in database load (the worked example below shows the numbers), so always state the hit rate your design assumes.

What to cache:

  • Data that is read much more often than it changes: movie details, product pages, profiles.
  • Results that are costly to compute: a ranked list, a report, an aggregate query.
  • Data where being a little old is acceptable.

What not to cache: data that must always be exact (an account balance before a payment, stock during checkout), data that is different for every user and never reused, and data that changes faster than it is read.

2. Where to Cache

Layer Typical use Speed Notes
Browser or app Static files, API responses with cache headers No network at all Cannot be cleared from the server. Use versioned file names
CDN Images, video, static pages 10 to 50 ms, near the user Shared by many users. See the CDN lesson
In-process (on each app server) Small, hot data that seldom changes, such as configuration About 100 ns Each server has its own copy, so copies can disagree. Limited by heap size
Distributed (Redis, Memcached) Shared data: sessions, query results, objects 0.5 to 1 ms One copy for all servers. A network call away

A common setup uses two levels: a tiny in-process cache for the hottest items, backed by a shared Redis cache, backed by the database. The closer to the user, the faster it is, and the harder it is to invalidate. The database also caches in its own memory (the buffer pool), so give it enough RAM.

3. Caching Strategies

These patterns describe who reads and writes the cache and the database.

3.1 Cache-Aside (Lazy Loading)

The application checks the cache first. On a miss it reads the database and puts the result in the cache. This is the most common pattern, and Redis is usually used this way.

sequenceDiagram
    participant App
    participant Cache
    participant DB
    App->>Cache: get movie:42
    alt hit
        Cache-->>App: movie
    else miss
        Cache-->>App: nothing
        App->>DB: read movie 42
        DB-->>App: movie
        App->>Cache: set movie:42 with TTL
    end
public Movie getMovie(String id) {
    String key = "movie:" + id;
    Movie cached = cache.get(key);
    if (cached != null) return cached;                       // hit

    Movie movie = db.findMovie(id);                           // miss: load it
    if (movie != null) {
        long ttl = 600 + ThreadLocalRandom.current().nextInt(120); // seconds, with jitter: 10 to 12 minutes
        cache.set(key, movie, ttl);
    }
    return movie;
}

Only requested data is cached, and a dead cache only makes the system slower. The first request is slow, and data can be stale until it expires or is invalidated.

3.2 Other Strategies

Strategy How it works Good Risk
Read-through Like cache-aside, but the cache itself loads from the database on a miss Simpler application code Needs a cache that supports it
Write-through Every write goes to the cache and the database together, and returns when both succeed Cache is never stale. Reads after writes hit the cache Writes are slower. Caches data that may never be read
Write-around Writes go to the database only. The cache fills on the next read No cache pollution from write-heavy data First read after a write is a miss
Write-behind (write-back) Writes go to the cache, which saves them to the database later in batches Very fast writes. Batching reduces database load If the cache dies before saving, data is lost. Use for counters or data you can afford to lose
Refresh-ahead The cache reloads popular items shortly before they expire Hot keys never miss Wasted loads for items that are not read again

Default answer: cache-aside with a TTL, deleting the cached item when the data changes.

4. Eviction: What to Remove When Full

A cache has limited memory. When it is full, it must remove something to make room.

  • LRU (least recently used): remove the item not used for the longest time. It is a good default, because recently used data is likely to be used again.
  • LFU (least frequently used): remove the item with the fewest uses. It keeps stable favorites and resists one-time scans, but it is slow to forget items that were popular long ago.
  • TTL (time to live): every item expires after a set time, whatever the memory. This bounds staleness.

Redis has a memory limit (maxmemory, 0 meaning no limit until you set it) and an eviction policy, such as allkeys-lru, allkeys-lfu or volatile-ttl (only keys with a TTL, soonest to expire first). The default, noeviction, returns errors for writes at the limit. Exact LRU needs a list of all keys reordered on every read, which is costly, so Redis approximates it: it samples a few random keys (5 by default) and evicts the least recently used of them.

Caffeine, a Java in-process cache, uses Window TinyLFU. Plain LRU lets every new item in, so a big scan (a job that reads every movie once) can push out the popular items. Caffeine keeps approximate request counts, and when the cache is full it lets a new item in only if it is requested more often than the item it would remove. The counts are halved from time to time, so old popularity fades.

A cache that is too small evicts hot data. Size it for the working set, plus about 2 times overhead (the estimation lesson).

5. Invalidation: Keeping the Cache Fresh

When the data in the database changes, the cached copy is wrong. You have four tools:

  • TTL only: accept staleness up to the TTL. The simplest option, and right when a few minutes of staleness is fine.
  • Delete on write: after updating the database, delete the cache key. The next read reloads it. Prefer deleting over updating the cache with the new value, because two concurrent writers can leave the older value in the cache.
  • Event-driven: publish a change event (from the transaction log or an outbox table), and a consumer deletes or refreshes the keys. This works across services, and the cache is eventually consistent (see the consistency lesson).
  • Versioned keys: include a version in the key (movie:42:v7). A change creates a new key, and old keys expire. Browsers and CDNs often use this with file names such as app.3f9a.js.

Choosing a TTL. Ask how old the data may be before a user is harmed or annoyed, and how often it changes. A movie description can live for hours. A product price may need a minute. A short TTL keeps data fresher but lowers the hit rate and raises database load, so pick the longest TTL the business accepts, and still delete the key on every write.

5.1 The Stale-Write Race

Even "delete on write" has a race with cache-aside:

  1. Reader A misses the cache (the key is empty) and reads the old value from the database. A is slow and has not filled the cache yet.
  2. Writer B updates the database and deletes the cache key. The key is already empty, so the delete does nothing.
  3. Reader A now puts the old value into the cache. Nothing is left to remove it.

The delete ran too early, before the stale value was put in, so it could not remove it. The cache keeps the stale data until the TTL ends. This is rare but real. The safeguard is a TTL on every key. For stricter needs there are two fixes:

  • Delete again after a short delay. The writer deletes the key, waits a little longer than a slow read takes (for example 1 second), and deletes it again. This removes anything reader A put back in step 3.
  • Use versioned keys (the fourth tool above). After the update, readers ask for v7. Readers learn the current version from a cheap source, such as a small version counter that the writer increases after the database commit. Reader A can only write the old value under v6, which nobody reads any more, so it does no harm and expires.

6. Cache Stampedes

A stampede (also called a thundering herd) happens when one hot key expires and many requests miss it at the same moment. All of them go to the database to rebuild the same value. Suppose a hot movie page is read 5,000 times per second, and a rebuild takes 100 ms. When the key expires, about 5,000 × 0.1 = 500 requests find it missing, and all 500 run the same expensive query. The database slows down, the rebuild takes longer, and more requests pile up.

The fix is to make sure only one request rebuilds the key, while the others either wait for that result or use the old value.

6.1 Single Flight (Request Coalescing)

Inside one server. Keep a map of loads that are in progress. The first request for a key starts the database read and stores it in the map. Requests that arrive meanwhile find it there and wait for the same result, instead of starting their own read.

private final ConcurrentHashMap<String, CompletableFuture<Movie>> inFlight = new ConcurrentHashMap<>();
private final ExecutorService dbPool = Executors.newFixedThreadPool(32);   // own threads for database calls

Movie loadOnce(String id) {
    CompletableFuture<Movie> load = inFlight.computeIfAbsent(id,
        k -> CompletableFuture.supplyAsync(() -> db.findMovie(k), dbPool));
    try {
        return load.join();            // all callers share one database read
    } finally {
        inFlight.remove(id, load);     // the next miss starts a fresh load
    }
}

The caller then puts the result in the cache. This gives one database read per key per server, so 100 servers mean at most 100 reads, not 500. Use your own thread pool: the shared default pool is for CPU work, and blocking calls can starve it.

Single flight across servers. Use a short lock in the cache. A request that misses tries SET lock:movie:42 token NX PX 5000 (set only if absent, expires in 5 seconds). The winner reads the database, fills the cache, and releases the lock only if the stored token is still its own (a small Lua script does the compare and delete), so a slow winner cannot delete another request's lock. The others wait about 50 ms and read the cache again. The expiry guards against a crashed winner. If the value is still missing after a few retries, read the database.

6.2 Serve Stale While Refreshing

Store two times with each value: a soft expiry (when to refresh) and a later hard expiry (when to delete), for example 10 minutes and 10 minutes 30 seconds. After the soft expiry, every request still gets the old value, but each one first tries to take a short refresh lock (SET refresh:movie:42 1 NX PX 5000). Only one succeeds, and it refreshes in the background. The others fail to get the lock and return the old value at once, without waiting. When the refresh finishes, the value has new times, so later requests find it fresh. If the winner crashes, the lock expires after 5 seconds and the next request takes over. The key is never empty, so nobody waits and the database sees one read. If refreshes keep failing, the key goes empty at the hard expiry.

Refresh ahead (section 3.2) does the same job for keys you know are hot.

6.3 Related Failures: Different Problems, Different Fixes

These look like a stampede, but the cause is different, so the fix is too.

  • Cache avalanche: many different keys expire at the same time, or the whole cache goes down, and all those reads reach the database together. Keys loaded together with the same TTL expire together, for example after a restart. Fixes: TTL jitter (a random amount added to each TTL, as in section 3.1) to spread the expiry, filling a restarted cache slowly, cache replicas, and rate limits and load shedding in front of the database. Jitter does not help a stampede on one key: that is one TTL, not many.
  • Cache penetration: requests for keys that do not exist (a wrong or malicious ID) always miss, so every one reaches the database. Cache the "not found" result for a short time, or use a Bloom filter to reject IDs that cannot exist (see the probabilistic structures lesson).
  • Hot key: one key lives on one cache node. If a single movie gets 200,000 reads per second and a node handles about 100,000, that node is overloaded while the others sit idle, and adding nodes does not help. Fixes: a small in-process cache on every app server (TTL of a few seconds), or store the value under several keys (movie:42#0 to movie:42#9) and read a random one. The cost is that every update must change or delete all the copies.

7. Worked Example: A Movie Site at 432 Million Reads a Day

A movie site has 2 million movies. Each movie page takes about 4 KB in the cache. Readers make 432 million movie reads a day.

Load.

  • 432,000,000 ÷ 86,400 = 5,000 reads a second on average, and 20,000 at peak (4 times).
  • Without a cache, all 20,000 reads a second go to the database. One server cannot do that, so you would need many read replicas.

Hit rate. A cache read takes 1 ms and a database read takes 10 ms.

  • 95% hit rate: average latency = 0.95 × 1 + 0.05 × (1 + 10) = 1.5 ms. The database sees 1,000 reads a second at peak.
  • 90% hit rate: average latency is 2.0 ms, and the database sees 2,000 reads a second, twice as much.

Size. Reads are uneven. Suppose the hottest 20% of movies (400,000) get about 95% of the reads (an assumption). 400,000 × 4 KB = 1.6 GB. With 2 times overhead for keys and structures, that is 3.2 GB, so one Redis node of 8 GB plus a replica is plenty. For speed, 20,000 reads a second is far below the 100,000 operations a second that one node can do.

Freshness. Movie details change a few times a day, and a delay of 10 minutes is fine. Use cache-aside with a TTL of 10 minutes plus jitter, and delete the key when an editor saves a change.

Stampede check. A new release gets 5% of the reads: 1,000 a second. If its key expires and a rebuild takes 100 ms, about 1,000 × 0.1 = 100 requests miss together. A lock or serve-stale cuts this to one database read.

Watch: hit rate (alert below 92%), evictions per second (near zero), memory use, p99 cache latency and database reads per second.

8. Common Pitfalls

  • Caching without a TTL. Any invalidation bug then stays forever.
  • Updating the cache instead of deleting it under concurrent writes.
  • Same TTL for every key, causing avalanches.
  • Caching data that is seldom reused, which wastes memory and lowers the hit rate.
  • Cache as the only copy. The cache can lose data. The database stays the source of truth, except for deliberate write-behind.
  • No protection for hot keys. When a hot key expires, hundreds of requests hit the database together. Use single flight or serve stale.
  • Caching sensitive per-user data under a shared key. One user may see another's data.
  • No plan for a cold or failed cache. The database must survive the load, or you must shed it.
  • Using a cache to hide a slow query that should be fixed with an index.

9. Interview Questions This Lesson Prepares You For

  • How does cache-aside work, and what are its drawbacks? The app checks the cache, on a miss reads the database and fills the cache. Drawbacks: the first read is slow, data can be stale, and a stampede is possible on hot keys.
  • Compare write-through, write-around and write-behind. Write-through writes both together: simple and fresh, slower writes. Write-around writes only the database and lets reads fill the cache. Write-behind writes to the cache and saves later: fastest, but can lose data.
  • What eviction policy would you use? LRU as the default. LFU if popularity is stable and scans should not flush the cache. Always with a TTL.
  • How do you keep a cache consistent with the database? A TTL to bound staleness, delete the key on every write, and events for cross-service changes. Say that perfect consistency is not possible, and state the staleness you accept.
  • What is a cache stampede, and how do you prevent it? Many requests miss one hot key together and overload the database. Use single flight so one request rebuilds it, and serve stale while refreshing. Do not confuse it with an avalanche (many keys expiring together), which TTL jitter fixes.
  • Your cache hit rate drops from 95% to 90%. What happens? Database reads double, from 5% to 10% of traffic. Check for a cache that is too small, keys expiring together, or new traffic patterns.
  • One movie gets 200,000 reads a second. What do you do? One key lives on one cache node, which handles about 100,000 operations a second, so adding nodes does not help. Add a short-lived in-process cache on every app server, or store the value under several keys so the copies land on different nodes.