Skip to content

bb Connect tunnel deflates response bodies that the server already compressed #8222

Description

@lanjak

Summary

The bb Connect tunnel client sends each HTTP response body chunk with permessage-deflate when the gate negotiates the extension. The bb server already compresses its compressible responses with brotli or gzip before they enter the tunnel. The second compression gives no size gain and costs host CPU: for an 8 MB brotli body, the tunnel client used 229-280 ms of CPU, and the wire was 3.6 KB larger than without deflate.

Versions and environment

  • bb at origin/main 2a21dd5, from source.
  • Linux (CachyOS, kernel 7.3.4), Node v26.13.1, ws 8.22.1.
  • No live host or gate was used. The repro runs the real TunnelSession against a local ws server with perMessageDeflate: true in the role of the gate. Local workerd also negotiates permessage-deflate on a Durable Object WebSocketPair when the client offers it (scout measurement, miniflare 4.20260730). Negotiation on production Cloudflare is inferred, not observed.

Steps to reproduce

  1. Start an origin HTTP server that returns 8 MB of incompressible bytes with content-encoding: br (the shape of a brotli API response).
  2. Start a ws WebSocketServer with perMessageDeflate: true as the gate. Count the bytes on its TCP socket.
  3. Connect a ws client with default options, as plugins/connect/src/tunnel.ts does, and start a TunnelSession on it that resolves to the origin.
  4. From the gate, send an open-http frame. Measure process.cpuUsage() in the client process until the gate receives body-end.

A shorter repro is the test packages/tunnel-client/test/tunnel-compression.test.ts in the fix branch: a 1 MB body with content-encoding: br crosses the wire as 1727 bytes, which shows that the client deflated it.

Expected vs actual

Expected: a body that already has a Content-Encoding goes through the tunnel without a second compression, so the client CPU is near the cost of the copy.

Actual (7 runs, 8 MB brotli body, 64 KB origin chunks):

run 0: client cpu 263.5 ms, wall 226.6 ms, wire 8395895 bytes for 8388608 body bytes
run 1: client cpu 280.1 ms, wall 205.3 ms, wire 8395582 bytes for 8388608 body bytes
run 2: client cpu 258.4 ms, wall 192.6 ms, wire 8395583 bytes for 8388608 body bytes
run 3: client cpu 238.6 ms, wall 175.9 ms, wire 8395583 bytes for 8388608 body bytes
run 4: client cpu 229.4 ms, wall 200.0 ms, wire 8395583 bytes for 8388608 body bytes
run 5: client cpu 275.5 ms, wall 226.4 ms, wire 8395583 bytes for 8388608 body bytes
run 6: client cpu 237.6 ms, wall 206.6 ms, wire 8395583 bytes for 8388608 body bytes

With compress: false on the body frames, the same transfer used 8-49 ms of client CPU and 8391961 wire bytes.

Evidence

  • The tunnel socket uses the ws defaults, which offer permessage-deflate:
    tunnel = new NodeWebSocket(tunnelUrl, {
    headers: { authorization: `Bearer ${credential}` },
    handshakeTimeout: TUNNEL_HANDSHAKE_TIMEOUT_MS,
    createConnection: tunnelUrl.startsWith("wss:")
    ? timedTlsConnection(dialStartedAt, diagnostics)
    : undefined,
    });
  • sendRaw calls tunnel.send(data) with no options, so ws uses compress: true for every frame:
    private send(frame: Frame): void {
    if (this.options.tunnel.readyState === NodeWebSocket.OPEN) {
    const encoded = encodeFrame(frame);
    this.sendRaw(encoded, encoded.byteLength);
    }
    }
    private async waitForSendBuffer(signal: AbortSignal): Promise<void> {
    const { tunnel } = this.options;
    while (
    !signal.aborted &&
    tunnel.readyState === NodeWebSocket.OPEN &&
    tunnel.bufferedAmount > SEND_BUFFER_HIGH_WATER_BYTES
    ) {
    await new Promise((resolve) => setTimeout(resolve, SEND_BUFFER_POLL_MS));
    }
    }
    private sendRaw(data: string | Uint8Array, byteLength: number): void {
    this.options.tunnel.send(data);
    this.bytesSent += byteLength;
    this.lastSentAt = Date.now();
    }
  • Each origin response chunk becomes a body-chunk frame through that path:
    for await (const chunk of res) {
    const value =
    chunk instanceof Uint8Array ? chunk : Buffer.from(String(chunk));
    responseBytes += value.byteLength;
    for (const frame of chunkBody(streamId, value)) this.send(frame);
    await this.waitForSendBuffer(stream.abort.signal);
    }
  • The server compresses API JSON with brotli or gzip and other responses with hono compress():
    if (contentEncoding !== null) {
    headers.set("content-encoding", contentEncoding);
    }
    }
    export function apiJsonCompression(): MiddlewareHandler {
    return async (context: Context, next: Next) => {
    await next();
    if (!isBufferedApiJsonResponse(context)) {
    return;
    }
    await compressBufferedApiJsonResponse(context);
    };
    and
    const compressResponse = compress();
    const compressApiJson = apiJsonCompression();
    app.use("*", (context, next) => {
    if (PLUGIN_APP_ASSET_PATH_PATTERN.test(context.req.path)) {
    return next();
    }
    return compressResponse(context, async () => {
    await compressApiJson(context, next);
    });
  • Compress realtime WebSocket pushes with permessage-deflate #6209 (afc377a) set perMessageDeflate: false on the loopback relay for the same reason (no gain from a second compression step):
    socket = new NodeWebSocket(`${wsOrigin}${frame.path}`, frame.protocols, {
    headers,
    perMessageDeflate: false,
    });
  • Measurement method: a script runs the gate and the origin in a child process, so the parent process CPU is only the TunnelSession (HTTP client, frame encoding, ws sender). The gate counts bytes on its TCP socket.

What you ruled out

  • Size gain: deflate made the 8 MB brotli body 3.6 KB larger on the wire, not smaller.
  • Realtime frames: ws-data frames carry raw JSON from the loopback relay. Deflate reduces them about 4x, so they must keep compression.
  • Bodies without Content-Encoding (for example a shared dev server port): deflate reduces text bodies about 11x (8 MB to about 750 KB), so they must keep compression too.
  • The gate to tunnel direction (uploads that the Durable Object deflates) is a separate trade-off. Turning it off needs perMessageDeflate: false on the tunnel, which also stops compression of realtime pushes.

AGENT GENERATED

Activity

  1. added theissue type on Nov 26, 2026
  2. added
    remote
    connect
    confirmed-repro
    on Nov 26, 2026
  3. bb-slop-cop commented on Nov 26, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority: Medium · Effort: Low. Applied remote, connect, and perf; no existing values were replaced.
    • Report: https://get-bb.github.io/reports/issues/8222.html — REPRODUCED, root-cause confidence high. Applied confirmed-repro.
    • Root cause: TunnelSession sends already-encoded HTTP body frames without overriding the WebSocket sender's default compression when deflate is negotiated.
    • Evidence: A newly authored real-wire test using valid brotli/gzip bodies fails as expected in two clean trusted-main checkouts: 4/4 body messages are compressed again. Body integrity and the unencoded control pass; all 27 existing tunnel-client tests pass. Production negotiation and the reported CPU figures remain unverified.
    • No new PR: existing open PR Send already-encoded tunnel response bodies without permessage-deflate #8223 already links this issue; another would duplicate that work.
  4. added a commit that references this issue on Nov 30, 2026
    b9b63e3
  5. added a commit that references this issue on Dec 1, 2026
    67110f2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reproconnectperfremote

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions