Skip to content

WebSocket: uncompressed messages received in one chunk are dispatched in the same task (no microtask checkpoint between message events) #6246

Open

Description

@Lightning00Blade

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):

  1. Start an HTTP/WebSocket server using node:http createServer() that handles 'upgrade' without negotiating permessage-deflate.
  2. Connect with new WebSocket(url) from undici.
  3. From the server, send two or more uncompressed text frames in one socket.write() call.
  4. In the client's 'message' listener, log event.data and schedule queueMicrotask(() => log.push('microtask(' + event.data + ')')) (or use an async listener that awaits 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:

  • log should be ['m1', 'microtask(m1)', 'm2', 'microtask(m2)', 'm3', 'microtask(m3)'].
  • seenBySecond should resolve to true.

Actual Behavior

All uncompressed messages present in the chunk fire synchronously before any microtask queued by the first listener runs:

  • log is ['m1', 'm2', 'm3', 'microtask(m1)', 'microtask(m2)', 'microtask(m3)'].
  • seenBySecond resolves to false.

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 on v22.23.4, and with globalThis.WebSocket on v22.12.0)
  • undici version: 8.13.1 (also reproduced on 8.12.4 and bundled 6.21.0 / 6.29.1 / 7.28.0)

Additional context

  • Root cause (lib/web/websocket/receiver.js):
    1. ByteParser.run(callback) parses frames in a synchronous while (this.#loop) loop.
    2. For uncompressed frames (!this.#info.compressed), when a message completes (!this.#info.fragmented && this.#info.fin, which also covers the final CONTINUATION frame), it calls websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments()) synchronously and continues looping over the remaining buffer in the same turn.
    3. websocketMessageReceived() -> #onMessage() -> fireEvent() dispatches the MessageEvent synchronously (target.dispatchEvent(event)) without queuing a task.
    4. Compressed messages happen to conform only by accident because permessage-deflate decompress() invokes its callback asynchronously.
  • Real-world impact: We hit this in Puppeteer when prototyping a transport backed by Node's built-in WebSocket. Chrome negotiates permessage-deflate, masking the bug; Firefox's WebDriver BiDi server does not negotiate compression, so coalesced uncompressed responses broke async handler ordering.
  • Browser comparison: Running the same client code against the same single-write server in Chrome 157.0.8103.78 and Firefox 160.0 produces ['m1', 'microtask(m1)', 'm2', 'microtask(m2)', 'm3', 'microtask(m3)'].
  • Possible fix: Pause ByteParser after calling websocketMessageReceived() on the uncompressed path (this.#state = parserStates.INFO; this.#loop = false; setImmediate(() => { this.#loop = true; this.run(callback) })) — the same mechanism ws uses for allowSynchronousEvents: false. (Prototyped on 8.12.4, where all 3 tests above pass.)

Activity

  1. added
    bug
    on Nov 23, 2026
  2. cestercian commented on Nov 23, 2026

    @cestercian

    taking a look at this, will send a PR

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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions