Nguyen Le Phong

Caching Strategies and the Pitfalls That Bite Later

Cache-aside, read-through, write-through and write-behind compared, plus TTLs, invalidation order, stampedes and the metrics that show a cache actually helps.

Right after lunch, the analytics dashboard starts loading slowly. Yesterday it was fine. Today it spins for eight seconds. One person opens the network tab, another pulls up the database chart, and within ten minutes someone types the classic line in the team chat: "should we just add a cache?"

Four engineers gather around a slow analytics dashboard, discussing whether a cache would actually fix the problem.
Most cache conversations start with a slow page, usually before anyone has agreed where the time is going.

Often the answer is yes, and caching is one of the cheapest speed-ups you can buy. If many users ask for the same expensive answer, computing it once and keeping a copy close by makes sense. It's like keeping the folder you use every day on your desk instead of walking to the archive room each time. The desk is faster. The archive is still where the real record lives. Most caching bugs come from forgetting which one is which.

So before the how, one check: find out why the page is slow. If the query is missing an index or pulls ten times more rows than it shows, a cache only hides that, and the first cache miss still takes eight seconds. Sometimes the better fix is an index or a smaller query (see Scaling the Database), or a precomputed read model (CQRS). When the work really is expensive and repeated, read on.

Cache-aside: the pattern you'll use first

Most teams start with cache-aside, also called lazy loading. The application checks the cache first. On a hit, it uses the value. On a miss, it reads from the database, stores the result in the cache with an expiry, and returns it. When data changes, the application updates the database and then deletes the cached entry, so the next read loads fresh data (Cache-Aside pattern, Azure Architecture Center).

// Read: try the cache, fall back to the database
async function getProduct(id) {
  const key = `product:v1:${id}`
  const cached = await cache.get(key)
  if (cached) return JSON.parse(cached)
  const product = await db.products.findById(id)
  if (product) await cache.set(key, JSON.stringify(product), { EX: 300 })
  return product
}

// Write: update the database first, then delete the cache entry
async function updateProduct(id, changes) {
  await db.products.update(id, changes)
  await cache.del(`product:v1:${id}`)
}

The order in updateProduct matters. Microsoft's guide spells it out: if you delete the cache entry first, another request can miss, read the old row before your update lands, and put the stale value right back. Facebook's memcache setup makes the same choice of deleting on write instead of updating the cached value, because deletes are idempotent and safe to repeat (Scaling Memcache at Facebook, NSDI 2013).

Cache-aside is popular because you can add it one read path at a time, and if the cache goes down, the app still works, just slower. The cost is that your application now owns the awkward parts: the key, the expiry, the miss path and invalidation. AWS also lists the miss penalty plainly: a miss costs three trips (check the cache, query the database, write the cache), and data can go stale because nothing updates the cache when the database changes (ElastiCache caching strategies).

Read-through, write-through, write-behind

The other common strategies move some of that work out of your application code. Each one makes a different trade:

StrategyHow it worksGood atWatch out for
Cache-asideThe app checks the cache, loads from the database on a miss and fills the cacheEasy to add, the app survives a cache outageMiss penalty, stale data until expiry or invalidation
Read-throughThe app only talks to the cache, and the cache loads missing data itselfLoading logic lives in one placeNeeds a cache library or product that supports loaders
Write-throughEvery write updates the database and the cache togetherReads see fresh data right after a writeSlower writes, and the cache fills with data nobody reads
Write-behindThe write lands in the cache and reaches the database laterVery fast writesIf the cache loses data before the flush, those writes are gone

AWS suggests combining them in practice: write-through keeps hot data fresh, lazy loading fills in what's missing (after a node replacement, for example), and a TTL on every entry keeps unread data from piling up. Write-behind is the one to treat with real care. You're trading durability for speed, so use it only for data you can afford to lose or rebuild, like view counters.

TTL is a freshness budget

A TTL (time to live) says how long a cached value may be served before it has to be reloaded. Think of it as a budget for how stale the data is allowed to get. Five minutes is fine for a public article list, probably fine for a product catalog, and risky for permissions. An hour is harmless for a footer menu and a problem for prices.

So the useful question isn't "how long should the cache live?" Ask instead: how stale can this screen get before a user notices or gets hurt, and what happens if the stale value is wrong? A slightly old view count bothers no one. A price that changed an hour ago turns into a support ticket.

A product team looks over a hand-drawn data-flow diagram, talking through cache keys, TTLs and where the source of truth lives.
Cache design gets safer once the team can point at the real read path, the shape of each key and how long stale data may live.

Invalidation, and why keys decide how hard it is

Phil Karlton's line gets quoted for a reason: "There are only two hard things in Computer Science: cache invalidation and naming things" (via Martin Fowler). The database changed, so which cache entries are now wrong? Say a user changes their display name. That name might be cached inside a profile card, a team list, an audit view, a search index, a notification template and the @mention autocomplete. If you designed the keys around tables instead of around the screens that read them, invalidation turns into a hunt through the codebase.

A few habits keep it manageable:

  • Cache the thing you invalidate. If you can name the key from the id that changed (user:42:profile), deleting it is one line. Big composite blobs that embed other entities are where invalidation gets lost.
  • Version the key format. A prefix like v1 lets you change the shape of cached values on deploy without reading old, incompatible entries.
  • Keep a TTL even when you invalidate. Invalidation will miss a case sooner or later, and the TTL caps how long that mistake lives.
  • Know the remaining race. Even with "database first, then delete", a slow reader that loaded the old row just before your update can write it back just after your delete. Facebook added leases to memcache to deal with these "stale sets". For most apps, a short TTL is enough of a safety net.

When stale is fine, and when it isn't

Stale data isn't automatically a bug. A report can say "updated every few minutes". A feed can lag a little. A recommendation list doesn't need your last click reflected instantly.

Some data carries trust, though: permission checks, account balances, seat reservations, checkout prices, privacy settings. Microsoft's guide says cache-aside may not suit data that's sensitive or security related and recommends reading it from the primary source. Treat that as the default for this kind of data. If you do cache it, invalidate on every change and keep the TTL short. Better still, check the source at the moment that matters, like the final price at payment time.

Cache stampedes

A popular page's cached value expires at noon. At 12:00:01, thousands of requests miss together and all of them go to the database to rebuild the same answer. The cache was there to protect the database, and at the moment of expiry it sends the whole crowd straight at it. Andrea Vattani and coauthors describe the knock-on effect: the parallel rebuilds slow each other down, and that pulls even more requests into the stampede (Optimal Probabilistic Cache Stampede Prevention, VLDB 2015).

Facebook measured how much this matters (Scaling Memcache at Facebook, section 3.2.1). For a set of keys prone to this problem, tracked over a week, peak database queries from cache misses went from 17,000 per second without their lease mechanism to 1,300 per second with it. Leases let one client rebuild a key while the others wait briefly and retry.

Engineers review live monitoring dashboards and an event-flow diagram while discussing a spike of cache expiries and how to prevent stampedes.
Stampedes are easier to prevent when expiry spikes, miss storms and rebuild times show up on a dashboard before the next traffic peak.

You don't need Facebook's setup to get most of that benefit. The common tools:

  • Request coalescing. Concurrent misses for the same key share one rebuild. Go ships this as singleflight, and a few lines of JavaScript do the same inside one process.
  • Jittered TTLs. Add a random few seconds to each expiry so keys written at the same time don't all expire at the same time.
  • Early or background refresh. Rebuild a hot key a little before it expires. Vattani's paper gives a probabilistic way to decide when, and HTTP caches have stale-while-revalidate, which lets a cache keep serving the old response for a set number of seconds while it refreshes in the background (RFC 5861).
  • A lock or lease across servers. Coalescing inside one process doesn't stop fifty servers from each rebuilding once. A short lock in the shared cache does.
// One rebuild per key in this process; concurrent callers share the promise
const inFlight = new Map()

function loadOnce(key, loader) {
  if (!inFlight.has(key)) {
    inFlight.set(key, loader().finally(() => inFlight.delete(key)))
  }
  return inFlight.get(key)
}

// Spread expiries: 5 minutes plus up to 60 random seconds
const ttlSeconds = 300 + Math.floor(Math.random() * 60)

Memory limits and the numbers to watch

Caches are finite, and running out of memory can surprise you. In Redis, maxmemory defaults to zero on 64-bit systems, which means no limit at all. Once you set one, the eviction policy decides what goes. The Redis docs suggest allkeys-lru as a good default when a small set of keys gets most of the traffic (Redis key eviction).

If keys are too broad, values too big or the eviction policy doesn't match how the data is read, the cache spends its time filling up and throwing data away. A low hit rate can mean the cache is mostly adding a network hop, serialization cost and one more thing to run. Microsoft's guide says it directly: when most requests miss, the overhead can outweigh the benefit.

So "we have a cache" doesn't tell you much. Track a few numbers per cache, ideally per key prefix:

  • Hit rate. Redis gives you keyspace_hits and keyspace_misses in INFO stats.
  • Miss latency, which is what users feel on a cold path.
  • Evictions and expirations. Lots of evictions can mean the wrong keys are being dropped, and lots of expirations can mean the TTL is too short.
  • Value size and the age of values served.
  • Error rate and timeouts talking to the cache itself.

If you want those signals to exist before the incident, Observability as a Design Choice covers how to plan them in.

Picking the smallest cache that helps

Good caching design starts from what you promise users. Which answer is slow, and why? How often does it change? Who's allowed to see it? How wrong can it be, and for how long? Then pick the smallest cache that does the job:

  • An in-process cache for small reference data that rarely changes (country lists, feature config). It's the fastest option, but each instance has its own copy, so keep TTLs short.
  • A shared cache like Redis or Memcached for hot reads used by many instances.
  • A CDN or HTTP caching for public assets and pages, with Cache-Control doing most of the work.
  • No cache at all, when an index, a smaller query or a precomputed read model fixes the slowness at the source.
Five questions before "just add a cache"

What exactly is slow, and have we measured it? How often does the data change? How stale can it be for this screen? What deletes or refreshes it when the source changes? Which metric tells us the cache is helping?

Key takeaways

  • Measure first. A cache on top of a missing index hides the problem and still leaves a slow miss path.
  • With cache-aside, update the database first and then delete the cache entry. The reverse order puts stale data back.
  • Treat the TTL as a freshness budget per screen, and keep one even when you invalidate on writes.
  • Read permissions, balances and final prices from the source, or cache them only with tight invalidation.
  • Plan for stampedes with coalescing, jittered TTLs and early refresh, and watch hit rate, evictions and miss latency.

Next time a slow page brings up "just add a cache", take five minutes on the questions in that box first. Writing the answers down is half the design, and it's also what lets the next person change the cache safely.

What did you think?

Frequently asked questions

What is the cache-aside pattern?
The application checks the cache first. On a miss it reads from the database, stores the result in the cache with an expiry and returns it. On a write it updates the database and then deletes the cached entry, so the next read loads fresh data. It's easy to add one read path at a time, and the app keeps working if the cache goes down.
Should I update the database or delete the cache first?
Update the database first, then delete the cache entry. If you delete first, another request can miss, read the old row before your update lands and write the stale value back into the cache. A short TTL is still worth keeping as a safety net for the rare race that remains.
What is the difference between write-through and write-behind caching?
Write-through updates the database and the cache in the same write, so reads see fresh data right away at the cost of slower writes. Write-behind writes to the cache first and updates the database later, which makes writes fast but can lose data if the cache fails before it flushes.
What is a cache stampede and how do I prevent it?
A stampede happens when a popular key expires and many requests miss at once, all rebuilding the same value against the database. Common fixes are request coalescing so one caller rebuilds, random jitter on TTLs, refreshing hot keys a little before they expire, and a short lock or lease shared across servers.
How do I know if a cache is actually helping?
Track hit rate, latency on misses, evictions, expirations, value size and errors talking to the cache. In Redis, keyspace_hits and keyspace_misses in INFO stats give you the hit rate. If most requests miss, the cache may be adding more overhead than it saves.