Skip to content

Wait for WebSocket send pumps without JavaScript promises - #7929

Open
simplyzetax wants to merge 2 commits into
cloudflare:mainfrom
simplyzetax:websocket-send-pump
Open

simplyzetax wants to merge 2 commits into
cloudflare:mainfrom
simplyzetax:websocket-send-pump

Conversation

@simplyzetax

Copy link
Copy Markdown

Fixes #7745.

Problem

LegacyWebSocketAdapter::ensurePumping() starts an outgoing pump whenever send() or close() finds the queue drained, and the pump ends as soon as the queue is empty again. A server that sends to many WebSockets every frame (a Durable Object game or chat room) therefore starts one pump per socket per frame.

Each start awaited the pump with context.awaitIoLegacy(js, promise).then(js, ...). That is two jsg::Promise::then() calls, so four v8::Function::New() calls, and V8 creates an uncached FunctionTemplateInfo and SharedFunctionInfo for each in old space, plus the promises, functions and three opaque wrappers (each a cppgc shim and two CppHeap pointer-table entries that only a full GC frees). #7745 measured 4 FunctionTemplateInfo and 0.56 KB of direct old-generation growth per send turn. Every pump end also entered the isolate (lock, input gate in actors, CPU-limit scope, microtask checkpoint) only to run a continuation that, in the common case, does nothing.

So full-GC frequency scales with the number of sockets sent to per second, not with bytes or messages. workerd runs full GCs atomically (jsg/setup.c++), so each is a stop-the-world pause for the whole isolate.

Change

ensurePumping() now hands the pump to a small coroutine, awaitPump(), added with context.addTask():

  • It waits for the pump on the KJ event loop.
  • If the pump succeeded, outgoing isn't aborted, and the socket isn't closed in both directions (the usual end), it returns without entering the isolate.
  • Otherwise it enters with context.run(), in the critical section that was current when the pump started (what awaitIoLegacy() did), and runs the old continuation's code unchanged: report the error, or release the native socket. A pump failure is passed to the existing reportError(js, kj::Exception&&) overload, which converts it with the same jsg::exceptionToJs() as before. The code runs in js.tryCatch(), so an exception thrown by an error listener still becomes an unhandled rejection, as it did in the .then() continuation, instead of failing the task.

Why the fast path is equivalent: the old continuation started with exactly these checks, and it could always have got the isolate lock before anything else changed the WebSocket. Skipping it is that schedule. Every path that changes the flags afterwards (close(), the read loop's Close or disconnect, reportError(), whenAborted, hibernatable release) already handles a pump that has finished, because the old continuation often ran first too.

Why IoContext::run() rather than awaitIo() or makeReentryCallback(), which io-context.h recommends: awaitIo() would bring back a JavaScript promise and resolver per pump. The concerns that comment lists are covered here. The coroutine is an IoContext task, so it is canceled with the context. In an actor it is a waitUntil task, as with awaitIoLegacy(). It runs in the critical section captured when the pump started. Like awaitIoLegacy(), it is deliberately not a pending event (the WebSocketPair-in-one-isolate case in the existing TODO). readLoop() re-enters the same way.

Lifetime: the jsg::Ref<WebSocket> that the old lambdas held now rides on the task as a .attach(), which KJ destroys after the pump promise, so the adapter outlives the pump on cancellation as before.

What a Worker can observe: the same events, in the same order, with the same error values. Two details differ, both only when a pump fails or the socket closes:

  • The error event that a failed pump dispatches runs outside any AsyncLocalStorage context, like the events the read loop dispatches. Before, it ran in the context of whichever send() happened to start the last pump.
  • With async tracing on, a pump no longer appears as an awaitIo resource. The turn that reports a failure or releases the socket is attributed to the current request, as IoContext::run() does for the read loop.

No compatibility flag or autogate, for that reason. Happy to put it behind an autogate if you'd prefer.

Results

Apple M5 Pro, macOS 27, --config=benchmark, the same base commit with and without this change.

#7745's repro (16 sockets, 30 s per phase, forced full GCs between phases; objects that died and old-generation growth per second):

phase send turns/s dead KB/s FunctionTemplateInfo per turn old-gen growth KB/s
idle 0 9.1 → 9.1 – 0.7 → 0.7
one per turn 309 197.6 → 9.2 4.00 → 0.00 173.7 → 0.0
four per turn 309 197.6 → 9.1 4.00 → 0.00 173.7 → 0.0
split 1,235 822.5 → 9.2 4.00 → 0.00 694.5 → 0.0
one per turn, hibernation API 309 197.3 → 9.1 4.00 → 0.00 173.6 → 0.0
split, hibernation API 1,236 822.8 → 9.1 4.00 → 0.00 695.3 → 0.0

Sends now leave as much garbage as an idle Durable Object.

websocket-send-bench (new in the first commit; median per call, two runs of each binary):

case before after
send to 1 socket 3.40 µs, 3.80 µs 2.07 µs, 1.95 µs
send to 16 sockets 54.4 µs, 52.0 µs 25.7 µs, 26.1 µs
send to 64 sockets 203 µs, 211 µs 102 µs, 106 µs
send to 256 sockets 832 µs, 838 µs 427 µs, 438 µs

Each call includes delivering the messages to the other ends, so the send side alone gains more than the 2× shown.

A Durable Object that sends 256 bytes to each of 100 WebSockets 30 times a second, like a game server's tick (worker below; a Bun client on the same machine records the gaps between frames; GCs from --trace-gc, CPU time from ps):

sends only, 2 min plus 30 inputs/s from each client, 4 min after a 1 min warmup
full GCs per minute 10.5 → 0 9.8 → 3.2
full-GC pause per minute 66.6 → 0 ms 101 → 51 ms
longest full GC 26 ms → – 18 → 62 ms (see below)
young GCs per minute 2.0 → 4.0 (5.4 → 1.8 ms) 0 → 41.5 (0 → 33.7 ms)
workerd CPU 6.6% → 5.4% 10.5% → 7.1%
gap between frames, p99.9 44.2 → 40.4 ms 48.3 → 41.2 ms

With inputs, what still reaches full GCs is each received message's MessageEvent and payload, at a third of the old rate. Young GCs appear because full GCs no longer collect the young generation every 6 s. One thing gets worse: the isolate's first full GC comes later (106 s instead of 17 s) and so takes longer, 62 ms here and 123 ms in a 2-minute run, against 24–40 ms for the first one before. The full GCs after it take 6–16 ms, as before.

Load test worker
import { DurableObject } from 'cloudflare:workers';

export class Room extends DurableObject {
  sockets = new Set();
  timer = null;
  frame = new Uint8Array(256);

  async fetch(request) {
    const [client, server] = Object.values(new WebSocketPair());
    server.accept();
    server.addEventListener('message', () => {});
    const drop = () => this.sockets.delete(server);
    server.addEventListener('close', drop);
    server.addEventListener('error', drop);
    this.sockets.add(server);
    this.timer ??= setInterval(() => {
      for (const ws of this.sockets) ws.send(this.frame);
    }, 33);
    return new Response(null, { status: 101, webSocket: client });
  }
}

export default {
  fetch(request, env) {
    return env.ROOM.get(env.ROOM.idFromName('room')).fetch(request);
  },
};

Tests

New src/workerd/api/web-socket-test.c++:

  • Drained sends allocate nothing on the JavaScript heap, in a stateless context and in an actor. The test sends 4,096 messages, each after the peer received the previous one, so each send starts a pump. It compares V8's total_allocated_bytes() with entering the isolate as often without sending. Without this change it fails: 3,521,092 bytes for the sends (about 860 bytes per send), against 0 for entering without sending. With it, the sends stay within the test's allowance of 128 KB, a few allocation buffers, for all 4,096.
  • Released when the pump ends after both directions close (half-open accept, the peer closes, then close()): covers the path that still enters the isolate to release the socket.
  • Reports an error when the pump fails (the peer goes away during a send): covers the path that reports the error. The read loop reports a disconnect as a close event without setting an error, so CLOSED here means the pump's failure was reported.

The last two pass with and without this change. All four passed 10 of 10 runs with --runs_per_test=10.

Existing tests (--config=benchmark, macOS), every variant each defines (default, @all-autogates, @all-compat-flags, @gc-stress, @eslint): websocket-allow-half-open-test, websocket-client-error-test, websocket-constructor-test, websocket-open-error-test, websocket-hibernation, WPT websockets, cross-context-promise-test, events-test, global-scope-test, http-test, http-test-ts, resizable-arraybuffer-aliasing-test and tail-worker-test; output-gate-test, hibernation-manager-test, worker-entrypoint-test and server-test; and websocket-send-bench@smoke. 76 of the 77 targets pass. The other, tail-worker-test@gc-stress, fails the same way on the base commit: the forced GCs add an "RPC stub was not disposed properly" warning to a js-rpc trace that log:test compares.

Follow-ups (not in this PR)

simplyzetax and others added 2 commits October 23, 2026 19:31
websocket-send-bench sends one 256-byte message on each of 1, 16, 64
or 256 accepted WebSockets per call and waits until every message
arrives at the other end, like a server that sends to each of its
clients once per frame. Each send finds its socket's queue drained, so
each starts a new outgoing pump, which is the cost the next commit
reduces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ensurePumping() starts an outgoing pump when send() or close() finds
the queue drained, and the pump ends as soon as the queue is empty
again. A server that sends to many WebSockets every frame, such as a
Durable Object game or chat room, therefore starts one pump per socket
per frame.

Each start awaited the pump with awaitIoLegacy() and two
jsg::Promise::then() calls. That allocated JavaScript promises, four
uncached v8::Functions (each with a FunctionTemplateInfo and a
SharedFunctionInfo in old space) and three opaque wrappers, about 860
bytes per start that only a full GC frees. Each pump's end also
entered the isolate to run a continuation that usually does nothing.
workerd runs full GCs atomically, so a busy room paused every few
seconds in proportion to the sockets it sends to.

ensurePumping() now adds the pump to the IoContext as a KJ task,
awaitPump(). When the pump ends normally and the WebSocket is still
open, it returns without entering the isolate. Otherwise it enters
with IoContext::run(), in the critical section that was current when
the pump started, as the awaitIo() family does, and runs the old
continuation unchanged: report the error, or release the native
WebSocket. A pump failure goes to reportError(js, kj::Exception&&),
which converts it with the same exceptionToJs() as before. The code
runs in js.tryCatch(), so an exception from an error listener becomes an
unhandled rejection, as it did in the promise continuation, and doesn't
fail the task.

Skipping the continuation in the usual case is what happened whenever
it got the isolate lock before anything else changed the WebSocket, so
the code that later closes a WebSocket or aborts outgoing (close(), the
read loop, reportError(), whenAborted, hibernatable release) already
handles a pump that has ended. The jsg::Ref<WebSocket> that the lambdas held is
attached to the task, so the adapter outlives the pump on
cancellation, and addTask() registers no pending event, like
awaitIoLegacy() (see the existing TODO). In an actor, addTask() becomes
addWaitUntil(), which awaitIoLegacy() used too.

Compatibility: events, their order and their error values don't
change. Two details do, only when a pump fails or the socket closes:
the error event that a failed pump dispatches runs outside any
AsyncLocalStorage context, like the events the read loop dispatches,
instead of in the context of whichever send() started the last pump;
and with async tracing on, a pump no longer appears as an awaitIo
resource. We accept both without a compatibility flag or autogate.

In cloudflare#7745's repro, sends now leave as much garbage as an idle Durable
Object: 9.2 KB/s of dead objects at 1,235 send turns/s, against 822.5
before and 9.1 idle. websocket-send-bench runs about twice as fast
(256 sockets: 835 us before, 432 us after). A Durable Object that
sends to 100 WebSockets 30 times a second goes from 10.5 full GCs a
minute to none. With 30 inputs a second from each client it goes from
9.8 to 3.2, full-GC pauses from 101 to 51 ms a minute, and workerd's
CPU from 10.5% to 7.1%.

Fixes cloudflare#7745

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@simplyzetax
simplyzetax requested review from a team as code owners October 23, 2026 18:01
@github-actions

github-actions Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@clanky-the-clanker

Copy link
Copy Markdown

This pull request was not reviewed automatically because its author does not have write access to this repository. A maintainer with write access can start a review by commenting clanky review (or clanker review or @clanky-the-clanker review), optionally followed by instructions (e.g. clanky review focus on the retry logic).

@simplyzetax

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

github-actions Bot added a commit that referenced this pull request Oct 23, 2026
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.

Each WebSocket send from an idle socket leaves 4 FunctionTemplateInfo objects in old space

1 participant