The Hidden Cost of `revalidateTag` at Scale: Why Our Cache Invalidations Took 40 Seconds
`revalidateTag` looks like a free lunch until you ship it to a site with 80,000 cached entries. Here's what we learned about Next.js tag invalidation when it stopped being instant.
We shipped a content-heavy marketplace on Next.js 15 last year. For the first three months, revalidateTag('product') felt like magic — call it from a server action, cached pages update, move on. Then a bulk import ran, the tag count crossed some invisible threshold, and a single tag invalidation started taking 40+ seconds. Here's what was actually happening, and how we fixed it without ripping out the cache layer.
What revalidateTag actually does
Most teams treat revalidateTag as a pub/sub primitive: emit a tag, subscribers refresh. That's roughly the mental model, but the implementation is more mechanical than that. Next.js maintains a tag manifest — a mapping from tag names to the cache entries that reference them. When you call revalidateTag, the framework doesn't actively push anything. It writes an invalidation timestamp for that tag. On the next request that touches a cached entry, the runtime compares the entry's creation time against the latest invalidation timestamp for every tag it carries.
That last part is where it gets expensive.
The manifest grows with your data, not your code
In a demo app with ten products, you have maybe twenty tags. In a real catalogue, every fetch with { next: { tags: [product:${id}] } } creates a tag per product. We had roughly 80,000 products, each page cached per locale (four), with sub-fetches for reviews and inventory. The tag manifest had somewhere north of half a million entries.
The manifest itself isn't the bottleneck. The problem is what happens when you invalidate a broad tag like product that's attached to a huge number of cache entries. On the next read, the runtime walks the set of entries carrying that tag to mark them stale. At our scale, that walk — combined with the filesystem writes on the standalone deployment — was dominating the response time of whatever unlucky request triggered the revalidation sweep.
How we noticed
It wasn't obvious from the outside. The server action that called revalidateTag returned fast; the invalidation itself is non-blocking. The slowness showed up on the next page render for an unrelated user, who'd eat a 40-second TTFB because their request happened to be the one that triggered the stale-entry sweep.
Our APM showed it clearly once we knew where to look:
// What we had in the server action
'use server'
export async function updateProductPrice(id: string, price: number) {
await db.product.update({ where: { id }, data: { price } })
revalidateTag('product') // <- the culprit
revalidateTag(`product:${id}`)
}
That revalidateTag('product') was there because we wanted the category listing pages to refresh too. It was a lazy shortcut, and it cost us.
Finding the hot tag
We added a wrapper to log tag fan-out:
import { revalidateTag as nextRevalidateTag } from 'next/cache'
export function revalidateTag(tag: string, context?: string) {
const start = performance.now()
nextRevalidateTag(tag)
logger.info({
tag,
context,
callSite: new Error().stack?.split('\n')[2],
durationMs: performance.now() - start,
}, 'cache.revalidate')
}
The wrapper call itself was fast — again, the cost is deferred. But correlating these logs with subsequent slow requests (same node, within a few seconds) made the pattern obvious. Every slow render was preceded by a broad tag invalidation.
Four patterns that fixed it
We didn't move off the Next.js cache. We just stopped treating tags like free labels.
1. Narrow tags over broad tags
The single biggest win was replacing product with specific tags per surface:
// Before
fetch(url, { next: { tags: ['product'] } })
// After
fetch(productUrl, {
next: { tags: [`product:${id}`, `category:${categoryId}`] }
})
fetch(listingUrl, {
next: { tags: [`listing:${categoryId}`] }
})
Now the server action invalidates only what actually changed:
export async function updateProductPrice(id: string, price: number) {
const product = await db.product.update({
where: { id },
data: { price },
select: { id: true, categoryId: true },
})
revalidateTag(`product:${product.id}`)
revalidateTag(`listing:${product.categoryId}`)
}
In our experience this dropped the worst-case invalidation time from tens of seconds to under 200ms on the next request.
2. Batch invalidations behind a queue
Bulk imports were still a problem. A 5,000-product import would call revalidateTag 10,000+ times inside a single transaction. Even narrow tags add up.
We pushed invalidations through a lightweight queue and coalesced them:
const pendingTags = new Set<string>()
let flushTimer: NodeJS.Timeout | null = null
export function queueRevalidate(tag: string) {
pendingTags.add(tag)
if (flushTimer) return
flushTimer = setTimeout(() => {
const tags = Array.from(pendingTags)
pendingTags.clear()
flushTimer = null
// Collapse category tags if we have more than N products in one category
const collapsed = collapseTags(tags)
for (const tag of collapsed) nextRevalidateTag(tag)
}, 50)
}
The collapseTags step is the clever bit: if we see invalidations for 500+ products in the same category, we promote them to a single category:${id} tag invalidation. Below that threshold, we stay narrow. The crossover point depends on your fan-out — benchmark your own.
3. Separate on-demand revalidation from the request path
For truly broad invalidations (a CMS schema change, a global pricing rule), we moved the work off the user request entirely. A tiny internal route handles it:
// app/api/internal/revalidate/route.ts
import { revalidateTag } from 'next/cache'
import { after } from 'next/server'
export async function POST(req: Request) {
const { tags, secret } = await req.json()
if (secret !== process.env.REVALIDATE_SECRET) {
return new Response('forbidden', { status: 403 })
}
// Respond immediately; do the work after the response
after(() => {
for (const tag of tags) revalidateTag(tag)
})
return Response.json({ queued: tags.length })
}
The after() API means the response ships before the invalidation sweep. The next user request still triggers the stale check, but at least the admin action that caused it doesn't hang.
4. Prefer revalidatePath for truly page-scoped updates
For pages that have exactly one source of truth — a user's profile, a settings page, a dashboard — revalidatePath is cheaper because it bypasses the tag lookup entirely. We'd been using tags everywhere out of habit. Mixing the two based on what you actually need reduced manifest pressure.
// When only one path is affected, skip the tag indirection
revalidatePath(`/u/${userId}`)
What we'd avoid next time
A few things we'd flag early on any new App Router build:
- Don't attach the same tag to thousands of entries unless you genuinely want to invalidate them together. The symmetry is deceptive.
- Avoid tagging per-request data. We saw teams tag fetches with the user ID, producing a tag per user. The manifest balloons and you gain nothing because that data isn't shared.
- Watch out for third-party SDKs that wrap
fetch. Some auth and analytics SDKs pass throughnext.tagsoptions in ways you didn't intend. Audit yourfetchcall sites. - Measure the request after an invalidation, not the invalidation itself. The cost is deferred by design.
Where we'd start
If you're already in production and suspect tag sprawl, do this before touching code:
- Wrap
revalidateTagand log every call for a week with the tag name and the calling file. - Count unique tags in your manifest (or infer from logs) and sort by fan-out. Anything attached to more than a few hundred entries is a candidate for narrowing.
- Pick the top three noisy tags and refactor only those first. You'll likely recover most of the headroom without a big rewrite.
The Next.js cache is one of the most powerful features in the App Router, but it rewards teams who treat tags like a schema — designed, documented, and reviewed — rather than free-form labels. If you'd like a second pair of eyes on an App Router architecture review, our web engineering team does these regularly, and more war stories from similar builds live on the blog.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
Why Our Design System's Tokens Broke Dark Mode in Server Components
We shipped a design system with CSS variables, theme toggles, and server components. Then half our pages flashed white on reload and the other half rendered the wrong theme entirely. Here's what we learned.
Server Actions and the N+1 Problem Nobody Talks About
Server Actions feel like a free lunch until you profile a page that fires twelve of them on mount. Here's how we found a 3-second TTI regression hiding behind what looked like clean React code.
The Edge Runtime Cold Start Myth: Why We Moved Three Routes Back to Node
Edge runtime promised faster cold starts and lower latency. For three of our routes, it delivered the opposite. Here's what we measured, why it happened, and the rules we now use to decide.
