A user updates their profile, refreshes the page, and still sees the old value. The team checks the database: the data is correct. The bug isn't in the write, it's in the Redis cache that kept serving the old value after the update. This is the most common problem with caching: not whether to use one, but exactly when to clear it, and that's precisely the part most implementations get wrong.

The three basic strategies and when to pick each

Cache-aside (lazy loading)

The most common pattern: the application reads the cache, and on a miss, reads the database and fills the cache.

async function getProduct(productId) {
  const cacheKey = `product:${productId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const product = await db.query('SELECT * FROM products WHERE id = $1', [productId]);
  await redis.set(cacheKey, JSON.stringify(product), 'EX', 300);
  return product;
}

Simple and resilient (a Redis outage degrades performance but doesn't break reads, since the code falls back to the database), but the first request after an expiration always pays the full database latency. On a high-traffic cache, simultaneous expiration of heavily requested keys (say, every key set at the same hour with the same TTL) triggers a stampede of identical requests hitting the database at the same instant: the thundering herd problem.

Write-through

The write updates the cache and the database in the same operation, before the write is considered complete.

async function updateProduct(productId, data) {
  const product = await db.query(
    'UPDATE products SET name = $1, price = $2 WHERE id = $3 RETURNING *',
    [data.name, data.price, productId]
  );
  await redis.set(`product:${productId}`, JSON.stringify(product), 'EX', 300);
  return product;
}

The cache is always consistent with the database immediately after a write, eliminating the whole class of bug where a user sees stale data right after their own action. The cost: every write gets slower (two operations instead of one) and the write path has to know the exact shape of what's cached, which couples business logic to the cache more tightly than cache-aside does.

Write-behind (write-back)

The write goes to the cache first, and synchronization to the database happens asynchronously. This is rarely justified for critical business data (the risk of loss if a failure hits before synchronization is real), but it's a good fit for very high-throughput counters (page views, likes) where an occasional loss is an acceptable trade for much higher write throughput.

The real problem: invalidating at the right moment, not just expiring

A short TTL (30 seconds, a minute) hides a lot of invalidation bugs by limiting the window during which stale data can be served. That's a band-aid, not a fix: it turns a correctness bug into an occasional latency bug, and it does nothing to protect against a user refreshing the page one second after their own edit.

Direct invalidation on write

The minimal version deletes the affected key right after the database write:

async function updateProduct(productId, data) {
  const product = await db.query(
    'UPDATE products SET name = $1, price = $2 WHERE id = $3 RETURNING *',
    [data.name, data.price, productId]
  );
  await redis.del(`product:${productId}`);
  return product;
}

This works fine for one isolated key, but breaks down the moment a piece of data is cached under several different keys: the product detail cached under product:42, but also inside a list cached under category:5:products, and inside a search result cached under search:query_hash. Forgetting one of these keys is the most common caching trap in production: every new place where data gets denormalized into the cache is a new place where invalidation can be forgotten.

Tag-based invalidation

To avoid manually tracking every derived key, one strategy ties each cache entry to one or more tags, stored in a Redis SET, and invalidates by tag instead of by individual key:

async function cacheWithTags(key, value, tags, ttl) {
  await redis.set(key, JSON.stringify(value), 'EX', ttl);
  for (const tag of tags) {
    await redis.sadd(`tag:${tag}`, key);
    await redis.expire(`tag:${tag}`, ttl + 60);
  }
}

async function invalidateTag(tag) {
  const keys = await redis.smembers(`tag:${tag}`);
  if (keys.length > 0) {
    await redis.del(...keys, `tag:${tag}`);
  }
}

// when writing a product
await cacheWithTags(`product:${id}`, product, [`product:${id}`, `category:${product.categoryId}`], 300);

// when category 5 is updated
await invalidateTag('category:5');

This centralizes invalidation logic around the data model instead of around each endpoint, which cuts the risk of forgetting a derived key, at the cost of a slightly more complex Redis structure to maintain and a SMEMBERS call that can get expensive if a tag ends up tracking thousands of keys.

The lying cache: a race between read and write

A subtler case than a forgotten invalidation: the race condition between a cache-aside read and a concurrent write. If thread A reads the database (a stale value, before the update), and between that read and its SET into the cache, thread B updates the database and invalidates the cache, thread A's SET overwrites that invalidation with the stale value it had read before the update.

T1: A reads the database -> value = "old price"
T2: B updates the database -> value = "new price"
T3: B invalidates the cache (DEL)
T4: A writes to the cache -> "old price" (stale, but just written after the DEL)

The cache then durably holds the stale value until the TTL eventually expires it. This is what's called the lying cache: it doesn't return an error, it returns a plausible but wrong value, which makes the bug particularly hard to catch in testing. The usual protection is to tag each cached entry with a version or timestamp, and refuse to write a value into the cache that's older than what's already there:

async function setIfNewer(key, value, version, ttl) {
  const script = `
    local current = redis.call('GET', KEYS[1])
    if current then
      local decoded = cjson.decode(current)
      if decoded.version >= tonumber(ARGV[2]) then
        return 0
      end
    end
    redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[3])
    return 1
  `;
  return redis.eval(script, 1, key, JSON.stringify({ value, version }), version, ttl);
}

Running this as a Lua script guarantees atomicity between the check and the write on the Redis side, something a separate GET followed by SET in JavaScript can never guarantee under concurrent load.

When the easy fix isn't enough

For a system with multiple application instances sharing a cache, invalidating a key locally is never enough: invalidation has to go through Redis itself, never through a cache held in an instance's local memory, or instances will disagree with each other. For very fine-grained invalidation at large scale (millions of keys derived from a single entity), homemade Redis tags start showing their limits, and a dedicated solution such as event-driven cache invalidation (CDC off the database, published to a message bus, consumed by cache instances) becomes more robust than a SMEMBERS set that keeps growing without bound.

Takeaway

A short TTL hides invalidation bugs, it doesn't fix them: the real question is exactly which derived keys to invalidate on every write, not just the obvious one. Tags centralize that logic but carry a maintenance cost; either way, a race between a concurrent read and write can leave a stale value sitting in the cache long after the invalidation ran, and only an atomic version check (a Lua script) genuinely protects against that case.