Repository navigation
Compress realtime WebSocket pushes with permessage-deflate - #6209
Merged
ymichael merged 3 commits intoOct 27, 2026
Merged
Conversation
The server's WebSocketServer came from @hono/node-ws with ws defaults, which leave permessage-deflate off, so 100-450KB timeline pushes crossed remote tunnels as raw JSON. Enable deflate (level 1, 1KB threshold) on the client realtime socket only: terminal, daemon and plugin sockets decline the offer, and the bb connect tunnel's loopback relay stops offering it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
host-daemon's ambient ws module replaces @types/ws wherever its source is compiled, including tunnel-client's session and the integration-tests program that includes server source. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…periment The /ws upgrade reads the experiment and declines the client's permessage-deflate offer while it is off, so a toggle applies to the next connection. Off by default, on for early adopters. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/compress-realtime-websocket-messages-thr_y984k5x2cv
branch
from
October 27, 2026 16:54
9a045d4 to
7c15de1
Compare
ymichael
deleted the
bb/compress-realtime-websocket-messages-thr_y984k5x2cv
branch
October 27, 2026 17:04
ymichael
added a commit
that referenced
this pull request
Nov 20, 2026
…7881) ## Human comments ## What was wrong `/internal/ws` (host daemons) and `/ws/terminals/:id` always declined `permessage-deflate` (`declineWebSocketCompression`). #6209 compressed only the browser `/ws`. So terminal output (base64 inside JSON, 1.4× the decoded bytes) and daemon RPC traffic crossed LAN, Tailscale and other direct routes at full size. On a 3.6 MB/s link a text-heavy terminal topped out at ~2.4 MB/s and buried replies behind it. Measured in the #6748 transport report: level-1 deflate brings terminal text to ~33% of its wire bytes. ## What changed - **Server** (`apps/server/src/ws/compression.ts`, `server.ts`): - Terminal and daemon sockets reuse #6209's mechanism: level 1, 1 KB threshold. - They decline compression only when the peer is on this machine: a loopback address with no `X-Forwarded-For`/`Forwarded` header (`declineSameMachineWebSocketCompression`). Requests forwarded by a local proxy such as Tailscale Serve count as remote. - `DaemonChannel` and the terminal send path now pass `compress: true`. hono's ws adapter otherwise sends uncompressed even when compression was negotiated. - **Daemon** (`apps/host-daemon/src/websocket-constructor.ts`, `server-connection*.ts`): - Daemons offer level-1 compression above 1 KB, like the server. - `host.read_file_chunk` replies go out uncompressed through a new `sendUncompressed`. partysocket's `send` drops ws options, so this writes to the underlying ws directly. - Deflating file bytes made fast-link downloads 4× slower (~120 → ~31 MB/s on the first build of this PR) and saved little on media. - **Protocol bump to 274.** Compression is negotiated per connection by the WebSocket handshake, and shipped daemons already offer `permessage-deflate` (the `ws` default) and handle it. But with `ws` defaults they compress every frame at level 6, file chunks included: against this server, 30 MB downloads through a pre-PR daemon on an unconstrained link ran at ~31 MB/s (random) / ~40 MB/s (text) instead of ~120 MB/s. The bump makes enrolled daemons update to the level-1 sender that leaves file chunks uncompressed. - Older servers keep declining. - **Docs:** the compression paragraph in `docs/configuration.md`. - **Not covered: bb connect.** The connect relay re-frames WebSocket messages; its tunnel client opens the origin socket with `perMessageDeflate: false`. Event POST bodies (HTTP) are also unchanged. ## How you verified **Numbers.** I used the #6748 harness on one M4 Mac, with an origin/main `base` stack and this branch. Each isolated `start:worktree` server was bound to `0.0.0.0`. Each client daemon reached its server through the shaping proxy at the machine's LAN address (non-loopback, so compression applies). Runs were interleaved base/branch with the order alternating per round. - Cells are median/p95 in ms; "·" separates the two rounds. - Text flood = `find apps/server/src -name '*.ts' | head -400 | xargs cat` in a loop. - The measuring client (the browser's role) talked to the server over loopback, so these rows compress only the daemon leg. | route | metric | origin/main | this PR | |---|---|---|---| | relay 45 ms / 3.6 MB/s | text flood MB/s | 1.99 · 2.41 | **7.80 · 7.81** | | | RPC during text flood | 211/344 · 226/373 (n=83, 62) | **101/378 · 109/120** (n=113, 126) | | | file download MB/s | 2.19 · 2.14 | 2.13 · 2.14 | | | idle RPC / echo (n=100) | 51/55 · 51/52 / 50/54 · 49/50 | 51/57 · 51/52 / 51/64 · 49/50 | | far relay 120 ms / 3.6 MB/s | text flood MB/s | 2.39 · 2.40 | **4.33 · 4.35** | | | RPC during text flood | 247/379 · 247/374 (n=58, 58) | **125/191 · 125/186** (n=106, 107) | | LAN emulation 3 ms / 25 MB/s | text flood MB/s | 16.69 · 16.78 | **47.94 · 46.65** | | | RPC during text flood | 41/50 · 41/51 (n=219, 218) | **16/21 · 15/19** (n=304, 308) | | | file download MB/s | 13.40 · 13.22 | 13.35 · 13.21 | | unshaped LAN address | file download MB/s | 129.0 · 123.7 | 121.3 · 127.8 | | | text flood MB/s | 47.4 · 49.2 | 45.1 · 49.0 | | | RPC during text flood | 4.7/6.6 · 4.4/6.2 (n=366, 368) | 14/19 · 15/19 (n=312, 307) | Wire bytes on the daemon leg for the same text flood (proxy tally): 1.42 bytes per decoded terminal byte on main vs 0.44 here (3.2× fewer). **Cost.** - **Latency on an unconstrained fast link.** During a sustained ~50 MB/s text flood, a reply on the same socket waits ~15 ms instead of ~5 ms. Deflate and inflate run in order per socket, and main lets up to 1 MiB of terminal output queue ahead of a reply. With #7874 applied (local merge, same runs), that goes to ~11.5 ms. The relay text flood keeps 7.7 MB/s, and replies during it take 58/66 ms instead of 209/363 ms. - **CPU.** 16 concurrent text-flooding terminals, browser client and daemon both on the LAN address (so the browser terminal sockets are compressed too), 20 s per run: | link | | origin/main | this PR | |---|---|---|---| | unshaped | terminal output | 65.7 · 61.8 MB/s | 49.7 · 49.4 MB/s | | | server CPU | 104% · 103%; 16 · 17 ms per MB | 152% · 151%; 30 · 31 ms per MB | | | daemon CPU | 96% · 93%; 15 · 15 ms per MB | 130% · 130%; 26 · 26 ms per MB | | 25 MB/s | terminal output | 17.2 · 17.2 MB/s | **49.2 · 49.4 MB/s** | | | server CPU | 33% · 31%; 19 · 18 ms per MB | 151% · 151%; 31 · 31 ms per MB | - Compression roughly doubles server CPU per terminal megabyte (~16 → ~31 ms/MB, about 1.5 cores at 16 saturated terminals). - On a link that is not the bottleneck it lowers peak aggregate terminal throughput by ~22%. On a 25 MB/s link it delivers 2.9× the output. - Same-machine sockets are unaffected. **Tests:** - `websocket-compression.test.ts`: a forwarded or remote peer gets compressed daemon and terminal sockets. A 400-entry daemon message crosses in < 1/4 of its bytes; this fails without the `compress: true` send flag. Loopback peers still decline. The same-machine rule is covered for IPv4, IPv6, IPv4-mapped and forwarded cases. - `server-connection-support.test.ts`: against a real compressing `ws` server, a normal send compresses (< 1/4) and `sendUncompressed` does not. - `server-connection.test.ts`: `host.read_file_chunk` replies take the uncompressed path; other replies do not. **Commands:** - `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`: 11/11. - `pnpm exec turbo run test --filter=@bb/server --filter=@bb/host-daemon`: server 4344 passed, host-daemon 885 passed. These ran before the uncompressed-chunk change; I reran the affected daemon files after it (`server-connection*.test.ts`, `websocket-constructor.test.ts`, `app.test.ts`). **Live check.** I used an isolated instance with a second daemon on the LAN address behind the 45 ms / 3.6 MB/s shaper, and the app loaded from the LAN address in a browser: - A Claude Code turn with an uploaded attachment returned its token and ran a command in the client host's workspace. - A file preview opened. - A terminal printed `bb6748-42`, `19999`, `20000` for `echo bb6748-$((6*7)) && seq 1 20000 | tail -2`. **Interaction with #7874.** The two PRs merge with conflicts in the daemon send path; they are independent but touch the same lines. Whichever lands second should keep #7874's binary chunk frames out of compression. In the local merge I measured, the rule "compress text frames only" in the ws `send` override replaces `sendUncompressed`. Refs #6748 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
createNodeWebSocketfrom@hono/node-wscreates itsWebSocketServerwithwsdefaults, which leaveperMessageDeflateoff. It takes no options to change that. Every realtime push went out as raw JSON, including timeline windows of 100–450KB, and remote clients on bb connect next paid the full size. On top of that, hono'sWSContext.sendcallsws.send(data, { compress: opts?.compress }). That explicitundefinedoverrides ws'scompress: truedefault, so even a negotiated connection would not compress unless the caller asks.What changed
Behind the
websocketCompressionexperiment. It is off indefaultExperimentsand on inearlyAdopterExperiments, liketimelinePush, and appears in Settings → Experiments as "Compressed live updates". You can also toggle it withbb settings experiment websocketCompression <true|false>.On each
/wsupgrade the server readsgetExperiments(deps.db). While the experiment is off, it callsdeclineWebSocketCompression(context), so the connection negotiates no extension and behaves exactly like main.The setting is read when the socket connects, so a toggle takes effect on the next connection (when the app reconnects). Sockets that are already open keep what they negotiated.
Terminal, daemon and plugin sockets never compress, whatever the setting. The bb connect loopback relay's
perMessageDeflate: falseapplies unconditionally.Documented in
docs/configuration.md(Experiments) and inbb guide customization. The app's fallback config (system-config-atoms.ts) includes the new key.apps/server/src/ws/compression.ts(new): the deflate settings (threshold: 1024,zlibDeflateOptions.level: Z_BEST_SPEED), theCOMPRESSED_SENDsend option, anddeclineWebSocketCompression(context). That function removes the client'sSec-WebSocket-Extensionsoffer beforewsrunshandleUpgrade.apps/server/src/server.ts: setswss.options.perMessageDeflateon the shared server, and/wsdeclines it while the experiment is off.wsreads this option at each upgrade. The terminal (/ws/terminals/:id) and daemon (/internal/ws) routes decline compression. Plugin WebSocket routes decline it too (routes/plugins.ts). Only/wsnegotiates.wsclient would start deflating every daemon message, which changes CPU on both sides. That is a separate decision.apps/server/src/ws/hub.ts: the three client fan-out paths send with{ compress: true }. They are broadcast, thread-list-only, and keyedchanged/thread-timeline/ plugin-signal pushes. Frames under 1KB stay uncompressed because of the threshold, so pongs and smallchangedmessages are untouched. Terminal and daemon sends are unchanged.packages/tunnel-client/src/session.ts: the bb connect tunnel's loopback relay to the server now passesperMessageDeflate: false. Otherwisews's default offer would make the server deflate onto loopback and the daemon inflate it again before re-framing into the tunnel, which is pure CPU loss.Settings rationale:
ws'sserverNoContextTakeoveronlyreset()s the zlib stream and never frees it, so turning takeover off saves no memory and costs ratio.concurrencyLimitleft at ws's default of 10: it is a module-wide zlib limiter. Deflate runs on the libuv threadpool, not the event loop.No
HOST_DAEMON_PROTOCOL_VERSIONbump: no server/daemon wire field changed, and the daemon socket keeps negotiating no extension.Tunnels:
Sec-WebSocket-Extensionsboth ways and pipes the upgraded socket raw through frps → frpc → the server's tunnel ingress relay, which copies the header into the upgrade. The tests below cover this.WebSocketPair, stripssec-websocket-extensions(HOP_HEADERS), and re-frames data over the tunnel. Getting compression there would mean negotiating on the DO legs inapps/connect, which is out of scope here.How you verified
Real 457KB timeline (
GET /threads/thr_epab8x343w/timeline) pushed throughhubto a realwsclient on a test server, counting socket bytes:Tests:
apps/server/test/app/websocket-compression.test.ts(new):/wsthen negotiates no extension. Turning it on throughPUT /settings/experimentsmakes the next connection negotiate deflate. Turning it off again makes the next connection plain. Sockets already open keep their extension. This test fails with the gate removed./wsnegotiatespermessage-deflate. A large push arrives at under a quarter of its size on the wire. A pong arrives as an uncompressed 17-byte frame./internal/ws) get no extension.apps/server/test/connect-next/tunnel-ingress.test.ts:/wsthrough the ingress relay negotiates deflate, and plugin sockets do not./wsthrough frp and asserts deflate.apps/connect-next/test/gate.e2e.test.ts: the harness origin offers deflate. A new test asserts negotiation through the gate's raw pipe and a compressed echo ofBIG_JSON.packages/tunnel-client/test/origin-websocket.test.ts(new): the loopback relay sends noSec-WebSocket-Extensionsto a deflate-capable origin. It fails withoutperMessageDeflate: false.apps/server/test/connect-next/tunnel-ingress.test.tsandtest/system/experiments.test.tsturn the experiment on where they expect deflate, and they cover the new key.pnpm exec turbo run typecheck lintover every affected package passed (153 tasks).turbo run testpassed for@bb/app(6434),@bb/db(633),@bb/domain(259),@bb/templates(46) and@bb/tunnel-client(27).@bb/serverpassed 3686 of 3688. The two failures were builtin-plugin build tests inbuiltin-plugins.test.tsthat hit 21–40s timeouts while the app suite ran alongside; that file passed 28/28 when re-run alone.🤖 Generated with Claude Code