Skip to content

Compress realtime WebSocket pushes with permessage-deflate - #6209

Merged
ymichael merged 3 commits into
mainfrom
bb/compress-realtime-websocket-messages-thr_y984k5x2cv
Oct 27, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/compress-realtime-websocket-messages-thr_y984k5x2cv

Conversation

@ymichael

@ymichael ymichael commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

createNodeWebSocket from @hono/node-ws creates its WebSocketServer with ws defaults, which leave perMessageDeflate off. 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's WSContext.send calls ws.send(data, { compress: opts?.compress }). That explicit undefined overrides ws's compress: true default, so even a negotiated connection would not compress unless the caller asks.

What changed

Behind the websocketCompression experiment. It is off in defaultExperiments and on in earlyAdopterExperiments, like timelinePush, and appears in Settings → Experiments as "Compressed live updates". You can also toggle it with bb settings experiment websocketCompression <true|false>.

  • On each /ws upgrade the server reads getExperiments(deps.db). While the experiment is off, it calls declineWebSocketCompression(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: false applies unconditionally.

  • Documented in docs/configuration.md (Experiments) and in bb 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), the COMPRESSED_SEND send option, and declineWebSocketCompression(context). That function removes the client's Sec-WebSocket-Extensions offer before ws runs handleUpgrade.

  • apps/server/src/server.ts: sets wss.options.perMessageDeflate on the shared server, and /ws declines it while the experiment is off. ws reads 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 /ws negotiates.

    • Terminal: output is latency-sensitive.
    • Daemon: the ws client would start deflating every daemon message, which changes CPU on both sides. That is a separate decision.
    • Plugins: unknown payloads.
  • apps/server/src/ws/hub.ts: the three client fan-out paths send with { compress: true }. They are broadcast, thread-list-only, and keyed changed / thread-timeline / plugin-signal pushes. Frames under 1KB stay uncompressed because of the threshold, so pongs and small changed messages 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 passes perMessageDeflate: false. Otherwise ws'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:

  • Level 1: on a real 457KB timeline, level 1 gives 3.8x in 1.8ms and level 6 gives 4.4x in 4.2ms.
  • Context takeover kept: ws's serverNoContextTakeover only reset()s the zlib stream and never frees it, so turning takeover off saves no memory and costs ratio.
  • concurrencyLimit left 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_VERSION bump: no server/daemon wire field changed, and the daemon socket keeps negotiating no extension.

Tunnels:

  • bb connect next: compression negotiates end to end. The gate forwards Sec-WebSocket-Extensions both 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.
  • bb connect (Cloudflare): compression does not reach the visitor through this change. The Durable Object ends the visitor socket in a WebSocketPair, strips sec-websocket-extensions (HOP_HEADERS), and re-frames data over the tunnel. Getting compression there would mean negotiating on the DO legs in apps/connect, which is out of scope here.

How you verified

Real 457KB timeline (GET /threads/thr_epab8x343w/timeline) pushed through hub to a real ws client on a test server, counting socket bytes:

timeline client offers deflate message wire bytes push→receive (loopback)
457KB no 456,764 456,774 1.1–1.6ms
457KB yes 456,764 119,052 4.1–4.4ms
166KB no 166,466 166,476 0.5ms
166KB yes 166,466 42,503 1.6ms

Tests:

  • apps/server/test/app/websocket-compression.test.ts (new):
    • The experiment is off by default, and /ws then negotiates no extension. Turning it on through PUT /settings/experiments makes 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.
    • With the experiment on, /ws negotiates permessage-deflate. A large push arrives at under a quarter of its size on the wire. A pong arrives as an uncompressed 17-byte frame.
    • With the experiment on, terminal and daemon sockets (a real session open plus an authenticated /internal/ws) get no extension.
    • Fails before the change. Disabling either the server option or the decline call fails its half.
  • apps/server/test/connect-next/tunnel-ingress.test.ts:
    • /ws through the ingress relay negotiates deflate, and plugin sockets do not.
    • The real frps + connect-next frpc test now also opens /ws through 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 of BIG_JSON.
  • packages/tunnel-client/test/origin-websocket.test.ts (new): the loopback relay sends no Sec-WebSocket-Extensions to a deflate-capable origin. It fails without perMessageDeflate: false.
  • apps/server/test/connect-next/tunnel-ingress.test.ts and test/system/experiments.test.ts turn the experiment on where they expect deflate, and they cover the new key.
  • After merging origin/main:
    • pnpm exec turbo run typecheck lint over every affected package passed (153 tasks).
    • turbo run test passed for @bb/app (6434), @bb/db (633), @bb/domain (259), @bb/templates (46) and @bb/tunnel-client (27).
    • @bb/server passed 3686 of 3688. The two failures were builtin-plugin build tests in builtin-plugins.test.ts that hit 21–40s timeouts while the app suite ran alongside; that file passed 28/28 when re-run alone.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 3 commits October 27, 2026 09:52
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
ymichael force-pushed the bb/compress-realtime-websocket-messages-thr_y984k5x2cv branch from 9a045d4 to 7c15de1 Compare October 27, 2026 16:54
@ymichael
ymichael merged commit afc377a into main Oct 27, 2026
93 of 95 checks passed
@ymichael
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]>
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