Repository navigation
Wait for WebSocket send pumps without JavaScript promises - #7929
Open
simplyzetax wants to merge 2 commits into
Open
simplyzetax wants to merge 2 commits into
simplyzetax wants to merge 2 commits into
Conversation
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]>
|
All contributors have signed the CLA ✍️ ✅ |
|
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 |
Author
|
I have read the CLA Document and I hereby sign the CLA |
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.
Fixes #7745.
Problem
LegacyWebSocketAdapter::ensurePumping()starts an outgoing pump wheneversend()orclose()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 twojsg::Promise::then()calls, so fourv8::Function::New()calls, and V8 creates an uncachedFunctionTemplateInfoandSharedFunctionInfofor 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 4FunctionTemplateInfoand 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 withcontext.addTask():context.run(), in the critical section that was current when the pump started (whatawaitIoLegacy()did), and runs the old continuation's code unchanged: report the error, or release the native socket. A pump failure is passed to the existingreportError(js, kj::Exception&&)overload, which converts it with the samejsg::exceptionToJs()as before. The code runs injs.tryCatch(), so an exception thrown by anerrorlistener 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 thanawaitIo()ormakeReentryCallback(), whichio-context.hrecommends: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 awaitUntiltask, as withawaitIoLegacy(). It runs in the critical section captured when the pump started. LikeawaitIoLegacy(), 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
errorvalues. Two details differ, both only when a pump fails or the socket closes:errorevent that a failed pump dispatches runs outside anyAsyncLocalStoragecontext, like the events the read loop dispatches. Before, it ran in the context of whicheversend()happened to start the last pump.awaitIoresource. The turn that reports a failure or releases the socket is attributed to the current request, asIoContext::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):
FunctionTemplateInfoper turnSends 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):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 fromps):With inputs, what still reaches full GCs is each received message's
MessageEventand 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
Tests
New
src/workerd/api/web-socket-test.c++: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.close()): covers the path that still enters the isolate to release the socket.closeevent without setting an error, soCLOSEDhere 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, WPTwebsockets,cross-context-promise-test,events-test,global-scope-test,http-test,http-test-ts,resizable-arraybuffer-aliasing-testandtail-worker-test;output-gate-test,hibernation-manager-test,worker-entrypoint-testandserver-test; andwebsocket-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 thatlog:testcompares.Follow-ups (not in this PR)
awaitIo*()still ends withjsPromise.then(js, throwOrReturnResult<Result>), and everyjsg::Promise::then()makes two uncachedv8::Functions. Creating those functions once per isolate (the other idea in Each WebSocket send from an idle socket leaves 4FunctionTemplateInfoobjects in old space #7745) would help all I/O, not just WebSockets.MessageEventand payload, which is per message and expected.