Skip to content

Cache-Aside: Invalidation, Stampedes, TTLs and Stale Reads

How cache-aside works against write-through, and how to stop stampedes, synchronized expiry and stale reads after writes in a production read path.

22 min readSystem pattern

Keep a fast, disposable copy of hot read data next to the database. The application loads it lazily on a miss and invalidates it on write. Read traffic then scales with the cache, and the database stays the single source of truth.

Cache-aside is the caching pattern interviewers expect you to reach for first, and it is also the one that most often breaks in production. The application owns the cache. It reads the cache first, falls back to the database on a miss, and writes the result back. The happy path is easy. The hard parts are what happens when thousands of keys expire in the same second, when a writer and a reader race on the same key, and when you have to explain why the TTL is 60 seconds and not 10 minutes. This guide follows one invented incident at a grocery delivery company through to a design you can defend. It also contrasts cache-aside with write-through so you can say when each one fits.

The problem

A situation where the obvious design starts to hurt.

Pantrybox is an invented grocery delivery app. Its catalog-service answers GET /products/{sku} for product pages, search results and the basket. That is about 6,000 requests per second on a normal evening and 22,000 at the Saturday 09:00 promo launch. Product rows live in Postgres: one primary, two read replicas, max_connections 500. A Redis cluster in front of it has a 98 percent hit rate, so the database normally sees a few hundred product reads per second.

Before one Saturday launch, a warm-up job wrote 40,000 promo product keys at 08:45, every one with a fixed 15 minute TTL. At 09:00:00 traffic quadrupled and all 40,000 keys expired in the same second. Misses jumped from roughly 400 to 18,000 per second, all running the same 8 ms product query. Under that load the query took 900 ms and connections hit the 500 limit. Catalog p99 went from 25 ms to 7.8 s, and checkout returned errors for 14 minutes. The busiest key, the oat milk 1 L promo, had about 3,000 concurrent requests querying Postgres for the same row.

The postmortem found a second bug. When the pricing team cut a price, pricing-service committed the UPDATE and then SET the new value into Redis. A catalog request that had missed a moment earlier read the row from a replica lagging 400 ms, and its SET landed after the writer's. The old price stayed cached until the TTL ran out. For up to 15 minutes, shoppers saw 3.49 on the product page and 2.99 at checkout.

You are asked to fix both without giving up the cache. That means no synchronized expiry, no herd on a hot key, and a bounded, explainable staleness window after writes.

The solution

What the pattern proposes.

Keep cache-aside, but make each step deliberate.

Reads: catalog-service checks Redis and returns on a hit. On a miss it takes a short lease with SET lease:{key} NX PX 3000. The winner queries Postgres and writes the value back. Everyone else polls the cache every 50 ms for up to 250 ms, and only then falls back to the database. A refill costs one row query per key, not thousands.

TTLs: every entry gets a soft expiry of 60 s and a hard Redis TTL of 300 s. Both are scaled by a random factor of plus or minus 10 percent, so keys written together expire spread out. After the soft expiry, the first request takes the lease and refreshes while every other request keeps serving the old value. Hot keys never actually go missing. One request refreshes them while everyone else is still served from cache.

Writes: pricing-service commits to Postgres and then deletes the key. It never writes the new value into the cache, so the next reader loads from the source of truth. A reader that loaded before the commit can still write an old value after the delete. To close that race, a change-data-capture consumer tails the Postgres WAL and issues a second delete about 1 s after each commit. If both deletes are lost, the 60 s soft TTL is the upper bound on staleness. Cache fills read from the primary, never a replica, so replica lag cannot bring an old row back.

Why not write-through? In write-through, the write path updates the cache and the database together, so a read right after a write sees the new value. Pantrybox makes about 60 price changes a second and serves 22,000 product reads a second. Making every write pay a Redis round trip, and caching rows nobody reads, buys little. Write-through also does nothing for stampedes after expiry or eviction, and bulk imports that write straight to Postgres bypass it. It fits better when reads must see the write immediately and the write rate is modest, such as a shopper's own basket.

An everyday analogy

The same idea, outside software.

Picture the information desk at a large conference centre. Staff keep a printed sheet of room assignments so they do not phone the organisers for every question. The sheet is the cache and the organisers' office is the database.

When a session moves rooms, the office does not reprint and deliver a new sheet. It tells the desk to throw the old one away, and the next person who is asked phones the office and prints a fresh copy. If forty visitors ask while the sheet is missing, one staff member makes the call and the rest wait a moment, instead of forty people dialling the same number.

Each sheet also carries a slightly different expiry time, so the desk never throws every sheet away in the same minute.

Structure

The pieces and how they relate.

Pantrybox catalog read path with lease-protected cache-aside, delete-on-write and a CDC-driven second delete.Shopper app calls catalog-service (GET /products/:sku). catalog-service calls Redis cluster (GET, SET on miss). catalog-service calls Postgres primary (load on miss). Pricing console calls pricing-service (change price). pricing-service calls Postgres primary (UPDATE). pricing-service calls Redis cluster (DEL product key). Postgres primary sends to Change stream (row changes). Change stream sends asynchronously to cache-invalidator (product changed). cache-invalidator calls Redis cluster (delayed DEL).Shopper appproduct pages,basketcatalog-servicecache-aside reader,22k req/s peakLease per keySET lease:{key} NXPX 3000Redis clustersoft TTL 60s, hardTTL 300s, +/-10%Jittered expirykeys writtentogether expir…Postgres primarysource of truth,cache fills rea…Pricing consolemerchandising teampricing-servicecommit, then DEL keyChange streamWAL decoded to roweventscache-invalidatorsecond DEL ~1s aftercommitGET /products/:skuGET, SET on missload on misschange priceUPDATEDEL product keyrow changesproduct changeddelayed DEL
Pantrybox catalog read path with lease-protected cache-aside, delete-on-write and a CDC-driven second delete.

Participants

catalog-service (reader)
Owns the cache-aside logic. Reads Redis first and serves soft-expired values while one request refreshes. On a hard miss it takes a lease so only one request per key queries Postgres. Fills always read the primary.
Redis cluster (cache)
Holds serialized product entries with an embedded soft expiry and a jittered hard TTL, plus short-lived lease keys. It is disposable: losing it costs latency, not correctness.
Postgres primary (source of truth)
Owns every product row. The cache never holds a value that did not come from here, and every write commits here first.
pricing-service (writer)
Commits price and stock changes, then deletes the affected cache key. It never writes values into the cache, so a lagging or reordered write cannot pin an old price.
Change stream and cache-invalidator
Turns committed row changes into a second, delayed DEL. This catches the race where a reader loaded before the commit and wrote after the first delete, and it also covers writes from bulk imports that never pass through pricing-service.
Lease key
A per-key mutex with a 3 s expiry. Whoever holds it refreshes the entry. Everyone else serves stale data or waits up to 250 ms, which bounds database load to one query per key per refill.

Pseudocode

The solution to the scenario, language-neutral.

function get(key, load):
  entry = cache.GET(key)
  if entry exists:
    if now < entry.softExpiresAt:
      return entry.value                       // fresh hit
    if cache.SET('lease:' + key, NX, PX 3000):
      try: return refresh(key, load)           // one caller refreshes
      catch: return entry.value                // DB failing: serve stale
    return entry.value                         // everyone else serves stale

  repeat 5 times:                              // hard miss
    entry = cache.GET(key)
    if entry exists: return entry.value
    if cache.SET('lease:' + key, NX, PX 3000):
      return refresh(key, load)
    sleep 50 ms
  return load()                                // lease holder stuck or dead

function refresh(key, load):
  try:
    value = load()                             // read from the primary
    f = random(0.9, 1.1)
    cache.SET(key, {value, softExpiresAt: now + 60s * f}, PX 300s * f)
    return value
  finally:
    cache.DEL('lease:' + key)

function updatePrice(sku, price):
  db.UPDATE products SET price = price WHERE sku = sku   // commit first
  cache.DEL('product:' + sku)                  // delete, never set

on change event (products row committed):
  wait until commitTime + 1s
  cache.DEL('product:' + row.sku)             // second delete closes the race

The code

The same solution in TypeScript, Python and PHP.

type Entry<T> = { value: T; softExpiresAt: number };

interface KeyValueStore {
  get(key: string): Promise<string | null>;
  set(key: string, value: string, ttlMs: number): Promise<void>;
  setIfAbsent(key: string, value: string, ttlMs: number): Promise<boolean>;
  del(key: string): Promise<void>;
}

// Stand-in for Redis: GET, SET PX, SET NX PX, DEL.
class InMemoryStore implements KeyValueStore {
  private data = new Map<string, { value: string; expiresAt: number }>();

  private peek(key: string): string | null {
    const item = this.data.get(key);
    if (!item) return null;
    if (Date.now() >= item.expiresAt) {
      this.data.delete(key);
      return null;
    }
    return item.value;
  }

  async get(key: string): Promise<string | null> {
    return this.peek(key);
  }

  async set(key: string, value: string, ttlMs: number): Promise<void> {
    this.data.set(key, { value, expiresAt: Date.now() + ttlMs });
  }

  async setIfAbsent(key: string, value: string, ttlMs: number): Promise<boolean> {
    if (this.peek(key) !== null) return false;
    this.data.set(key, { value, expiresAt: Date.now() + ttlMs });
    return true;
  }

  async del(key: string): Promise<void> {
    this.data.delete(key);
  }
}

const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

class CacheAside<T> {
  constructor(
    private readonly store: KeyValueStore,
    private readonly softTtlMs = 60_000,
    private readonly hardTtlMs = 300_000,
    private readonly jitter = 0.1,
    private readonly leaseMs = 3_000,
  ) {}

  async get(key: string, load: () => Promise<T>): Promise<T> {
    const raw = await this.store.get(key);
    if (raw !== null) {
      const entry = JSON.parse(raw) as Entry<T>;
      if (Date.now() < entry.softExpiresAt) return entry.value;
      // Soft-expired: one caller refreshes, everyone else serves the old value.
      if (await this.store.setIfAbsent(`lease:${key}`, '1', this.leaseMs)) {
        try {
          return await this.refresh(key, load);
        } catch {
          return entry.value; // database is struggling: stale beats an error
        }
      }
      return entry.value;
    }
    // Hard miss: one caller loads, the rest poll briefly for its result.
    for (let attempt = 0; attempt < 5; attempt++) {
      const filled = await this.store.get(key);
      if (filled !== null) return (JSON.parse(filled) as Entry<T>).value;
      if (await this.store.setIfAbsent(`lease:${key}`, '1', this.leaseMs)) {
        return this.refresh(key, load);
      }
      await sleep(50);
    }
    return load(); // lease holder is slow or dead; do not fail the request
  }

  async invalidate(key: string): Promise<void> {
    await this.store.del(key); // on write: delete, never overwrite
  }

  private async refresh(key: string, load: () => Promise<T>): Promise<T> {
    try {
      const value = await load();
      const factor = 1 + (Math.random() * 2 - 1) * this.jitter;
      const entry: Entry<T> = { value, softExpiresAt: Date.now() + this.softTtlMs * factor };
      await this.store.set(key, JSON.stringify(entry), Math.round(this.hardTtlMs * factor));
      return value;
    } finally {
      // With real Redis, release with a compare-and-delete script on a unique token.
      await this.store.del(`lease:${key}`);
    }
  }
}

async function main(): Promise<void> {
  const cache = new CacheAside<{ sku: string; priceCents: number }>(new InMemoryStore(), 1_000, 5_000);
  let dbReads = 0;
  let priceCents = 349;
  const loadProduct = async () => {
    dbReads++;
    await sleep(100); // simulated Postgres query
    return { sku: 'sku-4471', priceCents };
  };

  const burst = await Promise.all(
    Array.from({ length: 500 }, () => cache.get('product:sku-4471', loadProduct)),
  );
  console.log(burst[0], 'db reads:', dbReads); // 1 read for 500 requests

  priceCents = 299; // writer commits to the database first...
  await cache.invalidate('product:sku-4471'); // ...then deletes the key
  console.log(await cache.get('product:sku-4471', loadProduct), 'db reads:', dbReads); // 299, 2
}

void main();

When to use it

Situations where it pays off.

  • Reads far outnumber writes on the same keys, and the product can tolerate a staleness window measured in seconds.

    Cache-aside pays its cost on misses and invalidations. At 22,000 reads against 60 writes per second, almost every request is a cheap hit, and the delete-on-write design keeps the staleness window short and explainable.

  • Only a fraction of the dataset is hot at any moment, for example 40,000 promo SKUs out of a 1.2 million product catalog.

    Lazy loading caches only what is requested, so memory tracks the working set. Write-through would cache every written row, including the long tail nobody reads.

  • Losing the cache must cost latency, not correctness.

    The database stays authoritative and the cache can be flushed, resized or failed over at any time. You still need load protection on the database when the cache is cold, but no data is lost.

  • The cached value is composed from several tables or services, such as a product with price, stock and promo badge.

    The reader builds the composed value once and caches it. With write-through, every writer to any of those sources would need to rebuild the full value, which spreads cache logic across services.

How to implement it

Steps to introduce it in existing code.

  1. Define keys and their format up front, for example product:{sku}:v3. Put a schema version in the key so that a format change moves to a new namespace instead of failing to deserialize old entries.

  2. Derive TTLs from a staleness budget, not a guess. If the product team accepts 60 s of stale catalog data, use 60 s as the soft expiry and set the hard Redis TTL several times longer (300 s) so hot keys can be served stale during a slow refresh.

  3. Multiply every TTL by a random factor between 0.9 and 1.1 at write time. Do this in the cache wrapper, not at call sites, so warm-up jobs and bulk loads cannot forget it.

  4. Protect misses and soft expiry with a per-key lease: SET lease:{key} NX PX 3000. The holder refreshes. Others serve stale or poll every 50 ms for up to 250 ms, then fall back to a direct load so a dead holder cannot block requests.

  5. On write, commit to the database first, then DEL the key. Never SET the new value from the writer. Make cache fills read from the primary so replica lag cannot reinsert an old row.

  6. Add a second delete driven by change data capture or a delayed job, roughly 1 s after commit. This closes the reader/writer race and also catches writes that bypass the service, such as SQL backfills.

  7. Cache misses for nonexistent keys too: store a not-found marker with a 30 s TTL so scrapers requesting random SKUs do not reach Postgres on every request.

  8. Emit hit rate, misses per second, lease waits, direct-load fallbacks and the age of served stale entries. Alert on misses per second, because that is what the database actually feels.

Pros and cons

What you gain and what you pay.

Pros

  • Database load scales with the miss rate, not the request rate, so read traffic can grow without growing Postgres.
  • Only requested data occupies memory; cold rows are never cached.
  • The cache is disposable: a Redis failover costs latency, never data.
  • Writers stay simple. A DEL after commit is the only cache code on the write path.
  • Soft expiry with a lease keeps hot keys served from cache even while they are being refreshed.

Cons

  • Every first read after a miss or delete pays the database round trip, so p99 includes cold reads.
  • Stale reads are possible by design. You must state the bound (here up to 60 s, usually about 1 s) and defend it.
  • Correct invalidation needs extra machinery: delete ordering, primary-only fills and a second delete via CDC.
  • Cache logic sits in the application. Every service that reads the data must use the same wrapper or it reintroduces stampedes.
  • A cold cache after a full flush can overload the database without additional load shedding.

Trade-offs

Decisions you'll have to make, each with its price.

  • Delete the key on write instead of setting the new value

    You gainWrite-order races cannot pin an old value. The next read always comes from Postgres, and the writer code is a single DEL.

    You payEvery price change causes one extra miss. A hot key that is written often (say 10 times a second) barely benefits from caching, and needs a short-lived local cache or a different design.

  • Cache-aside instead of write-through

    You gainOnly requested keys are cached, writes stay at database latency, and losing Redis never blocks writes.

    You payA read right after a write can be stale for up to the second delete (about 1 s), or 60 s in the worst case. Write-through would make same-path reads fresh immediately.

  • Soft TTL 60 s with hard TTL 300 s (stale-while-revalidate)

    You gainHot keys never miss. One request refreshes while thousands keep reading, and a slow database results in stale data instead of errors.

    You payUsers can see data up to 300 s old if refreshes keep failing. You need a metric for served-stale age and an alert when it exceeds the 60 s budget.

  • Lease wait of 50 ms polls up to 250 ms, then direct load

    You gainBounds the worst-case extra latency on a miss and avoids a deadlock if the lease holder dies.

    You payIf Postgres is slower than 250 ms, waiters fall through and load directly, partly recreating the herd. Pair it with a database concurrency cap per pod, for example 20 in-flight product queries.

  • Fill from the primary instead of a replica

    You gainReplica lag cannot reinsert an old row after a delete, which was the root cause of the stale price.

    You payAll misses, about 400 per second normally, land on the primary. That load disappears from the replicas and needs headroom on the primary during cold starts.

How it fails

What goes wrong in production and how to prevent it.

  • Synchronized expiry: thousands of keys written together expire in the same second, like the 09:00 promo launch.

    What to doApply a plus or minus 10 percent random factor to every TTL in the cache wrapper, and use soft expiry so expired hot keys are refreshed by one request while others read the old value. Warm-up jobs must go through the same wrapper, never raw SET.

  • Hot-key stampede after eviction or delete: 3,000 concurrent requests miss the same product.

    What to doPer-key lease with SET NX PX 3000 so one request loads and the rest poll for 250 ms. On a single-process runtime, also collapse identical in-flight loads in memory so only one request per pod even asks for the lease.

  • Stale set after invalidation: a reader loads the old row, the writer commits and deletes, then the reader writes the old value back.

    What to doFill only from the primary, and issue a second DEL from the change stream about 1 s after commit. For stricter cases, store the row version and use a Lua script that only SETs if the cached version is older.

  • DEL fails after the database commit because of a Redis timeout or a pod crash.

    What to doThe CDC invalidator retries from the change stream, so the delete is eventually applied without depending on the writer process. The 60 s soft TTL bounds staleness if the stream also lags.

  • Redis cluster outage turns every request into a miss: 22,000 per second against a database sized for hundreds.

    What to doPut a circuit breaker and a per-pod concurrency limit on the database load path, shed low-priority traffic such as search suggestions, and return degraded responses rather than queue requests until connections run out.

  • Cache penetration: bots request random nonexistent SKUs, and every request misses and queries Postgres.

    What to doCache not-found results as a marker with a 30 s TTL, and rate-limit per client. Validate SKU format before touching the cache at all.

In a system design interview

When to bring it up and how to explain it.

Bring it up whenever a design has a read-heavy path in front of a relational store: product pages, profiles, feeds, configuration. Interviewers usually ask how you keep the cache consistent and what happens when a hot key expires, so lead with invalidation and stampede protection, not just with putting Redis in front of it.

What you could say

For the product read path I'd use cache-aside in front of Postgres. The service checks Redis, and on a miss it loads the row from the primary and writes it back. On writes, the pricing service commits first and then deletes the key. It never sets the new value, so a write-order race can't pin an old price. A reader that loaded just before the commit could still write the old value back, so I'd add a second delete from a change-data-capture consumer about a second after commit.

For TTLs I'd start from the staleness budget. Say the business accepts 60 seconds, so that's the soft TTL, with a 300 second hard TTL in Redis, and I'd randomise both by about 10 percent so keys written together don't expire together. After the soft expiry, one request takes a lease with SET NX and refreshes while everyone else keeps serving the old value. On a hard miss, the others poll for up to 250 milliseconds before loading directly. That makes a refill one database query per key instead of thousands.

I'd pick this over write-through because reads outnumber writes by a few hundred to one and only a fraction of the catalog is hot. Write-through would make every write pay a cache round trip and cache rows nobody reads. I'd use write-through for something like a user's own basket, where they must see their write immediately.

Likely follow-ups

What if a single key is so hot that one Redis shard saturates?

Add a small in-process cache in each catalog pod with a 1 to 2 s TTL for the top few hundred keys, so most reads never leave the pod. Alternatively, replicate the hot key under a few suffixed names and read a random copy. Both widen the staleness window slightly, so the delete path must also clear or version the local copies.

How would you guarantee a shopper sees their own price change or basket update immediately?

For their own writes I'd route the next read to the primary, bypassing the cache, for a few seconds after the write. I'd track that with a timestamp in the session. Other users keep reading through the cache with the normal staleness bound. If that's needed broadly, write-through for that specific data is reasonable.

How do you warm the cache after a full flush without hurting the database?

Don't let warm-up jobs write raw keys with fixed TTLs. They should go through the same wrapper with jitter, and be throttled to a fixed rate, for example 2,000 keys per second, ordered by recent popularity. Meanwhile, the database concurrency cap and leases keep live traffic from piling on top of the warm-up.

Why not just make the TTL very short, like 5 seconds, and skip invalidation?

That multiplies refills across every hot key, raising steady database load, and it still serves stale data for up to 5 seconds after every write. Explicit deletes give fresher data with fewer misses. The TTL then becomes a safety net, not the main consistency mechanism.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Why delete the key on write instead of setting the new value?

Two writers, or a writer and a filling reader, can reach the cache in a different order than they reached the database. If they SET values, the loser of that race pins an old value until the TTL expires. A DEL is idempotent and order-insensitive: whatever happens, the next reader goes to the database. The cost is one extra miss after every write, which is cheap when writes are rare compared with reads.

Is cache-aside the same as read-through?

The behaviour is similar, but the responsibility sits in a different place. In cache-aside, application code checks the cache and loads from the database. In read-through, the cache library or service does the load through a configured loader, and the application only talks to the cache. Read-through centralises stampede protection, but it ties you to a cache product that supports loaders.

Does write-through remove stale reads entirely?

No. It removes the gap between a write and the next read through the same path, as long as the cache and database updates are ordered consistently. Writes that bypass the path, such as SQL backfills or another service writing the same table, still leave stale entries. A failed cache write after a successful database commit leaves one too. Most teams that use write-through still keep TTLs and an invalidation path.

How do I choose the TTL?

Start from how stale the data may be, not from the hit rate you want. Pantrybox accepts 60 s of catalog staleness, so the soft TTL is 60 s. The hard TTL only needs to be long enough to keep serving stale data while a refresh runs or the database is degraded, so a few multiples of the soft TTL works. Then check that misses per second at that TTL fit comfortably within the database's capacity.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide7 of 8 · DataRead Replicas: Scaling Reads Without Serving Stale WritesRead the next one