LazyLayersv9.1.0
Learn caching

Cache invalidation for beginners

Cache invalidation explained: TTL expiry, delete on write, versioned keys, pattern and tag invalidation, and clearing copies on many servers, with TypeScript.

Cache invalidation is removing or replacing a cached copy because the original data changed. A cache cannot tell when its source changed, so your code has to delete the key after a write, let a TTL expire it, or both. The common recipe is: commit the database write, delete the key, and keep a TTL as the safety net.

Level: zero to one · You need: The cache-aside pattern

Rendering diagram...

Why is cache invalidation hard?

Phil Karlton, a Netscape engineer, is credited with the line: "There are only two hard things in Computer Science: cache invalidation and naming things." It is a joke, and it lasts because it is accurate.

A cache is a copy, and a copy never learns that the original changed. Three things must go right, and each one fails on its own:

  1. You must remember to invalidate, in every code path that writes the data.
  2. You must do it at the right moment. Too early and a slow reader puts the old value back. Too late and users see old data.
  3. You must reach every copy: Redis, and the memory of every server.

The rest of this lesson takes those in order.

What are the cache invalidation strategies?

StrategyHow it worksStalenessCost
TTL expiryThe copy expires on a timerUp to the TTLOne reload per TTL per key
Delete on writeDelete the key after the database commitNear zeroOne miss after each write
Versioned keysA version number is part of the keyNear zeroOld versions sit until their TTL
PatternDelete every key matching user:42:*Near zeroA scan of the keyspace
TagDelete every entry with a labelNear zeroConstant, no scan
Event busTell every server to drop its copyNetwork delayA message per delete

Most real systems layer two of these: delete on write for freshness, a TTL as the backstop.

TTL expiry: let it age out

The simplest strategy needs no code in the write path. Give every entry a time to live and accept that a change can be invisible for that long.

await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 60) // gone in 60 s

A 60 second TTL means a worst case of 60 seconds of stale data. Shorter TTLs are fresher but reload the same value more often, so staleness and database load trade against each other. A TTL also cannot say "this value is wrong now": a revoked permission stays cached until the timer fires. That is why TTL is the safety net and not the whole answer.

Delete on write

When your code changes the data, delete the cached key right after the database commit. The next read misses, loads the new row and caches it. This is the write-around strategy from caching strategies.

update-user.ts
import { Redis } from 'ioredis'
import { db, type User } from './db.ts'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

export async function updateUser(id: string, changes: Partial<User>): Promise<void> {
  await db.users.update(id, changes) // 1. commit first
  await redis.del(`user:${id}`) // 2. then drop the copy
}

Order matters. If you delete before the commit, a reader can load the old row in the gap and cache it again.

Why delete beats update

It is tempting to write the new value into the cache instead of deleting. Do not. Two writers can reach the database in order A then B, and reach the cache in order B then A, so the cache ends up holding A's value while the database holds B's. A delete has no such order problem: two deletes leave the same empty key. It also never caches a value for a row that nobody reads.

Versioned keys: change the name instead of deleting

Another way to invalidate is to make the old key unreachable. Keep a version number per entity, put it in the key, and bump it on every write.

versioned-keys.ts
import { Redis } from 'ioredis'
import { db, type User } from './db.ts'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

async function userKey(id: string): Promise<string> {
  const version = (await redis.get(`user:${id}:version`)) ?? '0'
  return `user:${id}:v${version}`
}

export async function getUser(id: string): Promise<User | null> {
  const key = await userKey(id)
  const cached = await redis.get(key)
  if (cached !== null) return JSON.parse(cached) as User

  const user = await db.users.find(id)
  if (user) await redis.set(key, JSON.stringify(user), 'EX', 300)
  return user
}

export async function updateUser(id: string, changes: Partial<User>): Promise<void> {
  await db.users.update(id, changes)
  await redis.incr(`user:${id}:version`) // every old key is now unreachable
}

This is cache versioning. It fixes the slow-reader race from the previous lesson, because a reader that loaded the old row stores it under the old version, which nobody reads any more. The price is that old versions stay in Redis until their TTL ends, and each read costs one extra lookup for the version.

How do you invalidate a key family by pattern?

A user's data often lives under several keys: user:42, user:42:orders, user:42:settings. Deleting the family means matching a pattern. In Redis, use SCAN, never KEYS, because KEYS is O(N) and blocks the single-threaded server while it runs.

delete-by-pattern.ts
import { Redis } from 'ioredis'

const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')

export async function deleteByPattern(pattern: string): Promise<number> {
  let deleted = 0
  for await (const keys of redis.scanStream({ match: pattern, count: 100 }) as AsyncIterable<string[]>) {
    if (keys.length > 0) deleted += await redis.unlink(...keys) // frees memory in the background
  }
  return deleted
}

await deleteByPattern('user:42:*')

SCAN can return a key twice and walks the whole keyspace, so keep the prefix narrow. The full story, including batching, is in delete Redis keys by pattern.

Cache tags: invalidate a group with no common prefix

Sometimes the keys that must go together share no prefix: every page that shows team 7, every product in a store. A tag is a label you attach when you store the value. You then invalidate the label, not the keys. This is tag-based cache invalidation.

By hand, that means keeping a set of keys per tag. A library can do it without any scan.

Invalidate with lazy-layers-cache

teams.ts
import { setupCache } from 'lazy-layers-cache'
import { db, type User } from './db.ts'

const cache = await setupCache<string, User>({
  namespace: 'users-api',
  redis: { required: true }, // reads REDIS_URL
  ttlMs: 300_000,
})

export function getUser(id: string, teamId: string): Promise<User | undefined> {
  return cache.getOrSet(`user:${id}`, () => db.users.find(id), { tags: [`team:${teamId}`] })
}

export async function updateUser(id: string, changes: Partial<User>): Promise<void> {
  await db.users.update(id, changes)
  await cache.invalidate(`user:${id}`) // one key
  await cache.invalidateByPattern(`user:${id}:*`) // a key family, only * is a wildcard
}

export async function renameTeam(teamId: string): Promise<void> {
  await db.teams.rename(teamId)
  await cache.invalidateTags([`team:${teamId}`]) // every entry tagged team:7
}

Pattern deletes on Redis use SCAN with MATCH, limited to the cache's namespace, and delete the matches in batches. In a recorded run, a 500-key pattern delete took 36.3 ms before the 9.0 batching and 1.9 ms after. invalidateTags gives the tag a new token and does not scan, so its cost does not grow with the number of keys. Both are explained in invalidation.

How do you invalidate a cache across many servers?

If each server keeps a copy in its own memory, redis.del removes only the Redis copy. Server B still holds the old value in its own Map and keeps serving it until its TTL ends. The fix is an event bus: the server that made the change publishes a delete, and every other server drops its own copy.

Rendering diagram...

invalidate, invalidateByPattern and invalidateTags in lazy-layers-cache publish these events for you. The default bus with setupCache is Redis Pub/Sub, and NATS, RabbitMQ, Redis Streams, Durable Objects and MongoDB change streams are also supported. Every delete advances a per-key generation, so a peer ignores an older set event that arrives after a delete.

A bus is best effort. It can lose or delay a message, which is why every entry keeps a TTL. See event buses for the delivery options.

How much stale data is OK?

Staleness is a product decision, not a bug to remove. Ask what the worst outcome is if a user sees a value that is a few seconds old.

DataRule of thumb
A product description or a blog postMinutes of staleness are fine
A profile the user just editedDelete on write, so they see their own change
A price or stock countSeconds, with delete on write
Permissions, balancesDo not cache, or invalidate on every write with a very short TTL

Cache consistency is the name for how closely cached copies match the source. Delete on write plus a TTL gives eventual consistency: a short window of stale reads, and then the copies agree. If you need a stricter guarantee, read the value from the database for that request instead of caching it. The freshness page covers the library settings.

Next lesson: LRU cache and eviction policies.

Further reading

Questions

What is cache invalidation?

Cache invalidation is removing or replacing a cached copy because the original data changed. The cache cannot know on its own that the source changed, so the application must delete the key after a write, or let a TTL expire it, or both.

Why is cache invalidation hard?

The cache is only a copy, and nothing tells it when the original changes. You must delete at the right moment, reach every server holding a copy, and survive races and lost messages. Phil Karlton's joke names it one of the two hard things in computer science.

What are the cache invalidation strategies?

The main ones are TTL expiry, delete on write (write-around), versioned keys, pattern invalidation for a key family, tag-based invalidation for a group, and an event bus that tells every server to drop its copy. Most systems combine delete on write with a TTL.

Should I update or delete the cache on a write?

Delete it. Two concurrent writes can update the database in one order and the cache in the other, leaving a wrong value until the TTL. Two deletes always leave the cache empty, and the next read loads whatever the database holds.

What is tag-based cache invalidation?

Tag-based invalidation attaches labels such as team:7 to cached entries and clears every entry with a label in one call. It suits groups whose keys share no common prefix. In lazy-layers-cache, invalidateTags gives the tag a new token instead of scanning keys.

How do you invalidate a cache across multiple servers?

Delete the shared Redis key, then publish a delete event on a bus such as Redis Pub/Sub. Each server listens and drops its own in-memory copy. Keep a TTL, because a bus can lose a message, and the TTL bounds how long a missed copy can live.

On this page