fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41) #147

Merged
chrnx merged 1 commits from feature/fprd-001c-ws-backpressure into develop 2026-10-23 06:22:20 +00:00
Owner

Card CARD-26 (FPRD-001c), decision D23, GitHub issue #41.

Depends on #142 (CARD-24). Review and merge after it. This branch is stacked on feature/fprd-001c-ws-mesh-body, and its diff against develop includes #142's four commits until that merges.

What changed and why

The outbound pump (pumpOutbound, src/http/ws-core.ts) pulled a @Ws handler's async iterator as fast as it yielded, regardless of what the peer read. With a slow client, every frame on offer was pulled into the send buffer at once (T1: 10,000 × 64 KiB = 640 MiB).

  • The pump now awaits socket.drained() before each pull (rule 1), so the buffer peaks at the high-water mark plus one frame.
  • WS_HIGH_WATER_MARK = 1 MiB is an internal constant, not an option (rule 3). A close ends the wait. The pump then stops without pulling, and the existing abort path calls the iterator's return() (T2).
  • Adapters (rule 2):
    • Node (ws): bufferedAmount, with waiters released by each send's write callback or by the close.
    • Bun: getBufferedAmount(), with waiters released by the server-level drain callback, the close, or an error. Bun has no bufferedAmount property.
    • Deno: polls bufferedAmount every 10 ms, only while over the mark (the Web WebSocket has no drain event). The close aborts the wait at once.
    • Edge (workerd): probed under miniflare, and the server WebSocket has no bufferedAmount ('bufferedAmount' in server === false). There is no signal, so the pump never waits on the edge. This is documented in the CHANGELOG, as the card allows.

Found along the way: a Deno bug in the same pump

Deno hands the socket over while still CONNECTING. A handler that yielded at once had its first value pulled, isOpen was false, and the pump gave up: the client got no frame and a 1005 close. This is reproduced on develop by test/deno/ws-backpressure.test.ts, "a ws route that yields at once". Under rule 1 a CONNECTING socket is not writable, so the Deno drained() also waits while connecting. This also explains the unexplained 1005 I noted in #142.

The WsSocket addition (rule 4, before CARD-22 freezes it)

Chosen: one optional member, drained?(): Promise<void>. The card proposed readonly bufferedAmount: number + drained(): Promise<void>. I dropped bufferedAmount because the pump only needs "wait until writable". The level and the mark stay inside each adapter, so the frozen type carries no number whose meaning varies by runtime.

Optional, not required. Owner decision 2026-10-23: drained?() stays optional. A WsSocket built by hand (a custom adapter calling app.upgrade, or test fakes) keeps compiling and behaves as before, never waiting. Record it as optional in CARD-22's API report.

Alternatives I considered and did not take:

  • Zero new members: widen send() to return void | Promise<void> when backed up. This was rejected because every other caller of send (teapot, link) would start drain waits nobody awaits, and on Deno those are timers.
  • drained(): Promise<void> | undefined, to skip one microtask per frame. This was rejected in favour of a clean signature for a frozen type. T3 shows the pump never waits below the mark: each frame asks once, and the answer is already resolved.

For CARD-22's API report:

  • WsSocket.drained?(): Promise<void> is added.
  • WS_HIGH_WATER_MARK is exported from src/http/ws-core.ts (internal module) but not from the package index.
  • EventfulSocket (internal) gains optional bufferedAmount.

Tests (T1–T3)

# Where Evidence
T1 test/ws-backpressure.test.ts (Node), test/deno/ws-backpressure.test.ts, test/bun/ws-backpressure.test.ts 10,000 × 64 KiB frames to a client that pauses its TCP socket. Pulling stops (unchanged over 200 ms) at fewer than 1,000 frames: the 1 MiB mark plus kernel socket buffers. After resume, all 10,000 arrive in order. Before the fix all 10,000 are pulled at once (verified red on Node and Bun; on Deno the old pump hit the bug above).
T1 (exact bound) test/ws-core.test.ts A fake socket shows the buffer peaks at mark + one frame, and frames are delivered in order.
T2 the same three integration files, plus a unit test The client goes away mid-wait. The iterator's finally/return() runs, nothing more is pulled, and there is no unhandled rejection.
T3 test/ws-core.test.ts Below the mark drained() answers at once and every frame goes out. The existing ws suites on every runtime and the edge are unchanged.

The Deno and Bun twins use a raw node:net WebSocket client (test/helpers/raw-ws.ts) because the platform WebSocket cannot stop reading.

Results (base: #142 at bd85bf6, including the #148 and review-P1 commits, on develop @ e565b1d)

  • npm run lint: 0 errors, 51 warnings (all pre-existing no-explicit-any plus #142's one)
  • npm run format:check: clean
  • npm run typecheck: clean
  • npm test: 95 files, 932 tests passed
  • npm run build: ok
  • npm run complexity:check: every function ≤ 25
  • npm run test:deno: 48 passed, 0 failed
  • npm run test:bun: 37 pass, 0 fail
  • npm run test:edge: PASS

Unsure

  • The integration T1 pushes 640 MiB over loopback per runtime: about 1 s on Node and about 7 s on Deno (the node:net client there is slow). If that is too heavy for CI, the frame count can drop without losing the assertion.
  • Node relies on ws running the send callback once the frame is written to the socket. A frame sent without a callback (ping/pong/close) does not release waiters, but those also never hold the buffer over 1 MiB.

Docs follow-up (CARD-12)

  • WebSocket guide: outbound streams are backpressured (1 MiB internal mark). A slow client slows the producer instead of growing memory. On the edge there is no signal, so it is not backpressured.
  • Adapter / app.upgrade reference: document WsSocket.drained?() for custom adapters.

The CHANGELOG has entries under ### Fixed (backpressure, Deno early-yield) and ### Added (WsSocket.drained()).

Card **CARD-26** (FPRD-001c), decision **D23**, GitHub issue #41. **Depends on #142 (CARD-24). Review and merge after it.** This branch is stacked on `feature/fprd-001c-ws-mesh-body`, and its diff against develop includes #142's four commits until that merges. ## What changed and why The outbound pump (`pumpOutbound`, `src/http/ws-core.ts`) pulled a `@Ws` handler's async iterator as fast as it yielded, regardless of what the peer read. With a slow client, every frame on offer was pulled into the send buffer at once (T1: 10,000 × 64 KiB = 640 MiB). - The pump now awaits `socket.drained()` **before each pull** (rule 1), so the buffer peaks at the high-water mark plus one frame. - `WS_HIGH_WATER_MARK = 1 MiB` is an internal constant, not an option (rule 3). A close ends the wait. The pump then stops without pulling, and the existing abort path calls the iterator's `return()` (T2). - Adapters (rule 2): - **Node** (`ws`): `bufferedAmount`, with waiters released by each `send`'s write callback or by the close. - **Bun**: `getBufferedAmount()`, with waiters released by the server-level `drain` callback, the close, or an error. Bun has no `bufferedAmount` property. - **Deno**: polls `bufferedAmount` every 10 ms, **only while over the mark** (the Web `WebSocket` has no drain event). The close aborts the wait at once. - **Edge (workerd)**: probed under miniflare, and the server `WebSocket` has **no `bufferedAmount`** (`'bufferedAmount' in server === false`). There is no signal, so the pump never waits on the edge. This is documented in the CHANGELOG, as the card allows. ### Found along the way: a Deno bug in the same pump Deno hands the socket over while still `CONNECTING`. A handler that yielded at once had its first value pulled, `isOpen` was false, and the pump gave up: the client got no frame and a `1005` close. This is reproduced on develop by `test/deno/ws-backpressure.test.ts`, "a ws route that yields at once". Under rule 1 a `CONNECTING` socket is not writable, so the Deno `drained()` also waits while connecting. This also explains the unexplained `1005` I noted in #142. ## The `WsSocket` addition (rule 4, before CARD-22 freezes it) **Chosen: one optional member, `drained?(): Promise<void>`.** The card proposed `readonly bufferedAmount: number` + `drained(): Promise<void>`. I dropped `bufferedAmount` because the pump only needs "wait until writable". The level and the mark stay inside each adapter, so the frozen type carries no number whose meaning varies by runtime. **Optional, not required. Owner decision 2026-10-23: `drained?()` stays optional.** A `WsSocket` built by hand (a custom adapter calling `app.upgrade`, or test fakes) keeps compiling and behaves as before, never waiting. Record it as optional in CARD-22's API report. Alternatives I considered and did not take: - **Zero new members:** widen `send()` to return `void | Promise<void>` when backed up. This was rejected because every other caller of `send` (teapot, link) would start drain waits nobody awaits, and on Deno those are timers. - `drained(): Promise<void> | undefined`, to skip one microtask per frame. This was rejected in favour of a clean signature for a frozen type. T3 shows the pump never *waits* below the mark: each frame asks once, and the answer is already resolved. For CARD-22's API report: - `WsSocket.drained?(): Promise<void>` is added. - `WS_HIGH_WATER_MARK` is exported from `src/http/ws-core.ts` (internal module) but **not** from the package index. - `EventfulSocket` (internal) gains optional `bufferedAmount`. ## Tests (T1–T3) | # | Where | Evidence | |---|---|---| | T1 | `test/ws-backpressure.test.ts` (Node), `test/deno/ws-backpressure.test.ts`, `test/bun/ws-backpressure.test.ts` | 10,000 × 64 KiB frames to a client that pauses its TCP socket. Pulling stops (unchanged over 200 ms) at fewer than 1,000 frames: the 1 MiB mark plus kernel socket buffers. After resume, all 10,000 arrive in order. Before the fix all 10,000 are pulled at once (verified red on Node and Bun; on Deno the old pump hit the bug above). | | T1 (exact bound) | `test/ws-core.test.ts` | A fake socket shows the buffer peaks at mark + one frame, and frames are delivered in order. | | T2 | the same three integration files, plus a unit test | The client goes away mid-wait. The iterator's `finally`/`return()` runs, nothing more is pulled, and there is no unhandled rejection. | | T3 | `test/ws-core.test.ts` | Below the mark `drained()` answers at once and every frame goes out. The existing ws suites on every runtime and the edge are unchanged. | The Deno and Bun twins use a raw `node:net` WebSocket client (`test/helpers/raw-ws.ts`) because the platform `WebSocket` cannot stop reading. ## Results (base: #142 at bd85bf6, including the #148 and review-P1 commits, on develop @ e565b1d) - `npm run lint`: 0 errors, 51 warnings (all pre-existing `no-explicit-any` plus #142's one) - `npm run format:check`: clean - `npm run typecheck`: clean - `npm test`: 95 files, 932 tests passed - `npm run build`: ok - `npm run complexity:check`: every function ≤ 25 - `npm run test:deno`: 48 passed, 0 failed - `npm run test:bun`: 37 pass, 0 fail - `npm run test:edge`: PASS ## Unsure - The integration T1 pushes 640 MiB over loopback per runtime: about 1 s on Node and about 7 s on Deno (the `node:net` client there is slow). If that is too heavy for CI, the frame count can drop without losing the assertion. - Node relies on `ws` running the send callback once the frame is written to the socket. A frame sent without a callback (ping/pong/close) does not release waiters, but those also never hold the buffer over 1 MiB. ## Docs follow-up (CARD-12) - WebSocket guide: outbound streams are backpressured (1 MiB internal mark). A slow client slows the producer instead of growing memory. On the edge there is no signal, so it is not backpressured. - Adapter / `app.upgrade` reference: document `WsSocket.drained?()` for custom adapters. The CHANGELOG has entries under `### Fixed` (backpressure, Deno early-yield) and `### Added` (`WsSocket.drained()`).
Author
Owner

Owner decision (2026-10-23): drained?() stays optional; it is recorded for CARD-22's API report. Not merging yet: implementation review first.

Owner decision (2026-10-23): `drained?()` stays **optional**; it is recorded for CARD-22's API report. Not merging yet: implementation review first.
chrnx force-pushed feature/fprd-001c-ws-backpressure from 1145eab371 to 1603bcca53 2026-10-23 05:30:20 +00:00 Compare
chrnx force-pushed feature/fprd-001c-ws-backpressure from 1603bcca53 to 1c9f387b91 2026-10-23 05:53:14 +00:00 Compare
Author
Owner

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.
chrnx force-pushed feature/fprd-001c-ws-backpressure from 1c9f387b91 to 07f059ef2d 2026-10-23 06:11:32 +00:00 Compare
chrnx force-pushed feature/fprd-001c-ws-backpressure from 07f059ef2d to 144d880171 2026-10-23 06:14:28 +00:00 Compare
chrnx force-pushed feature/fprd-001c-ws-backpressure from 144d880171 to 23a600b438 2026-10-23 06:17:39 +00:00 Compare
chrnx added 1 commit 2026-10-23 06:20:16 +00:00
fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 19s
a9a4f6c6ef
The outbound pump pulled a @Ws handler's iterator as fast as it yielded,
whatever the peer read. With a slow client, 10,000 frames of 64 KiB were
all pulled at once and sat in the send buffer: 640 MiB.

WsSocket gains one optional member, drained(): it resolves once the
socket's send buffer is at or below the adapter's high-water mark
(WS_HIGH_WATER_MARK, 1 MiB, internal), or the socket has closed. The
pump awaits it before each pull, so the buffer peaks at the mark plus
one frame. A close ends the wait and the abort path runs the iterator's
return(), as before. A socket without drained() is never waited on.

Per runtime:
- Node: ws.bufferedAmount, released by each send's write callback;
- Bun: getBufferedAmount(), released by the server's drain callback;
- Deno: polls bufferedAmount every 10 ms, only while over the mark;
- workerd reports no buffered amount, so the edge never waits.

The Deno poll also waits while the socket is CONNECTING. Deno hands the
socket over before it opens, and a handler that yielded at once had its
first value pulled into a socket that was not open yet. The pump then
gave up, so the client saw no frame and a 1005 close.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
chrnx force-pushed feature/fprd-001c-ws-backpressure from 23a600b438 to a9a4f6c6ef 2026-10-23 06:20:16 +00:00 Compare
chrnx merged commit cdef95ffcb into develop 2026-10-23 06:22:20 +00:00
chrnx deleted branch feature/fprd-001c-ws-backpressure 2026-10-23 06:22:21 +00:00
Sign in to join this conversation.