Cache invalidation that actually works

There is a famous joke that the hardest problems in computer science are cache invalidation and naming things. This is the cache invalidation half. When data changes, any cached copy of it is now lying. Your job is to delete the cached copy before the next read comes in.

The rule is simple: every write has to invalidate every cache that could hold the data it touched. Creating a book invalidates books:all. Deleting a book invalidates books:all AND books:{id}. Updating a book invalidates both. You can be clever about this or you can glob it all away with books:*. Start with the glob.

after/services/book.service.ts
typescript
import { cacheDelete } from './cache.service';

export async function createBook(input: NewBook): Promise<Book> {
  const result = await db.insert(books).values(input).returning();
  await cacheDelete('books:*');
  return result[0];
}

export async function deleteBook(id: number): Promise<boolean> {
  const result = await db
    .delete(books)
    .where(eq(books.id, id))
    .returning({ deletedId: books.id });
  await cacheDelete('books:*');
  return result.length > 0;
}

Invalidate the cache every time you mutate.

Because delete is simpler and safer. Updating the cache means you have to serialize exactly what the next read would return, which couples your write logic to your cache shape. Deleting forces the next read to miss, go to the database, and repopulate the cache with fresh data. Slower on that one read, cleaner everywhere else. Start with delete, and only reach for cache-fill patterns when you have a measured reason to.

Even with invalidation, there is always a tiny window where a stale read can sneak in. Two requests arrive at the same time. One is a read that misses and starts loading from the database. One is a write that invalidates the cache and returns. The read finishes after the invalidation and stores stale data. This is the thundering-herd problem. Most apps solve it by using a short TTL as the backstop. You will feel this the first time you build something at scale.

Quiz: Quiz

Loading practice…