StoicBuilder

HandbookXIII the AqueductCache invalidation

XIIIthe Aqueduct, Scale it

Cache invalidation

1 min readUpdated 28 November

In plain words

Cache invalidation is how you make sure a cached copy is replaced when the real data changes, by expiring it, deleting it on write or changing its key, so users don't see yesterday's price.

Where you see it

Harbor caches plan prices in Redis for an hour to spare the database. Marketing drops Pro from $20 to $16, and for the next hour some visitors see $20 on the pricing page while checkout charges $16.

services/billing/plans.tsserver
const hit = await redis.get(`plan:${id}`);if (hit) return JSON.parse(hit);const plan = await db.plan.findUnique({ where: { id } });await redis.set(`plan:${id}`, JSON.stringify(plan), "EX", 3600);return plan; // on update: write the database first, then delete the keyawait db.plan.update({ where: { id }, data: { price } });await redis.del(`plan:${id}`);
Read through the cache, and delete the key after every write. The one-hour expiry is a safety net, not the plan.

What goes wrong

  1. Writing the new value into the cache instead of deleting it

    Two updates racing can leave the older value in the cache after the newer one reached the database. Deleting the key on write lets the next read fetch the truth.

  2. A stampede when a busy key expires

    When the cached pricing data expires, hundreds of requests miss at the same moment and all query the database. Let one request refill the key while the others serve the old value, and add random jitter to expiry times.

  3. Forgetting the other copies

    Deleting the Redis key doesn't touch the CDN, the framework's page cache or the browser, which each keep their own copy for their own time. List every layer that holds the data and what clears each one.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
List every cache this data passes through, such as Redis, the CDN, the framework and the browser, with its key, expiry and what clears it. Make every write path delete or version the affected keys after the database commit, and add a test that changes a price and checks the next read shows it.

Quick check

Sign in to earn +10 XP for it

Harbor deletes a plan's Redis key after every price change, yet the pricing page still shows the old price for 10 minutes afterwards. Where do you look?

Got a prompt that touches cache invalidation?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.