Repository navigation
Description
Hello friends, i really like what you are doing here, taking the handler into your own hands, after years of us being failed by previous projects, and vercel themselves. I truly appreciate it.
I wanted to post here, hoping to help future readers, even tho i doubt that this is something that YOU want in the codebase, I assume you want to keep it simplistic and focused. But it is a very common problem, and most folks don't even realize they have it, nor what the best practices are, so I hope this helps :)
This adapter, as well as all others out there do not have these important improvements, they focus on reliably "adapting" between Next and Redis, and these decisions below fall more into a "business logic" side of things, even tho they are fairly common problems as you start scaling:
- L1 LRU Keeps the last 15 seconds of sets and gets in memory, which turns tens of miliseconds to nanoseconds. Broadcast revalidation for multi-server setups.
- Deduplication Concurrent reads of one key share one Redis read, so it protects your Redis from sudden spikes.
- Miss latch coalescence If multiple users start MISS-ing at the same time, the first user triggers the underlying handler/request, while others simply wait on the same promise. Protects the underlying systems from cache stampede upon invalidation.
Luckily, its not that hard at all to wrap your cache handler and do it yourself. Its really not rocket science, this type of thing used to be hand-rolled as a commonplace back in the day, nor does it need to be perfect.
import { LRUCache } from 'lru-cache';
const MB = 1024 * 1024;
/**
* Wraps a Next cache handler class with a short in-process copy of fresh entries and shared in-flight work.
*
* Concurrent reads of one key share one read. Concurrent fetch misses wait for the first caller's `set()`, so one
* render asks the origin and the rest reuse its answer; after `refillWaitMs` they give up and fetch themselves.
* Entries age out after `ttlMs`. `revalidateTag` drops matching entries here and, through `broadcast`, on every
* other server, so no server rebuilds a page from data that was invalidated elsewhere.
* @param {new (...args: unknown[]) => object} Handler the cache handler class to wrap
* @param {{ ttlMs?: number, maxBytes?: number, maxEntryBytes?: number, refillWaitMs?: number, broadcast?: { publish: (tags: string[]) => unknown, subscribe: (onTags: (tags: string[]) => void) => unknown } }} [options] limits, and how to reach the other servers
* @example const Handler = withMicroCache(RedisCacheHandler, { broadcast }); // new Handler().get('/velliv/da/om-os')
*/
export function withMicroCache(Handler, { ttlMs = 10_000, maxBytes = 512 * MB, maxEntryBytes = 20 * MB, refillWaitMs = 5_000, broadcast } = {}) {
const entries = new LRUCache({ ttl: ttlMs, maxSize: maxBytes, maxEntrySize: maxEntryBytes, sizeCalculation: estimateBytes });
const reads = new Map();
const refills = new Map();
function remember(key, entry) {
if (isFresh(entry)) {
entries.set(key, entry);
}
}
function forget(tags) {
for (const [key, entry] of entries.entries()) {
if (entry.tags?.some((tag) => tags.includes(tag))) {
entries.delete(key);
}
}
}
function openRefill(key) {
let release;
const promise = new Promise((resolve) => {
release = resolve;
});
const timer = setTimeout(() => closeRefill(key), refillWaitMs);
refills.set(key, { promise, release, timer });
}
function closeRefill(key) {
const refill = refills.get(key);
if (!refill) {
return;
}
clearTimeout(refill.timer);
refills.delete(key);
refill.release();
}
broadcast?.subscribe(forget);
return class MicroCachedHandler extends Handler {
async get(key, ctx) {
const cached = entries.get(key);
if (cached) {
return cached;
}
const pending = reads.get(key);
if (pending) {
return (await pending) ?? this.afterRefill(key, ctx);
}
if (refills.has(key)) {
return this.afterRefill(key, ctx);
}
return this.share(key, ctx, { mayOpenRefill: true });
}
async set(key, data, ctx) {
try {
await super.set(key, data, ctx);
remember(key, await super.get(key, ctx));
} finally {
closeRefill(key);
}
}
async revalidateTag(tags, durations) {
const list = [tags].flat();
try {
await super.revalidateTag(tags, durations);
} finally {
forget(list);
await broadcast?.publish(list);
}
}
/**
* Waits for the first caller's `set()` on a missing fetch, then returns what it stored.
* @example await handler.afterRefill('menu', { kind: 'FETCH' }); // the entry the first render stored, or null
*/
async afterRefill(key, ctx) {
const refill = refills.get(key);
if (!refill) {
return null;
}
await refill.promise;
return entries.get(key) ?? reads.get(key) ?? this.share(key, ctx, { mayOpenRefill: false });
}
/**
* Starts one read of a key that every concurrent caller shares, keeping fresh entries and opening a refill on a fetch miss.
* @example await handler.share('menu', { kind: 'FETCH' }, { mayOpenRefill: true }); // null, callers now wait
*/
share(key, ctx, { mayOpenRefill }) {
const read = (async () => {
try {
const entry = await super.get(key, ctx);
remember(key, entry);
if (!entry && mayOpenRefill && ctx?.kind === 'FETCH') {
openRefill(key);
}
return entry;
} finally {
reads.delete(key);
}
})();
reads.set(key, read);
return read;
}
};
}
/**
* Whether an entry is still inside its revalidate window, so it is safe to serve again without asking Redis.
*
* A stale entry comes back backdated past its window and is never kept, or every request would start another rebuild.
* @example isFresh({ lastModified: Date.now(), revalidateSec: 60 }); // true
*/
function isFresh(entry) {
return Boolean(entry) && (Date.now() - entry.lastModified) / 1000 <= entry.revalidateSec;
}
/**
* Rough size of a cache entry in bytes, counting the page HTML, the RSC payload and fetch bodies.
* @example estimateBytes({ value: { kind: 'FETCH', data: { body: 'abc' } } }); // 1027
*/
function estimateBytes({ value }) {
if (value?.kind === 'FETCH') {
return 1024 + (value.data?.body?.length ?? 0);
}
const segments = value?.segmentData
? [...value.segmentData.values()].reduce((sum, segment) => sum + segment.byteLength, 0)
: 0;
return 1024 + (value?.html?.length ?? 0) + (value?.rscData?.byteLength ?? 0) + segments;
}
Activity
leejpsd commentedon Nov 23, 2026
Thanks for writing this up, Marko. You're right that I'd keep it out of the core: the promise here is that Redis stays the source of truth, and an L1 trades some of that for latency, which each app should decide for itself. But it's a very good map of problems people usually find only after traffic shows them.
Your wrapper already fits this handler:
isFresh()readsrevalidateSecandforget()readstags, andget()here returns both.createIncrementalCacheHandler()returns a class, so it wraps directly:I ran it that way against a local Redis to be sure: 100 reads after a
set()made no Redis calls, and 20 concurrentfetchmisses reached a simulated origin once instead of 20 times.For anyone landing here later, here's what Next.js already collapses inside one process, which shows where the wrapper adds the most:
'use cache': since 16.3 (Improve deduping of concurrent'use cache'invocations vercel/next.js#91830), concurrent calls with the same key share one handlerget()and, on a miss, one fill, across requests. (The wrapper is for the singularcacheHandler, so this path is outside it anyway.)fetch: Next locks a fetch cache key inside the incremental cache, which is created per request. Dynamic pages, or different pages, that hit the same cached fetch at the same moment each miss and each go to the origin. Your refill latch closes exactly that gap.broadcast, an invalidation on another server reaches the L1 only afterttlMs.Two things on my side:
singleFlightsection oversells itself. It says followers skip the refresh, but Next decides to refresh afterget()returns, so every instance that sees a stale entry still refreshes it. The lock only records which instance got there first. I'll fix the wording.Are you running it on top of this handler already? If so, I'd be curious what share of reads ends up served from the L1.
docs: correct the singleFlight description and link #34 (#35)
markomitranic commentedon Nov 23, 2026
Thank you for the response, i appreciate it, and the tests you ran. It is reassuring.
I have performed some of my own tests to compare the setups, and gain acceptance in the team, for adopting your library, as most saw it as "too early".
I was actually surprised with the results - unless Redis is slow, the gains are minimal. I will still use it in my setup due to bursts, but the L1 itself is the weakest link of the three :D
@fortedigital/nextjs-cache-handler@leejpsd/nextjs-cache-handlerWe can't tell yet about the L1 hit rate with the current setup, but I'll follow up soon with it, it will go into production next week :)
I have had multiple clients with different needs, and in the two cases where I ran L1 in production (1. Vercel, 2. Azure) both madea big difference, but for different reasons:
leejpsd commentedon Nov 24, 2026
Thanks for running these, and for sharing the numbers, including where this handler comes out behind.
The Redis command column stood out: six to seven times fortedigital's for the same steady traffic. That's on me. The ISR handler reads each tag's state with its own GET (auto-pipelined, so one round trip, but one command per tag), and a page carries an implicit
_N_T_tag for every layout segment on top of its own tags. I did it that way because tag keys aren't namespaced, so a multi-key MGET fails with CROSSSLOT on Redis Cluster. On a single node that's no reason to pay per tag. I'll switch it to one MGET outside Cluster, falling back to per-key GETs if the client reports CROSSSLOT, which brings a read down to two commands. That matters most with per-command pricing like Upstash, which was your Vercel case.Good luck with the rollout next week. I'd be glad to see the L1 hit rate when you have it, and if anything looks off in production, open an issue and I'll take a look.
fix(incremental): read tag states with one MGET; per-key only on Clus…
fix(incremental): read tag states with one MGET; per-key only where M…
leejpsd commentedon Nov 24, 2026
1.1.1 is out with the MGET change (#36).
In a small Next.js 16.4 app (400 ISR pages, three layout levels, nine tags per page), a warm page read went from 10 Redis commands to 2. Round trips are the same as before, so latency shouldn't move; the command count is what changes.
One thing I found while testing that may matter to you: if the Redis user's ACL allows GET but not MGET, the handler now notices on the first read, logs one warning, and goes back to per-key reads. Redis Cluster keeps reading per key as before.
markomitranic commentedon Nov 24, 2026
@leejpsd I reran the tests, as they were laying around. Thanks for the fix, as predicted, the median time did not move at all, but the request amount is significantly different. I'm sure Redis has some internal batching mechanisms that take care of it, as most databases do, but sounds healthier, if nothing else, with the new library version :)
Anyway, lets keep the issue open a tiny bit longer, until i get with real traffic results, and then we can close it down and leave it as archived - i opened it primarily for future readers (and their AIs) who encounter these issues, in mind, i fully realise why this is not in the lib, and I agree with that.
markomitranic commentedon Nov 24, 2026
So, since we concluded that L1 is not worth the effort, if your Redis is colocated and fast (read, not Upstash) I ended up removing it from the wrapper, and only deploying the coalescence wrapper. It is smaller and more elegant, and it has a sole purpose of preventing stampede :)
What's left is ~80 lines that does two things:
leejpsd commentedon Nov 25, 2026
Thanks for rerunning it. On the median: the old per-tag GETs already went out together in one write (node-redis pipelines commands issued in the same tick, and ioredis does with
enableAutoPipelining), so it was one round trip either way. Redis still ran each GET as its own command, and that's the part MGET saves.Happy to keep it open until you have the production numbers.
Two things I noticed reading the coalescing wrapper, for anyone who copies it:
set()to reach Redis, then reads the entry and its tag states again. That's three round trips a render fetching on its own wouldn't pay: noise at 3 ms, about 120 ms at 40 ms. It may be what the 40 ms spike row (565 → 706 ms) and the slow-backend p99 (311 → 433 ms) are showing. Handing waiters the value passed toset(), before the Redis write, would remove it.set()for a 200. After a 404, a 5xx or a failed fetch, the render that started it usually doesn't ask for that key again, so the refill stays open and every concurrent request for the key waits the full 5 s before fetching on its own. A product page that has gone away, or an origin having a bad minute, would turn quick errors into 5 s waits. Might be worth a shorter timeout before the rollout.royvou commentedon Nov 25, 2026
Love that change of get to mget!
We have been trying to optimize our performance, and the otel logs did indicate a lot of gets in a single request and to simplfy the opentelemetry logs we did a small local patch to try this out. Didn't get a chance to create a change request here.
Should move to our (pre)production soon, but on a test environment that (plus the on demand revalidation) does seem to improve the performance (and API calls to redis).
Pages on the website (which have like 10-20 tags per page) now load in 200ms (still over a few days) instead from 300-400ms going to 1000ms (after a few days).
Will share more information (in that other ticker) once its on a production like environment.
leejpsd commentedon Nov 25, 2026
Thanks, glad it matches what your traces were showing. 1.1.1 has it, so the local patch can go. After upgrading, your traces should show one MGET for a page's tags instead of a GET per tag. If they still show a GET per tag, the handler is on the per-key path, which it uses with
hashTag: trueor on Redis Cluster.On the numbers, I'd credit most of the drop to
tagReadMode: "on-demand". Climbing from 300–400 ms to 1,000 ms over a few days fits the scan from #31, whose cost grows with the total number of keys. MGET doesn't save a round trip, since the per-tag GETs already went out together; what it cuts is commands, and with Redis instrumented, spans.Looking forward to the production numbers in #31. They'll help decide whether
"on-demand"becomes the default.