Repository navigation
Description
Bug Description
When multiple uncompressed WebSocket messages arrive in the same network chunk, WebSocket dispatches all of their message events synchronously back-to-back in the same loop iteration. Microtasks queued inside a message listener (including Promise / await continuations) therefore do not run until after all subsequent messages in that chunk have already been dispatched.
According to WHATWG WebSockets §4 "Feedback from the protocol" (message step), the user agent must queue a task on the WebSocket task source for each received message, so the HTML event loop processing model performs a microtask checkpoint between consecutive message events. Both Chrome and Firefox behave that way on the exact same server bytes.
Reproduction
Standalone reproduction script:
'use strict'
const { test } = require('node:test')
const { createHash } = require('node:crypto')
const { createServer } = require('node:http')
const { once } = require('node:events')
const { WebSocket } = require('undici')
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
function frame (opcode, fin, text) {
const payload = Buffer.from(text)
return Buffer.concat([
Buffer.from([(fin ? 0x80 : 0x00) | opcode, payload.length]),
payload
])
}
function textFrame (text) {
return frame(0x01, true, text)
}
async function startWebSocketServer (t, frames) {
const sockets = new Set()
const server = createServer()
server.on('upgrade', (req, socket) => {
sockets.add(socket)
socket.on('close', () => sockets.delete(socket))
const key = req.headers['sec-websocket-key']
const accept = createHash('sha1').update(key + GUID).digest('base64')
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept}\r\n\r\n`
)
// Write all uncompressed frames in a single chunk so they arrive together.
setTimeout(() => {
if (!socket.destroyed) {
socket.write(Buffer.concat(frames))
}
}, 50)
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
t.after(() => {
for (const socket of sockets) socket.destroy()
server.close()
})
return `ws://127.0.0.1:${server.address().port}`
}
test('each uncompressed message is dispatched in its own task', { timeout: 60000 }, async (t) => {
t.plan(1)
const url = await startWebSocketServer(t, [
textFrame('m1'),
textFrame('m2'),
textFrame('m3')
])
const ws = new WebSocket(url)
t.after(() => ws.close())
const log = []
await new Promise((resolve) => {
ws.addEventListener('message', (event) => {
log.push(event.data)
queueMicrotask(() => {
log.push(`microtask(${event.data})`)
if (event.data === 'm3') resolve()
})
})
})
t.assert.deepStrictEqual(log, [
'm1', 'microtask(m1)',
'm2', 'microtask(m2)',
'm3', 'microtask(m3)'
])
})
test('fragmented uncompressed messages also yield a microtask checkpoint before the next message', { timeout: 60000 }, async (t) => {
t.plan(1)
const url = await startWebSocketServer(t, [
frame(0x01, false, 'm1-'),
frame(0x00, true, 'end'),
textFrame('m2')
])
const ws = new WebSocket(url)
t.after(() => ws.close())
const log = []
await new Promise((resolve) => {
ws.addEventListener('message', (event) => {
log.push(event.data)
queueMicrotask(() => {
log.push(`microtask(${event.data})`)
if (event.data === 'm2') resolve()
})
})
})
t.assert.deepStrictEqual(log, [
'm1-end', 'microtask(m1-end)',
'm2', 'microtask(m2)'
])
})
test('an awaited continuation from one message runs before the next message', { timeout: 60000 }, async (t) => {
t.plan(1)
const url = await startWebSocketServer(t, [
textFrame('first'),
textFrame('second')
])
const ws = new WebSocket(url)
t.after(() => ws.close())
let ready = false
const seenBySecond = new Promise((resolve) => {
ws.addEventListener('message', async (event) => {
if (event.data === 'first') {
await null
ready = true
} else {
resolve(ready)
}
})
})
t.assert.strictEqual(await seenBySecond, true)
})Steps to reproduce (if not using the script above):
- Start an HTTP/WebSocket server using
node:httpcreateServer()that handles'upgrade'without negotiatingpermessage-deflate. - Connect with
new WebSocket(url)fromundici. - From the server, send two or more uncompressed text frames in one
socket.write()call. - In the client's
'message'listener, logevent.dataand schedulequeueMicrotask(() => log.push('microtask(' + event.data + ')'))(or use anasynclistener thatawaits before mutating shared state).
Expected Behavior
Each message event runs in its own task, with a microtask checkpoint before the next message event is dispatched:
logshould be['m1', 'microtask(m1)', 'm2', 'microtask(m2)', 'm3', 'microtask(m3)'].seenBySecondshould resolve totrue.
Actual Behavior
All uncompressed messages present in the chunk fire synchronously before any microtask queued by the first listener runs:
logis['m1', 'm2', 'm3', 'microtask(m1)', 'microtask(m2)', 'microtask(m3)'].seenBySecondresolves tofalse.
Logs & Screenshots
Running node --test test/repro-message-tasks.js against undici@8.13.1:
✖ each uncompressed message is dispatched in its own task (98.866238ms)
✖ fragmented uncompressed messages also yield a microtask checkpoint before the next message (66.380569ms)
✖ an awaited continuation from one message runs before the next message (57.414459ms)
ℹ tests 3
ℹ suites 0
ℹ pass 0
ℹ fail 3
✖ failing tests:
✖ each uncompressed message is dispatched in its own task
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
'm1',
+ 'm2',
+ 'm3',
'microtask(m1)',
- 'm2',
'microtask(m2)',
- 'm3',
'microtask(m3)'
]
✖ fragmented uncompressed messages also yield a microtask checkpoint before the next message
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
'm1-end',
+ 'm2',
'microtask(m1-end)',
- 'm2',
'microtask(m2)'
]
✖ an awaited continuation from one message runs before the next message
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
false !== true
Environment
- OS: Debian GNU/Linux rodete (
Linux 7.1.6-1rodete1-amd64 x86_64) - Node.js version:
v24.18.0(also reproduced onv22.23.4, and withglobalThis.WebSocketonv22.12.0) - undici version:
8.13.1(also reproduced on8.12.4and bundled6.21.0/6.29.1/7.28.0)
Additional context
- Root cause (
lib/web/websocket/receiver.js):ByteParser.run(callback)parses frames in a synchronouswhile (this.#loop)loop.- For uncompressed frames (
!this.#info.compressed), when a message completes (!this.#info.fragmented && this.#info.fin, which also covers the finalCONTINUATIONframe), it callswebsocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments())synchronously and continues looping over the remaining buffer in the same turn. websocketMessageReceived()->#onMessage()->fireEvent()dispatches theMessageEventsynchronously (target.dispatchEvent(event)) without queuing a task.- Compressed messages happen to conform only by accident because
permessage-deflatedecompress()invokes its callback asynchronously.
- Real-world impact: We hit this in Puppeteer when prototyping a transport backed by Node's built-in
WebSocket. Chrome negotiatespermessage-deflate, masking the bug; Firefox's WebDriver BiDi server does not negotiate compression, so coalesced uncompressed responses brokeasynchandler ordering. - Browser comparison: Running the same client code against the same single-write server in Chrome
157.0.8103.78and Firefox160.0produces['m1', 'microtask(m1)', 'm2', 'microtask(m2)', 'm3', 'microtask(m3)']. - Possible fix: Pause
ByteParserafter callingwebsocketMessageReceived()on the uncompressed path (this.#state = parserStates.INFO; this.#loop = false; setImmediate(() => { this.#loop = true; this.run(callback) })) — the same mechanismwsuses forallowSynchronousEvents: false. (Prototyped on8.12.4, where all 3 tests above pass.)
Activity
cestercian commentedon Nov 23, 2026
taking a look at this, will send a PR