The Hidden Cost of `revalidateTag` at Scale: A Cache Invalidation Post-Mortem
We treated `revalidateTag` like a magic eraser. Then a product import triggered 40,000 simultaneous regenerations and took down our listing pages. Here's what we got wrong about Next.js tag-based invalidation and how we rebuilt it.
We treated revalidateTag like a magic eraser. Tag a fetch, call the function, done. Then a routine supplier import ran during business hours, touched 40,000 SKUs, and our product listing pages started serving 504s for about eleven minutes. This is the post-mortem, the mental model we were missing, and the invalidation patterns we now use in Next.js App Router projects.
What actually happened
The client runs a mid-sized B2B catalogue — roughly 180,000 SKUs, Next.js 15 App Router, deployed on a managed Node runtime behind a CDN. Product pages and category listings used fetch with next: { tags: ['product:'+id, 'category:'+slug] }. A nightly job normally updated a few hundred items. On the day in question, a supplier pushed a full catalogue refresh.
The server action looked innocent:
'use server'
import { revalidateTag } from 'next/cache'
import { db } from '@/lib/db'
export async function importProducts(rows: ProductRow[]) {
for (const row of rows) {
await db.product.upsert({ where: { id: row.id }, update: row, create: row })
revalidateTag(`product:${row.id}`)
revalidateTag(`category:${row.categorySlug}`)
}
}
Two things went wrong at once. First, revalidateTag doesn't regenerate pages — it marks cache entries as stale. The next request for each affected route triggers regeneration. When our scheduled warmer and real users hit those routes simultaneously, we fired tens of thousands of concurrent data-layer queries against the same Postgres instance. Second, every category tag touched the same handful of listing pages, so a single page was invalidated and re-fetched hundreds of times in a few seconds because each product in that category re-dirtied the tag.
The result was a stampede. Database CPU pinned, the connection pool saturated, server components started timing out, and the CDN served error responses that it then cached briefly. Classic.
The mental model we were missing
If you come from Pages Router ISR, revalidateTag feels like an upgrade. It isn't a direct equivalent. Here's the model that finally clicked for us:
- A
tagis a label on a data fetch, not on a page. - Calling
revalidateTagmarks every cached fetch carrying that tag as stale. - Stale entries are recomputed lazily, on the next request that needs them.
- Multiple pages can depend on the same tag, and a single page can depend on many tags. The fan-out is not obvious from the call site.
That last point is the killer. In our code, category:electronics was attached to the category page, to the homepage "featured categories" strip, and to a sidebar component rendered on every product detail page. Invalidating one tag invalidated three high-traffic routes. We hadn't drawn that graph anywhere.
Tags are cheap to add, expensive to reason about
The DX encourages liberal tagging. A junior dev who adds tags: ['user:'+id] to a header component has just coupled every page that renders the header to that user's mutation cadence. You will not notice this in dev. You will notice it the first time a power user clicks something twenty times.
Fix one: batch, then invalidate once
The simplest win was to stop calling revalidateTag inside the loop. We collected unique tags, deduped, and flushed at the end.
'use server'
import { revalidateTag } from 'next/cache'
export async function importProducts(rows: ProductRow[]) {
const tags = new Set<string>()
await db.$transaction(
rows.map((row) => db.product.upsert({
where: { id: row.id },
update: row,
create: row,
}))
)
for (const row of rows) {
tags.add(`product:${row.id}`)
tags.add(`category:${row.categorySlug}`)
}
for (const tag of tags) revalidateTag(tag)
}
This alone cut the invalidation storm because each tag was only marked stale once per import, not once per row. But the regeneration stampede was still there — the next thousand visitors to /c/electronics would each try to rebuild it.
Fix two: a request coalescing layer
Next's data cache deduplicates within a single render pass, but not across concurrent requests to different route instances. We added a small coalescing layer in front of the expensive queries so that only one database round-trip happens per key at a time.
const inflight = new Map<string, Promise<unknown>>()
export function coalesce<T>(key: string, fn: () => Promise<T>): Promise<T> {
const existing = inflight.get(key) as Promise<T> | undefined
if (existing) return existing
const promise = fn().finally(() => inflight.delete(key))
inflight.set(key, promise)
return promise
}
Used inside the data layer:
export async function getCategory(slug: string) {
return coalesce(`category:${slug}`, async () => {
const res = await fetch(`${API}/categories/${slug}`, {
next: { tags: [`category:${slug}`], revalidate: 3600 },
})
return res.json()
})
}
This is per-instance, not distributed, so it only helps within one Node process. On a serverless platform with many cold instances, you need the next fix too.
Why not just rely on fetch memoisation?
React's cache and Next's fetch memoisation scope to a single request. Two users hitting the same stale page at the same time each trigger their own fetch, each of which hits your origin. Request coalescing closes that gap for the duration a promise is pending.
Fix three: pre-warm instead of waiting for users
For the bulk import case, we stopped relying on lazy regeneration entirely. After the transaction committed, we kicked off a controlled warmer that fetched the affected pages with a small concurrency limit before invalidating.
import pLimit from 'p-limit'
async function warm(paths: string[]) {
const limit = pLimit(4)
await Promise.all(
paths.map((p) =>
limit(() => fetch(`${SITE}${p}`, { headers: { 'x-warm': '1' } }))
)
)
}
The sequence became: write to DB, revalidate tags, then warm the top N affected routes at a controlled rate. For the long tail we accept that the first visitor pays the regeneration cost — that's fine because the tail is, by definition, low traffic.
Fix four: narrow your tags
We audited every tags: [...] call. The rule we settled on:
- Use entity tags (
product:123) for detail pages and anything that renders exactly one entity. - Use collection tags (
category:electronics) only on pages that render the collection itself. - Never attach collection tags to layout-level fetches. If the header needs the user's name, tag it
user:123:profile, notuser:123.
The principle: a tag should answer the question "what pages genuinely must change when this tag fires?" If the honest answer is "most of them", the tag is too broad and you're using the cache as a global bus.
What we monitor now
You cannot fix what you cannot see. We added three signals:
- Invalidation rate per tag prefix — logged from a wrapper around
revalidateTag. Ifproduct:*spikes, we know an import is running. - Origin fetch rate per cache key — from the data layer. A healthy system shows this flat relative to invalidations.
- Regeneration latency distribution — time between a request arriving at a stale route and the response being served. We alert on p95.
These three together let us catch a stampede within a minute or two instead of eleven.
Where this leaves the App Router cache
The tag system is genuinely good. It expresses invalidation in the language of your data rather than your routes, which is where it belongs. What it doesn't do is protect you from your own fan-out. Treat revalidateTag as "schedule a stampede unless you've planned otherwise" and you'll build the right guardrails from day one.
If you want a second opinion on an App Router cache strategy before you scale, that's the kind of audit we do in our web engineering engagements — and we've written up related gotchas on the blog if you want more context.
Where we'd start
If you're inheriting a Next.js codebase today, grep for revalidateTag and next: { tags. For each result, write down the pages that fetch depends on. If any single tag touches more than a handful of high-traffic routes, that's your first refactor. Add a logging wrapper around revalidateTag before you change anything else — you want a baseline, not a guess.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
Middleware Is Not a Router: What We Learned Running Auth at the Edge
We treated Next.js middleware like a mini router for auth and A/B tests. It bit us on cold starts, cookie races, and session drift. Here's the pattern we settled on.
Why Our React Server Component Payloads Doubled After a 'Harmless' Refactor
A quiet refactor pushed our RSC payload from 180KB to 410KB on a single route. Here's how we found it, why it happened, and the serialization rules we now enforce in CI.
React 19's useOptimistic Is a Trap If You Don't Model Failure First
useOptimistic feels like free UX magic until a server action fails in ways you didn't plan for. Here's the mental model we wish we'd had before shipping it to production.
