Skip to content

perf(server-core): pass SSR cache bytes through and store default cache entries as bytes - #9296

Open
deepcoldy wants to merge 1 commit into
perf/ssr-cache-single-flightfrom
perf/ssr-cache-entry-format
Open

deepcoldy wants to merge 1 commit into
perf/ssr-cache-single-flightfrom
perf/ssr-cache-entry-format

Conversation

@deepcoldy

Copy link
Copy Markdown
Contributor

Summary

Stacked on #9295; review the last commit only.

Problem (on main; PR4 does not change this part)

  • createTransformStream() decoded every rendered chunk and encoded it again, only to pass it on.
    • It decoded without stream: true, so a multi-byte character split across chunks became U+FFFD in miss and expired responses.
    • This bug is latent: Modern.js' Node renderer ends its chunks on character boundaries.
  • Every hit and stale response ran JSON.parse() on the whole { val, cursor } entry and encoded the HTML again. Every write ran JSON.stringify().

Change (plugins/render/ssrCache.ts)

  • Pass-through. An identity TransformStream forwards the rendered bytes.
    • The HTML is still decoded on the side, now with stream: true, for the no-ssr-cache / renderLevel checks and for custom containers.
    • Chunks of other BufferSource types are forwarded as a Uint8Array over the same bytes.
  • Default memory storage (no customContainer). A page is one Uint8Array: an 8-byte float64 cursor followed by the rendered bytes.
  • Custom containers keep the same JSON of { val, cursor }, byte-identical to main. Existing entries (e.g. in Redis) and rolling deploys work in both directions.
  • Removed helpers. The internal createTransformStream / transformResponse are removed. Nothing uses them, and no entry point (., ./node, ./hono) exports them: src/index.ts re-exports only createErrorHtml, onError and ErrorDigest from utils.

Behaviour changes and scope

  • Only SSR-cached routes are affected. Faster hits need the default memory storage. Custom-container hits are unchanged, but their renders still gain. Uncached routes run the same code.
  • Chunks. Cached miss responses carry the renderer's own chunks, the same as without the cache.
  • Invalid UTF-8 from a renderer. Misses and default-storage hits carry the raw bytes; main replaced them with U+FFFD. Custom-container hits still replay the decoded HTML.
  • LRU accounting. The default storage counts UTF-8 bytes + 8 instead of the JSON's UTF-16 length.
    • A ~210 KB ASCII page goes from 232,988 to 210,207.
    • A CJK page goes from 238,771 to 245,424.
  • Memory. Pages live off the V8 heap, so they count in RSS / external memory instead of heapUsed. Memory per page drops, by up to half for pages with non-Latin-1 characters.

中文摘要

问题(main 上,PR4 未改动这部分):

  • createTransformStream() 把每个渲染 chunk 解码再编码,只为原样透传。
  • 解码时没有用 stream: true,跨 chunk 的多字节字符会在 miss / expired 响应里变成 U+FFFD。这是潜在问题,Modern.js 自带的 Node 渲染器按字符边界切块。
  • 每次命中和 stale 都要对整个 { val, cursor } 做 JSON.parse(),再把 HTML 编码一次。
  • 每次写入都要做 JSON.stringify()。

改动:

  • 恒等 TransformStream 原样透传字节。
    • HTML 仍在旁路解码(改用 stream: true),用于 no-ssr-cache / renderLevel 判断和自定义容器。
    • ArrayBuffer、DataView 等 chunk 转成同一段内存上的 Uint8Array。
  • 默认内存存储(未配置 customContainer)把每个页面存成一个 Uint8Array:8 字节 float64 cursor 加渲染出的原始字节。
    • 透传时字节先复制进逐步翻倍的 slab,最后拷贝一次成精确大小的条目。
    • 命中、stale 和共享渲染直接发送这些字节,全程无 JSON,LRU 按 byteLength 计量。
    • 旧版本写入的 JSON 字符串仍可读取。
  • 自定义容器仍读写原有 JSON,与 main 逐字节一致,Redis 等已有条目和滚动发布双向兼容。
  • 删除内部且未从包入口导出的 createTransformStream / transformResponse。

行为变化:

  • 只影响配置了 SSR 缓存的路由:命中加速只针对默认内存存储,自定义容器的命中不变、只有渲染受益,未缓存路由的代码路径不变。
  • miss 响应下发渲染器自己的 chunk,与不开缓存时一致。
  • 渲染器输出非法 UTF-8 时,miss 响应和默认存储的命中下发原始字节,自定义容器的命中仍是解码后的 HTML。
  • 默认存储的 LRU 计量改为 UTF-8 字节数 + 8,页面数据移到 V8 堆外(计入 RSS / external,不计入 heapUsed)。

Benchmark

Environment: Node v22.21.1 (micro-benchmarks also on v24.22.2), Intel Xeon Platinum 8457C, 64 logical CPUs, on a shared machine. Each server is pinned to one logical CPU with taskset, and a guard keeps other tasks off that CPU's sibling hyperthread.

Method:

  • A is a build of main (27beabb) and B is a build of this branch. Both run side by side under modern serve in production.
  • Each URL gets a 10 s warm-up, then 6 rounds of 10 s at 32 keep-alive connections. The rounds load A and B in parallel and swap their CPUs every other round.
  • The primary metric is server CPU ms per request: utime+stime from /proc, divided by completed requests.
  • Results are medians with [min…max], plus the median of the paired per-round deltas.
  • Every run had 0 non-2xx responses and 0 errors.
  • The bench app uses the default memory storage.

Noise floor. In an A/A run (main vs main), CPU/req medians were within ±0.6% on every URL (/bench/cached-large −0.5%), and every paired round within ±2.1%. Cache-herd A/A: sustained CPU/req ±2%, req/s ±2.5%. p99 moved up to ±12%, so it is not cited alone.

Attribution. This branch contains PR4, so run 1 measures PR4 and PR5 together. Run 3 compares main with PR4 alone, in the same session and with the same URL order.

E2E run 1: main vs this branch (PR4 + PR5)

URL bytes CPU ms/req A CPU ms/req B Δ CPU/req paired Δ median [min…max] req/s A → B p50 ms A → B p99 ms A → B
/bench/cached-large 196085 1.198 [1.191…1.214] 0.198 [0.190…0.204] −83.5% −83.5% [−84.3%…−83.0%] 831 → 5004 (+502.1%) 37.6 → 5.6 (−85.1%) 75.5 → 13.3 (−82.4%)
/bench/cached 26236 0.176 [0.169…0.185] 0.121 [0.120…0.135] −31.2% −31.1% [−35.1%…−22.4%] 5631 → 8157 (+44.8%) 4.5 → 3.3 (−27.1%) 28.3 → 9.2 (−67.7%)
/bench/cached-nosw 26270 0.183 [0.177…0.188] 0.130 [0.126…0.146] −28.8% −28.5% [−30.7%…−22.0%] 5395 → 7405 (+37.3%) 4.6 → 3.4 (−26.4%) 25.2 → 10.7 (−57.5%)
/bench/large (control) 195960 9.300 [9.211…9.680] 9.130 [9.071…10.714] −1.8% −1.4% [−2.4%…+10.7%] 107 → 109 (+1.8%) 280.5 → 276.0 (−1.6%) 563.8 → 563.1 (−0.1%)
/bench/small (control) 26125 3.000 [2.992…3.037] 2.888 [2.857…2.902] −3.7% −3.5% [−5.1%…−3.4%] 333 → 346 (+3.8%) 88.5 → 84.9 (−4.1%) 183.8 → 173.1 (−5.8%)

This PR's own share (CPU ms/req)

The share is (B/A in run 1) / (B/A in run 3) − 1:

URL main → PR4 + PR5 (run 1) main → PR4 (run 3) PR5 own (ratio of medians) PR5 own per paired round, median [min…max]
/bench/cached-large −83.5% −0.4% (paired +0.3%) −83.4% −83.7% [−84.2%…−83.1%]
/bench/cached −31.2% −12.6% −21.3% −19.9% [−34.0%…−10.3%]
/bench/cached-nosw −28.8% −10.4% −20.6% −17.4% [−26.1%…−13.3%]
/bench/large (same code path) −1.8% +3.7% −5.3% (noise, see below) −2.6% [−12.7%…+3.1%]
/bench/small (same code path) −3.7% −1.8% −1.9% (noise, see below) −2.7% [−3.2%…−0.9%]

E2E run 2: fresh servers, controls first (main vs this branch)

URL CPU ms/req A CPU ms/req B Δ CPU/req paired Δ median [min…max] req/s A → B p50 ms A → B
/bench/small 3.006 [2.943…3.240] 3.006 [2.905…3.268] +0.0% +0.2% [−1.3%…+1.2%] 332 → 332 87.9 → 87.7
/bench/large 9.750 [9.527…9.819] 8.969 [8.884…9.005] −8.0% −8.0% [−9.1%…−6.4%] 102 → 111 296.5 → 269.2
/bench/cached-large 1.243 [1.231…1.248] 0.224 [0.222…0.227] −81.9% −81.9% [−82.1%…−81.5%] 803 → 4421 39.0 → 5.9

Cache herd (10 expired bursts × 64 requests, then 20 s sustained at C=64)

URL pair burst renders A → B sustained req/s A → B sustained CPU ms/req A → B
/bench/cached (SWR) main → this branch 595 → 10 5174 → 8282 (+60.1%) 0.193 → 0.120 (−37.7%)
/bench/cached (SWR) main → PR4 only 609 → 10 5217 → 6313 (+21.0%) 0.191 → 0.158 (−17.2%)
/bench/cached-nosw main → this branch 559 → 10 5010 → 8059 (+60.9%) 0.199 → 0.122 (−38.8%)
/bench/cached-nosw main → PR4 only 621 → 10 4979 → 6226 (+25.0%) 0.200 → 0.158 (−21.1%)

Coalescing is unchanged from PR4 alone: 1 render per burst, and 19 in the sustained run. In the sustained run, this PR's own share is about −25% / −22% CPU/req and +32% / +29% req/s.

Where the gain applies

  • Hit of a large entry in the default memory storage (the target). /bench/cached-large:
    • CPU/req −83.5% (1.198 → 0.198 ms, about 1 ms per request).
    • req/s about 6× (831 → 5004), and p50 37.6 → 5.6 ms.
    • All 6 paired rounds fell between −84.3% and −83.0%, and fresh servers reproduced −81.9%.
    • PR4 alone measured −0.4% in the same session, so the gain is this PR's own.
  • ~26 KB cached pages, mostly ASCII. This PR adds about −20% CPU/req on top of PR4.
    • That holds across the ratio of runs, the per-round medians and the herd.
    • It is the difference of two runs, so it is less precise, about ±5 points.
    • The gain is smaller per byte than on cached-large: one-byte ASCII strings parse and encode on V8's fast paths, and the large page has CJK text.
  • Uncached routes: no change. /bench/large and /bench/small run the same code on both sides: matchCacheControl returns undefined, so ssrRender calls the request handler directly.
    • The fresh-server control is /bench/small at +0.0%.
    • /bench/large moved −1.8% (run 1), −8.0% (run 2) and +3.7% (PR4 alone). That is variance between server pairs on identical code, not a gain.
    • /bench/small's −3.7% appears only after the cached URLs, and PR4 alone shows it too.
  • Mechanism. A diagnostic --cpu-prof of the cached-large hit (not a measurement):
    • On main, the time goes to getCacheResult self time, i.e. JSON.parse of the entry (24.8%), undici toUSVString (8.0%) and UTF-8 encoding (encode 9.0% + encodeUtf8String 7.4%).
    • On this branch those frames are gone. What remains is Response copying the bytes (extractBody 13.3%) and writev (13.9%).
E2E run 3 in full: main vs PR4 only (isolation control)
URL CPU ms/req A CPU ms/req B Δ CPU/req paired Δ median [min…max] Δ req/s Δ p50 Δ p99
/bench/cached-large 1.194 [1.174…1.216] 1.189 [1.186…1.243] −0.4% +0.3% [−0.5%…+2.2%] +0.4% −0.3% −0.3%
/bench/cached 0.176 [0.165…0.186] 0.154 [0.151…0.163] −12.6% −13.2% [−15.0%…−1.3%] +14.4% −2.8% −60.4%
/bench/cached-nosw 0.178 [0.176…0.196] 0.160 [0.157…0.186] −10.4% −11.2% [−18.3%…+5.5%] +9.9% −6.4% −56.0%
/bench/large 9.149 [9.108…9.544] 9.485 [9.170…10.997] +3.7% +4.1% [+0.0%…+19.5%] −3.5% +4.5% +6.4%
/bench/small 2.980 [2.948…2.996] 2.925 [2.895…2.968] −1.8% −1.6% [−2.8%…−0.2%] +1.8% −1.7% −0.3%
Bench app and commands
  • App. The bench app is tests/integration/ssr/fixtures/streaming (streaming SSR, nested routes with loaders) plus untracked generated files. It has 127 routes and a ~24 KB template.

  • Cache config. server/cache.ts exports only cacheOption, so the default memory storage is used:

    export const cacheOption = {
      '^/bench/cached-nosw(?:[/?#]|$)': { maxAge: 1000, staleWhileRevalidate: 0 },
      '^/bench/cached-large(?:[/?#]|$)': { maxAge: 24 * HOUR, staleWhileRevalidate: 24 * HOUR },
      '^/bench/cached(?:[/?#]|$)': { maxAge: 1000, staleWhileRevalidate: 60000 },
    };
  • URLs.

    • /bench/cached and /bench/cached-nosw are ~26 KB pages, and their loader sleeps 20 ms.
    • /bench/cached-large is ~196 KB: 1000 list items with CJK text, plus _ROUTER_DATA. It is a hit on every request after the first.
    • /bench/large (the same list page without the cache) and /bench/small are the uncached controls.
  • Load generator. A Node http keep-alive client in a closed loop. Functional checks run on both servers before every measurement.

  • Commands (temporary scripts outside the repo):

    • Runs 1 and 3: ab.sh <lane> <out> /bench/cached-large /bench/cached /bench/cached-nosw /bench/large /bench/small.
    • Run 2: the same command with /bench/small /bench/large /bench/cached-large.
    • Herd: cache-herd.sh <lane> <out> with the defaults.
    • For PR4 alone, the same lane was switched to PR4's commit.

Micro-benchmarks

Method:

  • Every sample runs in a fresh process pinned to one CPU, and the variant order rotates each round. A sample is the median of 5 batches, after warm-up.
  • Each cell is the median across rounds: 9 (Node 22) or 7 (Node 24) for the main set, and 7 / 5 for the miss set.
  • The render streams fresh 2 KB Buffer chunks unless noted. Pages are realistic markup plus _ROUTER_DATA. The custom container is a Map.
  • "vs PR4" is this PR's own effect. Values are µs/op:
Path Page Container Node 22: main → PR4 → this PR vs PR4 Node 24: main → PR4 → this PR vs PR4
hit ~50 KB default 91.7 → 91.4 → 11.7 −87% 108.4 → 107.7 → 38.8 −64%
hit ~210 KB default 536.6 → 532.1 → 145.6 −73% 523.9 → 527.2 → 134.0 −75%
hit ~210 KB CJK default 1289.2 → 1293.3 → 156.6 −88% 1375.8 → 1366.5 → 154.9 −89%
hit ~210 KB custom 525.4 → 523.3 → 530.5 +1% 513.4 → 522.5 → 525.3 +1%
render (expired) ~50 KB default 517.8 → 551.6 → 298.2 −46% 342.7 → 355.5 → 125.2 −65%
render (expired) ~210 KB default 2234.3 → 2252.4 → 1095.3 −51% 2014.4 → 1820.3 → 630.9 −65%
render (expired) ~210 KB CJK default 4226.1 → 4297.9 → 1663.4 −61% 3747.8 → 3511.6 → 1134.5 −68%
render (expired) ~210 KB custom 2193.3 → 2180.9 → 1997.7 −8% 1912.0 → 1744.3 → 1550.3 −11%
miss, 2 KB chunks ~210 KB default 1882.9 → 1890.3 → 1123.3 −41% not run
miss, 2 KB chunks ~210 KB custom 1872.8 → 1836.8 → 1651.7 −10% not run
miss, 128 B chunks ~210 KB default 7282.3 → 7773.7 → 5292.5 −32% 4577.8 → 4708.8 → 2551.1 −46%
miss, 128 B chunks ~210 KB custom 7215.7 → 7893.5 → 5948.2 −25% 4658.7 → 4809.6 → 3356.3 −30%
  • Absolute saving per hit vs main (default storage): about 70–85 µs at 50 KB, 345–390 µs at 210 KB and 1.1–1.2 ms at 210 KB CJK, on both Node versions.
  • Hit ratios. They depend on allocator state and batch size: 2.8×–7.8× at 50 KB and 3.5×–4.1× at 210 KB. Cite /bench/cached-large for the end-to-end effect.
  • Custom containers. Hits are unchanged, and renders are 6–32% faster than main.
  • PR4 on its own does not change hit costs. It trims 6–10% off the 210 KB render on Node 24, and is 7–11% slower than main on Node 22 for 128 B chunk streams, which this PR more than offsets.
  • Reproduced by both reviewers. Two independent reviewers re-ran the benchmark on Node 22 (one of them also on Node 24) and got medians within about 4–5%.

Related Links

Validation Evidence

  • Repo checks:
    • cd packages/server/core && npx rstest run: 162 passed, 0 failed.
    • npx tsc --noEmit -p tsconfig.json: OK.
    • rs fmt / rs lint on the changed files: clean.
    • pnpm check-changeset: exit 0.
    • pnpm check-test-governance --base origin/main --head HEAD: passed.
  • Build. pnpm --filter @modern-js/server-core build: OK. The built ssrCache.js is identical to the benchmarked build, and no transformStream is left in dist.
  • Integration. cd tests && npx rstest run integration/ssr/tests/base.test.ts: 10 passed, 2 skipped.
    • Re-run with the fixture temporarily on the default storage (no customContainer, then reverted): same result.
  • Temporary scripts outside the repo, on Node 20.20.2, 22.21.1 and 24.22.2:
    • Differential check, main vs branch. 913/913 checks pass. They cover:
      • miss, hit, stale and expired;
      • custom-container JSON compatibility in both directions;
      • the default-storage entry layout (the entry owns a buffer of the exact size);
      • uncacheable pages, single flight and invalid UTF-8.
    • HTTP check. Over a real socket, miss and hit bodies equal the rendered bytes.
    • Fuzz through the public getRenderHandler. 3930/3930 checks pass. Inputs:
      • 131 page sizes from 0 B to 600 KB, including the slab boundaries;
      • random chunk sizes from 1 B to 200 KB;
      • Uint8Array, pooled Buffer, ArrayBuffer, DataView and Uint16Array chunks;
      • consumers that transfer the buffers they read.
    • new Response(Uint8Array) copies the bytes (also checked on 22.16.0), so the cached entry stays intact when the client transfers a chunk.
  • Edge cases (temporary scripts):
    • ArrayBuffer / DataView chunks over HTTP. Both the miss and the hit are 200 with the full body. main corrupts the miss with U+FFFD.
    • A JSON entry in the default namespace is served as a hit, the same as on main.
    • Abort or error mid-render leaves no partial entry.
    • Stress run. 600 responses with multi-byte content, random chunk sizes and buffer-transferring consumers: 0 bad bodies on the branch, against 80 with U+FFFD on main.
  • Mutation runs on ssrCache.test.ts. The suite fails if the full slab is not pushed, the slab's remainder is not filled, or the last slab is left out of the entry. It also fails for each of 3 entry-format mutants.
  • E2E functional checks:
    • status, byte counts and the x-render-cache sequence pass on both servers;
    • Content-Type is text/html; charset=UTF-8 on both;
    • miss and hit bodies are byte-identical within each build;
    • main and branch bodies differ only in the server port and the render timestamp.
  • Reviews. Two independent reviews found no blockers or majors. Their minor findings were fixed in one round: non-Uint8Array chunks, foreign values in the default namespace, and one copy per chunk (now slabs).
  • Not run:
    • Full pnpm test:ut / test:framework / test:builder. The change is limited to server-core's SSR cache.
    • E2E with a custom container. The bench app uses the default storage, so custom containers are covered by the unit tests, the differential check and the micro-benchmarks.
    • The U+FFFD fix in the E2E app: its chunks never split a character, so the fix is covered only by the unit test and the scripts.

Retained Tests and Exceptions

  • What changed. Only the existing packages/server/core/tests/plugins/ssrCache.test.ts was updated. No test files or fixtures were added.
  • Both storages. The hit, stale and expired tests now run against a custom container and against the default memory storage (describe.each). The default storage is used whenever no customContainer is set, and it is where the entry format changed, yet nothing covered it before.
  • Larger hit page. The hit test now caches a ~120 KB page in chunks of 2 B, 20,001 B and ~100 KB that split an emoji. This covers slab overflow, a chunk larger than the next slab, and a character split across chunks.
  • Assertions. They read responses (x-render-cache + body) instead of container internals, so they do not depend on the storage format.
  • Temporary scripts. HTTP, fuzz, cross-version and compatibility checks stay in scripts outside the repo.
  • Exceptions. None.

Checklist

  • I have added a changeset via pnpm run change if published package behavior changes. (@modern-js/server-core patch)
  • I have updated the documentation where needed. N/A: there is no API or config change, and the SSR cache docs do not describe the storage format.
  • I have recorded validation evidence and the rationale for retained tests or exceptions.

🤖 Generated with Claude Code

…he entries as bytes

The SSR cache piped every rendered chunk through createTransformStream(),
which decoded it to a string and encoded it again only to pass it on. It
decoded each chunk on its own, so a character split across chunks reached
the client as U+FFFD. Every cache hit JSON.parse()d the whole entry and
encoded the HTML again, and every write JSON.stringify()d it.

- Pass the rendered bytes through an identity TransformStream. The HTML for
  the cache is still decoded on the side with `stream: true`. Chunks that
  are an ArrayBuffer or another ArrayBufferView are passed on as a
  Uint8Array, as the decoding and encoding used to do.
- The default in-memory storage keeps each page as one byte array: the
  cursor as a float64, followed by the bytes as they were rendered. Hits
  and stale responses send those bytes (Response copies them), without
  JSON or encoding. The memory container sizes the entry by its byte
  length. Requests that share a render get the same bytes.
- The bytes are copied into a few slabs of growing size while they pass,
  as the client may transfer the buffers it reads, then into the entry.
  One copy per chunk cost much more for streams of many small chunks.
- Custom containers keep reading and writing the JSON of { val, cursor },
  so entries already stored, e.g. in Redis, keep working. A JSON string
  found in the default storage is still read as before.
- Remove the internal createTransformStream / transformResponse helpers,
  which are no longer used and are not exported by the package.
- Run the hit, stale and expired tests against the default storage too,
  which no test covered. The hit test now caches a page of about 120 KB
  in chunks that split an emoji.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Rsdoctor Bundle Diff Analysis

📊 Quick Summary
Project Total Size Change
bundle-diff 514.3 KB 0

Generated by Rsdoctor GitHub Action

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant