Computer ScienceCachingArchitectureBackendPerformance

A Mental Model for Cache Invalidation

Why is cache invalidation so notoriously hard? A clear mental model covering data drift, TTL, cache-aside, SWR, versioned keys, and how to stop cache stampedes.

PRAS Samin

PRAS Samin

December 2, 2026

1 views

9 min read

Adding a cache to a slow app feels like magic. You drop Redis in front of your database, wrap a query in three lines of code, and suddenly a 400ms endpoint responds in 4ms.

Then a user updates their profile picture, refreshes the page, and still sees the old one. Or worse-someone cancels a subscription, and the cache keeps letting them in for the next hour.

That is why cache invalidation has such a bad reputation. Caching itself is easy. Knowing when to throw the copy away is the hard part.


"There are only two hard things in Computer Science: cache invalidation and naming things."

Phil Karlton
- Phil Karlton• Computer Scientist (Netscape) (karlton.org)

The Golden Rule: A cache is just a fast copy of your real data. The moment you make a copy, it starts drifting away from the source of truth. Every cache invalidation strategy is simply a trade-off between speed, freshness, and complexity.


Why Caches Break: Data Drift

If your data never changed, you would never need to invalidate anything. You could cache every database row forever and enjoy 1ms response times for life.

Problems start because your database keeps moving forward while your cache holds onto a snapshot from the past:

Data Drift

Notice what makes this tricky: neither the database nor Redis threw an error. Everything returned 200 OK, yet your user is looking at wrong data.

And in a real production app, Redis isn't the only place holding a copy.


Where Caches Actually Live

When a user loads a page, their request might pass through four or five separate caches before it ever touches your database:

Cache Request

Each layer makes reads faster, but adds one more copy you might need to clear when data changes:

  • Browser Cache: Lives on the user's device. You cannot reach into someone's laptop and delete it-you can only control it upfront with HTTP headers or new asset URLs.
  • CDN / Edge (Cloudflare, Vercel): Lives in data centers around the world. Clearing it takes an API purge call and can take seconds to propagate globally.
  • In-Memory Cache: Lives inside your server's RAM. Blazingly fast, but if you run 5 server pods, each pod has its own separate memory copy.
  • Distributed Cache (Redis / Memcached): A shared cache all your servers talk to. Much easier to invalidate in one place.

The 4 Core Invalidation Strategies

You don't need to invent a custom caching system from scratch. Almost every production system relies on one of these four patterns:


Strategy 1: Time-To-Live (TTL)

RedisUpstashNGINX

Attach an expiration timer to every cached item. When time runs out, the cache throws it away automatically and fetches a fresh copy on the next request.

// ❌ DANGEROUS: Cached forever until Redis runs out of memory
await redis.set(`trending:posts`, JSON.stringify(posts)); 

// ✅ SAFE: Auto-expires after 60 seconds
await redis.set(`trending:posts`, JSON.stringify(posts), { ex: 60 }); 

With TTL, you are making a clear deal: "I am okay if users see data that is up to 60 seconds behind reality."

  • Use it for: Trending feeds, analytics dashboards, public leaderboards, weather, and API rate-limit windows.
  • Avoid it for: Account balances, permission checks, inventory counts, or anything where stale data causes real bugs or security issues.

Strategy 2: Cache-Aside + Explicit Purge

RedisPostgreSQLTypeScript

When you cannot wait 60 seconds for stale data to expire, you use Cache-Aside:

  1. On Read: Check Redis. If it's there (hit), return it. If not (miss), query PostgreSQL, save the result in Redis with a safety TTL, and return it.
  2. On Write: Update PostgreSQL, then delete the key from Redis.

Notice that last word: delete, not overwrite.

async function updateUserProfile(userId: string, name: string) {
  await db.users.update({ where: { id: userId }, data: { name } });

  // ❌ RISKY: Overwriting the cache can race with another concurrent write
  await redis.set(`user:${userId}`, JSON.stringify({ id: userId, name })); 

  // ✅ SAFE: Delete the key so the next reader fetches fresh state
  await redis.del(`user:${userId}`); 
}

Why is DEL safer than SET?

Imagine Request A and Request B update the same user at almost the same millisecond. Request A finishes its database write first, but its redis.set gets delayed by a network hiccup and runs after Request B's redis.set. Now your database has B's data, while Redis is stuck holding A's older data.

Deleting the key avoids writing stale data back into Redis-and always keeping a fallback TTL (e.g., 1 hour) ensures that even if the delete call fails, the stale copy won't live forever.


Strategy 3: Stale-While-Revalidate (SWR)

Next.jsVercelTanStack

Normally, when a cache entry expires, the next unlucky user has to sit and wait for a slow database query before the page loads.

Stale-While-Revalidate flips that around. It says: "Give the user the slightly old copy right now in 5ms, and refresh it in the background."

In HTTP headers, it looks like this:

Cache-Control: public, s-maxage=60, stale-while-revalidate=300

Here is what happens over time:

  • 0s to 60s: The CDN serves the cached copy directly. Fresh and instant.
  • 61s to 360s: The CDN still serves the cached copy instantly, but triggers a background request to your server to rebuild the cache for the next person.
  • After 360s: The stale window is over, so the next request waits for a fresh response.

This is the exact mental model behind Next.js revalidate / revalidateTag, Cloudflare edge caching, and client libraries like TanStack Query. Users almost never feel a cold cache miss.


Strategy 4: Versioned Keys & Content Hashing (The Cheat Code)

CloudflareViteWebpack

The cleanest way to solve cache invalidation is to never invalidate at all.

Instead of mutating or deleting a key in place, you bake the version or content hash directly into the key name:

// Static JS/CSS bundles in production:
// /assets/app.8f3a9c12.js  <-- Cached in browsers for 1 year!
// Next deploy builds:
// /assets/app.d41b7e09.js  <-- Brand new URL, zero stale files

// Dynamic database data with a version pointer:
const version = await redis.get(`user:${userId}:version`) ?? "1";
const cacheKey = `user:${userId}:v${version}`;

When the user updates their data, you simply increment user:42:version to 2 (or publish a new filename).

  • All new requests immediately read user:42:v2.
  • No existing reads get half-updated data.
  • The old v1 key simply sits untouched until its TTL expires or Redis evicts it automatically.

The 3 Cache Traps Under High Load

Caches work great with 10 users. At 10,000 requests per second, three sneaky failure modes can take down your database even when your cache code looks fine:


Cache Stampede (The Thundering Herd)

Imagine your homepage hero data is cached in Redis for 60 seconds, and 5,000 users hit your site every second.

The exact millisecond that key expires, all 5,000 requests miss Redis at once and fire 5,000 identical heavy queries straight at PostgreSQL, crashing your database.

The Fix: Use request coalescing (also called singleflight or a mutex lock). Only let the first request query the database while the other 4,999 wait a few milliseconds for that single result to populate Redis-or refresh hot keys in the background before they expire.


Cache Penetration (Missing Key Attacks)

What happens when someone (a bug, a bot, or an attacker) keeps requesting /api/products/999999999, an ID that doesn't exist in your database?

Because it doesn't exist, nothing ever gets saved in Redis. Every single request misses the cache and hits PostgreSQL directly.

The Fix: Cache the "NOT_FOUND" / null result for a short TTL (like 30–60 seconds), or put a Bloom Filter in front of the cache to reject impossible IDs in memory before touching the database.


Cache Avalanche (Synchronized Expiration)

Suppose you restart your server or run a script that pre-warms 50,000 cache keys at 12:00:00 PM, all with TTL = 3600 seconds.

At 1:00:00 PM sharp, all 50,000 keys expire at the exact same second, sending a massive wave of cache misses straight to your database.

The Fix: Add random jitter to every TTL:

const baseTtl = 3600;
const jitter = Math.floor(Math.random() * 300); // 0 to 5 mins random offset
await redis.set(key, value, { ex: baseTtl + jitter });

The Cache Invalidation Decision Matrix

Use this cheat sheet to pick the right caching pattern for your data:

Data TypeStaleness ToleranceRecommended Pattern
Static assets (JS, CSS, images)Zero (must match deploy)Content-hashed URLs (app.a1b2c3.js) + 1 year TTL
Feeds, stats, leaderboardsSeconds to minutesShort TTL + random jitter
User profiles, settings, CMSVery low (read-after-write)Cache-Aside + DEL on write + fallback TTL
Blog posts, marketing pagesMinutes (speed matters most)Stale-While-Revalidate (s-maxage + swr)
Bank balances, auth, inventoryZeroDon't cache (or invalidate synchronously inside transactions)

The 4 Questions to Ask Before Adding a Cache

Before wrapping a function or endpoint in Redis or a CDN, pause and ask yourself:

  1. Do I actually need a cache yet? (Can a missing database index fix the slow query first without adding stale-data bugs?)
  2. How stale is too stale? (If a user sees old data for 30 seconds, is it annoying-or does it break billing or security?)
  3. Who can change this data? (If a background job, webhook, or admin panel updates the database, will it remember to purge the cache key too?)
  4. What happens if Redis goes down or restarts empty? (Will my database survive a cold start without a stampede?)

Summary

Cache invalidation only feels mysterious when we treat caches as magic speed boosters instead of temporary copies of truth.

Keep your caching simple: Fix slow queries at the database first, prefer deleting keys (DEL) over overwriting them, add jitter to your TTLs, and never cache data that cannot afford to be slightly stale.

Once you know where every copy lives and how long it's allowed to drift, caching stops causing phantom bugs and starts doing what it was meant to do: keep your app fast.