Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/isr-tag-read-mget.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@leejpsd/nextjs-cache-handler": patch
---

ISR handler: read all of an entry's tag states with one `MGET` instead of one `GET` per tag (#34). A page with five `_N_T_` layout tags now costs two Redis commands per `get()` instead of six; round trips were already one thanks to auto-pipelining, so this matters for per-command pricing and command-rate limits. On Redis Cluster, where the un-namespaced tag keys never share a slot, the handler keeps reading key by key: from the start when the client is the Cluster adapter (new `isCluster` flag on `RedisClientLike`) or `hashTag: true` is set, otherwise from the first `CROSSSLOT` reply on, retrying that read in place and logging one warning. The same fallback applies when `MGET` can never work for another reason: an ACL that allows `GET` but not `MGET`, a server that does not know the command, or a custom client without a usable `mGet`. `tag.expiration.read` is now also emitted by the ISR handler with `meta.strategy` (`"mget"` or `"per-key"`).
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,13 @@ Full reference: [`docs/api.md`](./docs/api.md).
Cluster support is validated by a dedicated e2e suite against a real
3-master cluster (`npm run test:cluster`, also in CI) — covering the
multi-key Lua scripts, per-master SCAN propagation, and both handlers.
Not yet load-tested at production scale.
Not yet load-tested at production scale. The flag also tells the ISR
handler to read tag states key by key: on a single node it reads all of
a page's tags with one `MGET`, but ISR tag keys are deliberately
un-namespaced (so `revalidateTag` survives a deploy) and never share a
slot. Without the flag, a Cluster client still works: the first
`CROSSSLOT` reply switches that handler to per-key reads and logs one
warning. A Redis user whose ACL denies `MGET` is handled the same way.
- [ ] **Redis `maxmemory-policy: allkeys-lru` or `noeviction`** — if you need
bounded memory, choose `allkeys-lru`. Otherwise `noeviction` keeps
tag indices intact.
Expand Down
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ ctx contract are accepted (`ctx.cacheControl.revalidate` / `kind` and
| `singleFlight` | `boolean` | `false` | opt-in refresh lock at the SWR boundary (leader/follower metrics; does not suppress refreshes) |
| `singleFlightLockTtlSec` | `number` | `10` | lock TTL for `singleFlight` |
| `isBuildPhase` | `() => boolean` | `NEXT_PHASE === "phase-production-build"` | build-phase gate override |
| `hashTag` | `boolean` | `false` | wrap namespace in `{}` — **required on Redis Cluster** (multi-key Lua) |
| `hashTag` | `boolean` | `false` | wrap namespace in `{}` — **required on Redis Cluster** (multi-key Lua). Also makes the ISR handler read tag states key by key instead of with one `MGET`, which Cluster refuses across slots; without it a Cluster client is detected on the first `CROSSSLOT` |
| `tagPubSub` | `boolean` | `false` | push-based cross-instance tag propagation (plural handler; ~3ms); scan polling remains the safety net; unavailable on Cluster |
| `tagReadMode` | `"scan" \| "on-demand"` | `"scan"` | plural handler only. `scan`: `refreshTags()` SCANs the namespace's tag markers once per request (cost grows with total keys in Redis, not with tags: ~20 ms at 20k keys, 65–170 ms at 100k on a local Redis). `on-demand`: no scan; `get()` and `getExpiration()` `MGET` exactly the tags they need (one extra round trip per `get()`). See [#31](https://github.com/leejpsd/nextjs-cache-handler/issues/31) |
| `onMetric` | `(event: MetricEvent) => void` | — | telemetry hook; emitter errors are swallowed |
Expand Down
19 changes: 17 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,23 @@ For multi-instance deployments:
With `tagReadMode: "on-demand"` (#31) step 2 is a no-op and steps 3 and 4
read the markers for exactly the tags they are given with one `MGET`,
merging them into the local mirror, so Redis stays the source of truth and
no request pays for a scan. That is also how the singular handler has always
read tags.
no request pays for a scan.

The singular (ISR) handler has always read tags on demand too. Since #34 it
reads all of an entry's tag states with one `MGET`, so a page carrying five
`_N_T_` layout tags costs two commands per `get()` (entry + markers), not
six. On Redis Cluster that `MGET` fails with `CROSSSLOT`, because ISR tag
keys are deliberately un-namespaced and so never share a slot; there the
handler reads key by key (one auto-pipelined round trip, one command per
tag). It knows it is on Cluster from the adapter's `isCluster` flag or
`hashTag: true`, and otherwise latches to per-key reads on the first
`CROSSSLOT` reply, retrying that read in place. The same latch covers the
other cases where `MGET` can never work: a Redis user whose ACL allows `GET`
but not `MGET`, a server or proxy that does not know the command, and a
custom client whose `mGet` is missing or malformed. Timeouts and dropped
connections do not latch. `scripts/bench-isr-tag-read.mjs`
prints the command count per `get()` for both strategies against a local
Redis.

The reference implementation in next-redis-cache-demo measured **6.4 ms**
mean propagation across two ECS tasks under sustained load with this
Expand Down
86 changes: 86 additions & 0 deletions scripts/bench-isr-tag-read.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/env node
// #34: how many Redis commands one ISR get() costs, by tag count, for the
// two ways the handler can read tag states: one MGET (default on a single
// node) and one GET per tag (what Redis Cluster needs; also what every
// release before this one did on a single node).
//
// npm run build
// REDIS_URL=redis://127.0.0.1:6390 node scripts/bench-isr-tag-read.mjs [runs]
//
// The target database is FLUSHED. The script refuses to run against a
// non-empty database unless BENCH_FLUSH=1 is set. Needs a single-node Redis.

import { createClient } from "redis";

import { createIncrementalCacheHandler } from "../dist/incremental/index.js";

const RUNS = Number(process.argv[2] ?? 200);
const url = process.env.REDIS_URL ?? "redis://127.0.0.1:6390";

if (!Number.isFinite(RUNS)) {
console.error("usage: bench-isr-tag-read.mjs [runs]");
process.exit(1);
}

const raw = createClient({ url });
raw.on("error", () => {});
await raw.connect();
if ((await raw.dbSize()) > 0 && process.env.BENCH_FLUSH !== "1") {
console.error(`${url} is not empty; set BENCH_FLUSH=1 to flush it.`);
await raw.quit();
process.exit(1);
}
await raw.flushAll();

// Total command count seen by the server, from INFO commandstats.
async function commands() {
const info = await raw.sendCommand(["INFO", "commandstats"]);
let total = 0;
for (const m of String(info).matchAll(/cmdstat_(\w+):calls=(\d+)/g)) {
if (m[1] !== "info") total += Number(m[2]);
}
return total;
}

// The entry's own tags plus the implicit `_N_T_` tag Next adds for every
// layout segment on the way to the page.
function tagsFor(n) {
return Array.from({ length: n }, (_, i) =>
i % 2 === 0 ? `tag-${i}` : `_N_T_/seg-${i}`
).join(",");
}
const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 60 } };
const body = Buffer.from("<html>".padEnd(4096, "."));

const modes = [
{ label: "mget (default)", opts: {} },
// hashTag only changes the entry key's shape; on a single node that is
// harmless, and it makes the handler read tag states key by key.
{ label: "per-key (Cluster / <=1.1.0)", opts: { hashTag: true } },
];

const rows = [];
for (const n of [1, 3, 5, 7, 10]) {
const row = { tags: n };
for (const mode of modes) {
const Handler = createIncrementalCacheHandler({
client: { type: "redis", url },
buildNamespace: `bench-${n}-${mode.label.slice(0, 4)}`,
...mode.opts,
});
await new Handler().set(`/page-${n}`, { kind: "APP_PAGE", body, headers: { "x-next-cache-tags": tagsFor(n) } }, ctx);
await new Handler().get(`/page-${n}`, ctx); // warm-up (connects)
const before = await commands();
for (let i = 0; i < RUNS; i++) {
await new Handler().get(`/page-${n}`, ctx);
}
row[mode.label] = ((await commands()) - before) / RUNS;
}
rows.push(row);
}

console.log(`Redis commands per ISR get(), ${RUNS} reads each (entry GET included)`);
console.table(rows);
await raw.flushAll();
await raw.quit();
process.exit(0);
2 changes: 1 addition & 1 deletion skills/nextjs-redis-cache/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ Facts that prevent misdiagnosis:
| `fallback: "auto"\|"always"\|"never"` | auto | `never` = strict (miss on Redis failure); `always` = no Redis (build/dev) |
| `singleFlight: true` | off | To measure duplicate refresh work across instances at revalidate boundaries (leader/follower metrics; it does not suppress refreshes) |
| `abortTimeoutMs` | 1500 | Per-op Redis deadline; timeouts degrade to miss |
| `hashTag: true` | off | REQUIRED on Redis Cluster |
| `hashTag: true` | off | REQUIRED on Redis Cluster (multi-key Lua; also switches ISR tag reads from one `MGET` to per-key GETs, which Cluster needs) |
| `onMetric` | — | Wire `createOtelMetricEmitter()` from `@leejpsd/nextjs-cache-handler/otel` |
| `tagPubSub: true` | off | 0.4+: push-based cross-instance invalidation (~3ms vs seconds); polling stays as safety net; not on Cluster |
| `tagReadMode: "on-demand"` | `"scan"` | 1.1+: Redis holds many keys (tens of thousands) and `refreshTags()` shows up in request latency. Skips the per-request SCAN; `get()` MGETs only the entry's tags (one extra round trip) |
Expand Down
118 changes: 110 additions & 8 deletions src/incremental/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type {
IncrementalCacheData,
Logger,
MetricEmitter,
RedisClientLike,
} from "../types.js";

import {
Expand Down Expand Up @@ -92,6 +93,15 @@ interface HandlerState {
/** Tag states, by bare tag (no namespace prefix — see tagMetaKey comment). */
memTagStates: Map<string, TagState>;
resolveNs: () => string;
/**
* How `readTagStates` fetches tag markers. `"mget"` (default) reads all of
* an entry's tags with one command. `"per-key"` sends one GET per tag; it is
* what Redis Cluster needs, because tag keys are deliberately un-namespaced
* (cross-deploy semantics) and so never share a hash slot. Starts as
* `"per-key"` when the options say Cluster (`hashTag: true`) and flips to it
* for good the first time an MGET fails with CROSSSLOT.
*/
tagReadStrategy: "mget" | "per-key";
}

function gateRedis(state: HandlerState): boolean {
Expand Down Expand Up @@ -125,6 +135,10 @@ function init(opts: CacheHandlerOptions): HandlerState {
memEntries: new MemoryStore<string>(opts.memoryMaxEntries),
memTagStates: new Map(),
resolveNs: () => resolveBuildNamespace(opts.buildNamespace),
// `hashTag` is only ever set for Cluster, so skip the MGET that would
// fail there. Everything else starts optimistic and may still latch to
// per-key on a CROSSSLOT reply (see readTagValues).
tagReadStrategy: opts.hashTag ? "per-key" : "mget",
};
}

Expand Down Expand Up @@ -253,14 +267,17 @@ async function readTagStates(
async () => {
const client = await state.conn.getOrConnect();
if (!client) return tags.map((t) => state.memTagStates.get(t) ?? null);
// Per-key GETs, not MGET: ISR tag keys are deliberately un-namespaced
// (cross-deploy semantics), so on Redis Cluster a multi-tag MGET is a
// guaranteed CROSSSLOT error — which the outer catch would silently
// swallow, disabling cross-instance revalidateTag for multi-tag
// entries. Auto-pipelining makes the fan-out one round trip anyway.
const values = await Promise.all(
tags.map((t) => client.get(tagMetaKey(state, t)))
);
const keys = tags.map((t) => tagMetaKey(state, t));
const values = await readTagValues(state, client, keys);
state.emit({
type: "tag.expiration.read",
meta: {
source: "redis",
op: "incremental.get",
count: tags.length,
strategy: state.tagReadStrategy,
},
});
return values.map((v) => {
if (!v) return null;
try {
Expand All @@ -276,6 +293,91 @@ async function readTagStates(
}
}

/**
* Fetch the raw marker values for `keys`.
*
* One `MGET` on a single node: one command whatever the tag count, which is
* what per-command pricing (Upstash) and command-rate limits see (#34). On
* Redis Cluster the keys sit in different slots, so an `MGET` is refused
* with CROSSSLOT: a client flagged `isCluster` (or options with `hashTag`)
* goes key by key from the start, and an unflagged Cluster client is caught
* on its first refusal.
*
* Any sign that `MGET` cannot be used here latches the handler to per-key
* reads for good and retries that read in place, so nothing is lost: a
* cross-slot refusal, a Redis user whose ACL allows GET but not MGET, a
* server or proxy that does not know the command, or a custom client whose
* `mGet` is missing or does not return one value per key. Without the
* latch those would fall through to the local tag mirror on every read and
* silently miss invalidations made by other instances. Transient failures
* (timeouts, dropped connections) are rethrown and do not latch.
*
* Per-key GETs are auto-pipelined by both supported clients, so they still
* cost one round trip; only the command count differs.
*/
async function readTagValues(
state: HandlerState,
client: RedisClientLike,
keys: string[]
): Promise<(string | null)[]> {
if (keys.length === 1) return [await client.get(keys[0]!)];
if (state.tagReadStrategy === "mget") {
if (client.isCluster) {
state.tagReadStrategy = "per-key";
} else if (typeof client.mGet !== "function") {
latchPerKey(state, "the client has no mGet method");
}
}
if (state.tagReadStrategy === "mget") {
try {
const values: unknown = await client.mGet(keys);
if (Array.isArray(values) && values.length === keys.length) {
return values as (string | null)[];
}
latchPerKey(state, "mGet did not return one value per key");
} catch (err) {
const reason = mgetRefusal(err);
if (!reason) throw err;
latchPerKey(state, reason);
}
}
return Promise.all(keys.map((k) => client.get(k)));
}

/** Switch to per-key reads for the life of this handler; warn once. */
function latchPerKey(state: HandlerState, reason: string): void {
// Concurrent first reads all see the same refusal; only the first warns.
if (state.tagReadStrategy === "per-key") return;
state.tagReadStrategy = "per-key";
state.logger.warn(
`MGET of tag states is not usable here (${reason}); reading tag states key by key from now on.`
);
}

/**
* Why an `MGET` error means "this command will never work here", or `null`
* for anything that may be transient.
*
* Cross-slot comes in two spellings: the server's `CROSSSLOT Keys in request
* don't hash to the same slot`, and ioredis's client-side check when
* auto-pipelining is on, `All the keys in a pipeline command should belong
* to the same slot`, which never reaches the server.
*/
function mgetRefusal(err: unknown): string | null {
const message =
err instanceof Error ? err.message : typeof err === "string" ? err : "";
if (/CROSSSLOT|same slot/i.test(message)) {
return "CROSSSLOT: Redis Cluster keeps these keys in different slots; set hashTag: true to skip this probe";
}
if (/NOPERM/i.test(message)) {
return "NOPERM: the Redis user may not run MGET";
}
if (/unknown command/i.test(message)) {
return "the server does not know MGET";
}
return null;
}

// ─── Handler class ──────────────────────────────────────────────────────────

export class IncrementalRedisCacheHandler {
Expand Down
1 change: 1 addition & 0 deletions src/shared/client/adapter-ioredis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type AnyRedis = Redis | Cluster;

function adapt(client: AnyRedis, isClusterClient = false): RedisClientLike {
return {
isCluster: isClusterClient,
get isOpen() {
// ioredis exposes a `status` string. Both single-node and cluster
// report "ready" once connected.
Expand Down
8 changes: 8 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ export interface RedisClientLike {
* both of which are used as fallbacks when this is absent.
*/
dispose?(): void;
/**
* `true` when the client talks to a Redis Cluster, where a multi-key
* command fails with `CROSSSLOT` unless every key hashes to the same slot.
* The ISR handler then reads tag states key by key instead of with one
* `MGET`. Set by `adaptCluster`; a raw Cluster client passed through a
* factory without this flag is still detected on the first `CROSSSLOT`.
*/
isCluster?: boolean;
}

export type RedisClientFactory = () =>
Expand Down
57 changes: 56 additions & 1 deletion tests/cluster/cluster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@
* - cross-"instance" (two handler objects) tag propagation on a cluster
* - tagPubSub degrades gracefully (no subscribe on the cluster adapter)
*/
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";

import { createCacheComponentsHandler } from "../../src/cache-components/index.js";
import { createIncrementalCacheHandler } from "../../src/incremental/index.js";
import {
adaptCluster,
createIoredisCluster,
} from "../../src/shared/client/adapter-ioredis.js";
import {
bufferToStream,
readStreamFully,
Expand Down Expand Up @@ -129,4 +133,55 @@ describe("Redis Cluster e2e — cacheHandler (ISR)", () => {
h.resetRequestCache();
expect(await h.get("/page", { kind: "APP_PAGE" })).toBeNull();
});

const multiTagPage = {
kind: "APP_PAGE" as const,
body: Buffer.from("multi-tag"),
headers: { "x-next-cache-tags": "posts,authors,_N_T_/page" },
};
const ctx = { kind: "APP_PAGE", cacheControl: { revalidate: 300 } };

it("tag states are read key by key on a cluster adapter: no MGET, invalidation still seen (#34)", async () => {
const ns = `cl-${Math.floor(Math.random() * 1e9)}`;
const client = adaptCluster(createIoredisCluster({ type: "cluster", nodes: NODES }));
const Handler = createIncrementalCacheHandler({
client: () => client,
hashTag: true,
abortTimeoutMs: 3000,
buildNamespace: ns,
});
const mget = vi.spyOn(client, "mGet");

await new Handler().set("/multi", multiTagPage, ctx);
expect(await new Handler().get("/multi", ctx)).not.toBeNull();
await new Handler().revalidateTag("authors"); // hard, one of three tags
expect(await new Handler().get("/multi", ctx)).toBeNull();
expect(mget).not.toHaveBeenCalled();
});

it("a cluster client without the isCluster flag or hashTag latches on the first CROSSSLOT and loses nothing", async () => {
const ns = `cl-${Math.floor(Math.random() * 1e9)}`;
const flagged = adaptCluster(createIoredisCluster({ type: "cluster", nodes: NODES }));
// Same adapter, flag hidden: what a raw Cluster client from a user factory looks like.
const client = Object.create(flagged, { isCluster: { value: undefined } }) as typeof flagged;
const warns: string[] = [];
const Handler = createIncrementalCacheHandler({
client: () => client,
abortTimeoutMs: 3000,
buildNamespace: ns,
logger: { debug() {}, info() {}, warn: (m: string) => warns.push(m), error() {} },
});
const mget = vi.spyOn(client, "mGet");

await new Handler().set("/latch", multiTagPage, ctx);
await new Handler().revalidateTag("posts"); // hard, before the first read
// First read: MGET → CROSSSLOT → per-key retry in the same read.
expect(await new Handler().get("/latch", ctx)).toBeNull();
expect(mget).toHaveBeenCalledTimes(1);
expect(warns.filter((w) => /CROSSSLOT/.test(w))).toHaveLength(1);

await new Handler().set("/latch-2", multiTagPage, ctx);
expect(await new Handler().get("/latch-2", ctx)).not.toBeNull();
expect(mget).toHaveBeenCalledTimes(1); // latched: no second probe
});
});
Loading
Loading