Skip to content

Stampede prevention and L1 cache #34

Open

Description

@markomitranic

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:

  1. 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.
  2. Deduplication Concurrent reads of one key share one Redis read, so it protects your Redis from sudden spikes.
  3. 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

  1. leejpsd commented on Nov 23, 2026

    @leejpsd
    Owner

    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() reads revalidateSec and forget() reads tags, and get() here returns both. createIncrementalCacheHandler() returns a class, so it wraps directly:

    module.exports = withMicroCache(
      createIncrementalCacheHandler({ client: { type: "redis", url: process.env.REDIS_URL } }),
      { broadcast },
    );

    I ran it that way against a local Redis to be sure: 100 reads after a set() made no Redis calls, and 20 concurrent fetch misses 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:

    • Pages (ISR): concurrent requests for the same page already share one cache read and one render through Next's response cache.
    • 'use cache': since 16.3 (Improve deduping of concurrent 'use cache' invocations vercel/next.js#91830), concurrent calls with the same key share one handler get() and, on a miss, one fill, across requests. (The wrapper is for the singular cacheHandler, 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.
    • L1: nothing in Next sits in front of a custom handler in production, so this part helps on every path. Without broadcast, an invalidation on another server reaches the L1 only after ttlMs.

    Two things on my side:

    • I'll link this issue from the README, so people looking for an L1 or stampede protection can find it.
    • Checking this against the README, the singleFlight section oversells itself. It says followers skip the refresh, but Next decides to refresh after get() 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.

  2. markomitranic commented on Nov 23, 2026

    @markomitranic
    Author

    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

    Scenario Redis round trip @fortedigital/nextjs-cache-handler @leejpsd/nextjs-cache-handler leejpsd + L1, dedup and miss latch
    Warm cache, steady traffic (40 req/s across 415 pages) 3 ms 24 ms response (median) 3,667 Redis commands 23 ms response (median) 24,068 Redis commands 18 ms response (median) 11,453 Redis commands
    40 ms 165 ms response (median) 3,545 Redis commands 114 ms response (median) 23,776 Redis commands 88 ms response (median) 12,036 Redis commands
    Traffic spike on one page (200 requests at once) 3 ms 482 ms response (median) 35 Redis commands 531 ms response (median) 69 Redis commands 379 ms response (median) 18 Redis commands
    40 ms 572 ms response (median) 7 Redis commands 623 ms response (median) 35 Redis commands 639 ms response (median) 18 Redis commands
    128 pages invalidated during live traffic 3 ms 1.1 s response (p95) 51 ms response (p95) 56 ms response (p95)
    40 ms 1.5 s response (p95) 142 ms response (p95) 167 ms response (p95)
    Data shared by every page invalidated, then 150 different pages requested at once 3 ms 22.5 s response (p95) 150 backend calls 1.3 s response (p95) 150 backend calls 1.2 s response (p95) 2 backend calls
    40 ms 32.8 s response (p95) 150 backend calls 1.2 s response (p95) 150 backend calls 1.1 s response (p95) 2 backend calls
    Every page invalidated at once, slow backend (30 req/s) 3 ms 2.8 s response (p99) 42 backend calls 167 ms response (p99) 28 backend calls 277 ms response (p99) 6 backend calls
    40 ms 7.0 s response (p99) 102 backend calls 336 ms response (p99) 28 backend calls 389 ms response (p99) 6 backend calls

    We 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:

    1. When I ran a large ecommerce website on Vercel, I resorted to Upstash Redis, as a way to lower the volatile ISR costs (also Vercel's cache reads varied between 20ms and 700ms!!) However, that comes with a tradeoff, 20-40ms network read overhead. Aggressive L1 lowered it to nanoseconds.
    2. When i ran it on Azure, we had our own Redis, and four availability zones, so while there was "some" win regarding L1 itself, the biggest win was a side-effect, the deduplication/coalescence
  3. leejpsd commented on Nov 24, 2026

    @leejpsd
    Owner

    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.

  4. leejpsd commented on Nov 24, 2026

    @leejpsd
    Owner

    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.

  5. markomitranic commented on Nov 24, 2026

    @markomitranic
    Author

    @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.

    Scenario Redis forte leejpsd 1.1.0 leejpsd 1.1.1 wrapper on 1.1.0 wrapper on 1.1.1
    Warm cache, steady traffic 3 ms 3,667 24,068 2,432 11,453 1,180
    40 ms 3,545 23,776 2,465 12,036 1,217
    Traffic spike on one page 3 ms 35 69 9 18 3
    40 ms 7 35 5 18 3
    128 pages invalidated 3 ms 11,287 32,394 6,332 19,332 3,774
    40 ms 11,315 18,060 6,264 19,921 2,012
    Shared data invalidated, 150 pages at once 3 ms 6,019 15,001 2,683 10,364 1,674
    40 ms 6,020 14,867 2,689 10,379 1,675
    Whole site invalidated, slow backend 3 ms 17,471 62,716 10,416 33,432 5,094
    40 ms 17,924 61,992 10,357 33,144 5,096
  6. markomitranic commented on Nov 24, 2026

    @markomitranic
    Author

    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:

    • When renders ask for the same key at the same moment, they share one Redis read.
    • When a fetch is missing, the first render calls the underlying service and the others wait for its answer. They wait 5 s at most.
    Scenario Redis leejpsd 1.1.1 leejpsd 1.1.1 + shared fetches
    Warm cache, steady traffic (median) 3 ms 23 ms, 2,432 Redis cmds 24 ms, 2,432 Redis cmds
    40 ms 115 ms, 2,465 114 ms, 2,394
    Traffic spike on one page (median) 3 ms 544 ms 541 ms
    40 ms 565 ms 706 ms
    128 pages invalidated (p95) 3 ms 48 ms 55 ms
    40 ms 167 ms 142 ms
    Shared data invalidated, 150 pages at once (p95) 3 ms 1.3 s, 150 backend calls 1.2 s, 2 backend calls
    40 ms 1.3 s, 150 1.0 s, 2
    Whole site invalidated, slow backend (p99) 3 ms 205 ms, 31 backend calls 172 ms, 6 backend calls
    40 ms 311 ms, 48 433 ms, 6
    /* eslint-disable node/no-process-env */
    import { createIncrementalCacheHandler } from '@leejpsd/nextjs-cache-handler/incremental';
    
    const RedisCacheHandler = createIncrementalCacheHandler({
    	client: { type: 'redis', url: process.env.REDIS_URL },
    	keyPrefix: process.env.REDIS_CACHE_PREFIX || undefined,
    	buildNamespace: 'shared',
    	compression: 'gzip',
    });
    
    export default withCoalescing(RedisCacheHandler);
    
    /**
     * Makes concurrent renders share upstream fetches, so a publish costs one origin call per missing fetch.
     *
     * When a fetch is missing, the first render fetches it and the others wait for its `set()`, then clear the reads
     * their handler remembers for the request and read the stored answer. Next stores only 200 answers and builds one
     * handler per request, so when the request that started the fetch asks again, it ended without one and everyone
     * fetches for themselves. After five seconds waiters give up anyway.
     * @example withCoalescing(RedisCacheHandler); // a handler class Next can use as its cacheHandler
     */
    function withCoalescing(Handler) {
    	const refills = new Map();
    
    	function openRefill(key, startedBy) {
    		const { promise, resolve } = Promise.withResolvers();
    		const timer = setTimeout(() => closeRefill(key), 5_000);
    
    		refills.set(key, { startedBy, promise, resolve, timer });
    	}
    
    	function closeRefill(key) {
    		const refill = refills.get(key);
    
    		if (!refill) {
    			return;
    		}
    
    		clearTimeout(refill.timer);
    		refill.resolve();
    		refills.delete(key);
    	}
    
    	return class CoalescingCacheHandler extends Handler {
    		#request = Symbol('request');
    
    		async get(key, ctx) {
    			const entry = await super.get(key, ctx);
    
    			if (entry || ctx?.kind !== 'FETCH') {
    				return entry;
    			}
    
    			const refill = refills.get(key);
    
    			if (!refill) {
    				openRefill(key, this.#request);
    
    				return null;
    			}
    
    			if (refill.startedBy === this.#request) {
    				closeRefill(key);
    
    				return null;
    			}
    
    			await refill.promise;
    			this.resetRequestCache();
    
    			return super.get(key, ctx);
    		}
    
    		async set(key, data, ctx) {
    			await super.set(key, data, ctx);
    			closeRefill(key);
    		}
    	};
    }
  7. leejpsd commented on Nov 25, 2026

    @leejpsd
    Owner

    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:

    • Waiters share the origin call, not the Redis read. Each one reads before waiting, then waits for the first render's 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 to set(), before the Redis write, would remove it.
    • Next only calls 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.
  8. royvou commented on Nov 25, 2026

    @royvou

    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.

  9. leejpsd commented on Nov 25, 2026

    @leejpsd
    Owner

    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: true or 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions