Skip to content

perf(serving): patch content comes from memory and goes out compressed - #770

Merged
allisonmahmood merged 7 commits into
mainfrom
perf/746-content-cache
Oct 18, 2026
Merged

allisonmahmood merged 7 commits into
mainfrom
perf/746-content-cache

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Every load of a scripted patch fetches its document from /~content/:patchId/:versionId. The server let the viewer in, then read the version's HTML from object storage: p50 122 ms in production, a large part of the content's 228–375 ms time to first byte. The body then went out uncompressed: 296 KB for a typical tier 2 patch.

Now, once the door has let the viewer in, the document comes from the host's memory, and it goes out compressed with brotli or gzip by Accept-Encoding, with Vary: Accept-Encoding. The door, retention, company, lifecycle and wire checks still run on every request, cache hits included. Only the storage read moves to memory. Browser caching is unchanged: private, no-store behind the door, and a public patch's current version keeps public, max-age=60.

Measured

On the local instance (pnpm dev up brightline), each patch was opened in Chromium through Playwright as Allison, 11 loads per run after a server restart. The throttled runs used CDP's 100 ms latency and 20 Mbps down, as in #761. The figures are medians of loads 2–11, plus 5 separate cold loads, each the first load after a restart. Wire bytes include response headers.

New Business (tier 2) main this branch
Content on the wire 235,112 B 96,195 B (br)
Storage reads in 22 loads 22 1
Warm time to first byte 6.0 ms 4.3 ms
Cold time to first byte, 5 restarts 19–26 ms 32–34 ms
Throttled, request to last byte 196 ms 139 ms
Kudos (tier 1) main this branch
Content on the wire 173,060 B 84,442 B (br)
Storage reads in 22 loads 22 1
Throttled, request to last byte 170 ms 135 ms

I counted storage reads with inotifywait on the stored document files, and they match the new contentLoad field: one read, then cached. The local store is a filesystem, about a millisecond away, so the warm gain here is small.

Expected in production: every load after a host's first read of a version skips the 122 ms p50 storage read, and a typical 296 KB document is about 120 KB with brotli. These documents compress 2.4–2.5× (234,517 → 95,556, 213,495 → 89,847, 172,465 → 83,803 bytes), less than the broker's 3.3×. With TLS and TCP slow start, cutting 175 KB saves more than the 57 ms it saved locally. Each host keeps its own copies, so after a deploy every host reads each version once. That first load pays the read plus compression, about 11 ms here and likely two to three times that on a 0.5 vCPU host; see below.

New Business and Kudos both rendered fully as their personas, with compression on and no browser errors. With curl, br, gzip and identity each decode to main's exact bytes. HEAD carries Content-Encoding: br, Vary and the br Content-Length. A signed-out request gets its 401 door with no Content-Encoding and no Vary.

Design

One cache helper for bundles and documents. I generalized #764's bundle cache into Content.makeArtifactCache. It holds the least-recently-used map with its byte and entry bounds, one job per miss, and the cached / read / joined labels.

  • Jobs. A miss starts a job that reads the artifact and keeps it. Simultaneous misses join that job. The job runs in the host's scope until it settles, even when every load waiting on it stops. A retry therefore joins it or finds what it kept, and never starts the read or compression again.
    • Each load decides cached, joined or started in one synchronous step, so there's no gap between a miss and its join.
    • A job's read is stopped after 30 seconds. Without that, a hung read would hold its identity forever: S3 reads have no request timeout of their own. Native compression can't be interrupted, so it finishes first, and a job past its deadline keeps nothing.
    • A job settles from its fiber's exit observer, which sees every exit. That covers a host scope closing before the job's fiber has run, which round 1's onExit missed (round 2).
  • Why not Effect Cache (round 1). This replaces the zero-lifetime Effect Cache from perf(patches): tier 2 calls reuse their server bundle instead of re-reading it #764. That Cache removes a lookup and interrupts it as soon as its last waiter leaves. A retry then started a second read, while the first one's native zlib work kept running.
  • Bundles. They share the change. An abandoned bundle read now finishes and is kept, and a hung one fails at 30 s. perf(patches): tier 2 calls reuse their server bundle instead of re-reading it #764's test for "a read with no one left waiting stops" is rewritten for that.
  • Dead code removed. perf(patches): tier 2 calls reuse their server bundle instead of re-reading it #764's "replaced bundle" test covered two lookups of one identity both keeping it, which can no longer happen. It now checks that the second load joins the first.
  • Where it's built. The document cache is built in Serving's route layer, not inside Content, because its compressed bodies come from compression.ts in Serving. Content.read still does the read.
  • Size check up front. The helper decides whether an artifact will be kept from its recorded size before reading it, and tells the read. A document too large to keep is then sent as stored instead of being compressed on every load.

Compression is bounded and never on the event loop. Synchronous brotli 9 plus gzip on these documents blocks for 25–31 ms (234 KB: 22 + 9 ms). compress now runs on libuv's threadpool; the event loop's longest gap during it was 2–4 ms in the same measurement.

  • One at a time (round 1). The host compresses one document at a time, with brotli then gzip on a single pool thread. That leaves the other three pool threads for file, crypto and DNS work. On a half-vCPU task, running the codings in parallel would finish no sooner.
  • The permit counts native work. Compression runs uninterruptibly inside the permit, so the permit is only released when zlib has finished, not when a waiting fiber stops.
  • Four documents at a time (round 2). A host reads and prepares at most four documents at a time, from the read through keeping them. Documents waiting their turn haven't been read, so they hold no bytes, and their wait counts against the job's deadline. Within those four, storage reads overlap and compression queues.
  • Measured: three different cold documents requested at once after a restart get their first byte at about 22, 35 and 46 ms (three runs).
  • A miss costs the storage read, a digest check, and both codings in turn.
  • A hit costs a map lookup, negotiate and the response headers.
  • The broker now uses the same async compress once at startup, and the synchronous precompress is gone, so compression.ts has one compressor and its header comment names both users.
  • I kept brotli 9. Quality 5 makes these documents 0.1–0.3% larger for about 55% of the CPU (New Business: 13 ms against 22 ms). It's the next lever if misses on the 0.5 vCPU hosts show up in traces.

Memory. I added two host-scoped operating limits, following #764's precedent:

  • serving.contentCache.bytes: 64 MiB, counting the raw, brotli and gzip bytes together.
  • serving.contentCache.entries: 256.

A typical 296 KB document holds about 550 KB with both codings, so a host keeps about 120 documents. A document whose stored size is over a quarter of the byte bound (16 MiB) is never kept or compressed. The largest scripted document a publish accepts is 10 MiB, so that only happens if the bound is tuned down.

Peak memory per host is 64 MiB of kept documents beside #764's 64 MiB of bundles, on a 2 GiB task. On top of that come the documents being prepared: at most four, each holding its decoded string (up to twice its size for non-Latin text), its bytes and its compressed outputs: four to five times its size. Worst case that's about 200 MiB with today's 10 MiB publish cap; with typical 300 KB documents it's about 6 MB.

Every other cold load waits without bytes. A document too large to keep goes through the same four places, then its body is held by the requests sending it, as on main. A compressed body under 16 KiB can keep zlib's 16 KiB output chunk alive, which is bounded by the entry count.

What's cached is the same for every viewer. The body is the stored bytes verbatim. The document nonce stays in the URL, and the server never reads it. Everything else is computed per request from the version row and the request, as before: the CSP from the tier only, Permissions-Policy, Cache-Control, cookies and the new Vary and Content-Encoding. No header depends on the body.

The key comes from the version row the door admitted, objectKey#contentHash, never from the URL. The object key contains the version id, so a viewer can only ever get bytes of a version they were just admitted to. There's no ETag or 304 path. Refusals return before the cache is touched, so they are never cached, compressed or varied.

Integrity. A miss checks the bytes against the version's recorded contentHash, as #764 does for bundles. A mismatch fails as StoredDocumentMismatch, a fault answered with a 500 like a missing object, and is never kept.

Scope. Only /~content. A tier 0 page embeds its HTML in the shell's srcdoc through Content.read and never fetches its content URL. Moving that page onto the cache would need extra code, so it isn't here. A tier 0 version's own content URL goes through the same route, so it is cached too.

Observability. A content request's wide event adds contentLoad (cached / read / joined) and contentEncoding (br / gzip / identity). responseBytes is now the compressed size. Both fields are in the analytics glossary and OPERATIONS' wide events section.

Tests

Pages.test.ts builds one host's routes over a store that counts document reads, with each request inside a request event:

  • Three loads read storage once: read then cached, in br, gzip and identity.

  • Two simultaneous loads share one read, labelled read and joined. A failed read and a digest mismatch are faults, and the next request reads again.

  • With the document kept, a signed-out reader gets 401, another company 404, a deactivated member 403, and an operator-disabled patch 404. None of these is compressed or varied, and the read count stays at 1.

  • Accept-Encoding picks br, gzip or identity, including weights, with Vary, and each body decodes to the stored bytes.

  • A document over a quarter of the byte bound is sent as stored and read on every load. The entry bound evicts the least recently used document.

  • Round 1:

    • Three different cold documents become ready to compress at the same moment, and only one compresses at a time. A watched compressor counts calls and the most running at once.
    • A load abandoned mid-compression, then retried at once, takes one read and one compression. The retry is joined and the next load cached.
    • Two documents that fit the byte bound by raw bytes, but not by everything they hold, evict the least recently used. Charging raw bytes alone fails this test.
    • Over a real socket, HEAD carries Content-Encoding: br, Vary and the brotli body's Content-Length, with no body.
    • I checked the tests by breaking the code on purpose: without the permit, with the job tied to its first waiter, or with raw bytes charged alone, the matching new test fails.
  • Round 2:

    • Six cold documents whose loads are all abandoned are read four at a time, and all six are still kept. That's six reads and six compressions in total, never two at once.
    • With the bound removed, the test fails (6 reads instead of 4).

Content.test.ts:

  • An abandoned bundle read finishes, and a retry joins it.
  • A read that never settles fails at 30 s and is read again.
  • Round 2: closing the host's scope before a job's fiber runs leaves no load waiting, and a later load starts afresh. Round 1's helper hangs on this test.

The existing UTF-8 and BOM test now records each rewritten document's digest, because stored bytes never change once published.

Round 2: pnpm check (5/5, 1,923 tests) and pnpm verify (9/9, including tier2-smoke, cli-smoke and browser) both passed in full.

Round 1: pnpm check passed format, lint, synth and all 1,890 tests. Typecheck failed on one type annotation in the new test helper; I fixed it, and pnpm typecheck then passed on its own. Outside Pages.ts, compression.ts, Content.ts and their tests, round 1 only changes the analytics glossary and comments, so I didn't run pnpm verify again.

pnpm verify (before round 1): 8 of 9 steps passed, including tier2-smoke, cli-smoke and browser. The test step had one failure, a 5 s timeout in packages/sdk/src/SdkApi.test.ts ("retains advertised archives after a same-version repack prunes local copies"), while the machine's load average was about 13. That file passed 3 of 3 runs alone, and the full suite passed in pnpm check an hour earlier. It packs and prunes SDK archives and touches nothing here.

Closes #746

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

Every scripted patch load read its document from object storage after
admission (p50 122 ms in production) and sent it uncompressed (296 KB for
a typical tier 2 patch).

Now the content route keeps admitted documents in memory, keyed by object
key and recorded digest, within new serving.contentCache.* limits, and
sends brotli or gzip by Accept-Encoding with Vary. Admission and every
refusal still run on every request. Compression runs on the threadpool, so
a miss never blocks the event loop. #764's bundle cache becomes the shared
Content.makeArtifactCache helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:l 501-1,000 changed lines labels Oct 18, 2026
allisonmahmood and others added 3 commits October 18, 2026 17:55
Review round 1 on #770: cold misses for different documents could start
brotli and gzip together with no host-wide limit, and a load whose waiter
stopped left native zlib running while a retry started the work again.

- The artifact cache's misses now run as jobs in the host's scope: a miss
  starts one, simultaneous misses and retries join it, and it finishes
  and keeps its result even when every waiter stops. A job not settled in
  30 seconds fails, so a hung read can't hold its identity. This replaces
  the zero-lifetime Effect Cache, which dropped and interrupted a lookup
  once its last waiter left.
- The host compresses one document at a time, codings one after another,
  holding the permit until zlib finishes. Reads stay concurrent.
- Tests: different cold documents compress one at a time; an abandoned
  load's retry does one read and one compression; kept documents are
  charged all three codings; HEAD carries the compressed length.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
allisonmahmood and others added 2 commits October 18, 2026 21:31
Review round 2 on #770.

- Documents waiting for the compression permit had already been read, so
  a burst of distinct cold documents could hold any number of them. A
  host now reads and prepares at most four documents at a time, from the
  read through keeping them; the rest wait without bytes, the wait
  counting against the job's deadline.
- A job forked into a host scope that closed before it ran never
  installed its onExit, stranding its loads and identity. Jobs now settle
  from their fiber's exit observer, which sees every exit.
- The helper's comment says the deadline stops the read, that native
  compression finishes first, and that a timed-out job keeps nothing.
- Tests: a burst of six abandoned cold loads prepares four at a time and
  still keeps all six; a host closing before its job runs leaves no load
  waiting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added size:xl Over 1,000 changed lines; review in multiple passes and removed size:l 501-1,000 changed lines labels Oct 18, 2026
@allisonmahmood
allisonmahmood merged commit d6f28e4 into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/746-content-cache branch October 18, 2026 21:50
allisonmahmood added a commit that referenced this pull request Oct 19, 2026
…ng Reconnecting (#783)

Release 14's What's new entry, written from \`7694bab\`. It covers
everything merged since release 13's \`through\` (\`c9b8fc4\`), and sets
the \`patchy\` release to \`0.14.0\` (\`packages/patchy/package.json\`
and \`CURRENT_RELEASE\`).

| Change | PRs |
| --- | --- |
| Improved: Tools with server code answer faster | #756, #764, #768,
#769, #771, #772, #773, #775, #778 |
| Improved: Your company's tools and pages open sooner | #759, #761,
#766, #770 |
| Fixed: Tools stop flashing Reconnecting while they load | #755, #776,
#780 |
| Improved: Publishing is quicker | #729 |
| Improved: New tools start with a tidy layout | #763 |
| Improved: Your usual is easier to scan | #721 |
| Fixed: A page that isn't there says what to do | #762 |
| Fixed: A logo Patchy can't read is refused, not a crash | #728 |
| Behind the scenes: richer logs for live data | #758 |

#720 is release 13's own entry, so it's left out.

Made by Claude Opus 5.5 via Claude Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:docs Touches the docs area area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Patch content is re-read from storage and sent uncompressed on every load

1 participant