DEV Community

Alex Georgiev
Alex Georgiev

Posted on AI-assisted

Node can finally mask WebSocket frames without a native addon

Up to 50x faster than JS fallbacks

I was going through the Node.js 26 changelog because 26.x went into long-term support at the end of October, and the usual one-line "what's new" summaries never go past the headline items. Buried in the 26.12.0 entry, filed as a plain SEMVER-MINOR line with no explanation, were two new functions on node:http: websocketMask() and websocketUnmask(). I hadn't heard of either, so I pulled them apart over an afternoon.

What they do is narrow: XOR a buffer against a repeating 4-byte key, either in place or into a separate output buffer. That is exactly the masking operation the WebSocket protocol requires every client to apply before sending a frame, and every server to undo on the way in (RFC 6455, section 5.3). Until this release, doing that fast in Node meant installing bufferutil, an optional native addon for the ws package. Without it installed, ws quietly falls back to a plain JavaScript loop and never tells you it happened - I wanted to know what that fallback actually costs.

What ws did before this landed

I pinned ws to version 8.18.0 for this comparison without checking whether that was still current - it wasn't, and what I found when I did check is the best part of this post, further down. 8.18.0 ships its own masking loop in lib/buffer-util.js:

function _mask(source, mask, output, offset, length) {
  for (let i = 0; i < length; i++) {
    output[offset + i] = source[i] ^ mask[i & 3];
  }
}
Enter fullscreen mode Exit fullscreen mode

Interestingly, ws doesn't always prefer the native addon even when it's installed. It only reaches for bufferutil above a size it has picked itself: 48 bytes for masking, 32 for unmasking. Below that it runs the loop above regardless, on the assumption that crossing into native code costs more than the loop saves at that size.

Measuring the builtin against that loop

I ran both functions side by side inside node:26-slim (26.13.1, the current LTS point release), across payload sizes from 16 bytes to 1MB. Each size was warmed up with 5,000 throwaway calls per side before timing - the first draft of this benchmark skipped that and got a noisy, inflated number for the very first size it measured, which is a mistake I should have caught sooner than I did. The script then ran as three separate processes, and the table below shows the median of those three runs for masking:

payload http.websocketMask ws's JS fallback native vs JS
16 B 41 ns 22 ns 0.5x (JS wins)
32 B 35 ns 49 ns 1.4x
48 B 34 ns 66 ns 1.9x
256 B 37 ns 293 ns 7.9x
4 KB 117 ns 4,516 ns 38x
64 KB 1.7 µs 76.4 µs 45x
1 MB 46.5 µs 1.21 ms 26x

Unmasking follows the same shape as masking, just with its crossover sitting a size band higher than masking's:

payload http.websocketUnmask ws's JS fallback native vs JS
16 B 28 ns 16 ns 0.6x (JS wins)
32 B 26 ns 29 ns roughly even
64 B 28 ns 51 ns 1.8x
4 KB 104 ns 3.7 µs 35x
1 MB 20.3 µs 879 µs 43x

Getting that unmask column right took a second pass: an earlier draft of the script passed half the iteration count into the unmask timing loop but still divided by the full count afterwards, which quietly halved every unmask figure I first had. The ratios between native and JS still looked right, which is exactly why I nearly missed it; the absolute numbers next to the mask table were what looked off.

For a chat app sending mostly small JSON frames, this is the difference between needing a compiled addon in your Docker image (and the toolchain that comes with it) and not needing one at all. For anything moving binary payloads in the kilobyte-to-megabyte range, it's a large win over the plain-JS fallback specifically - I only checked ws, not every WebSocket library, so I can't say how common that fallback path actually is across the ecosystem, only that it's what ws itself ships when bufferutil isn't installed.

The opposite reading

At 16 bytes, the plain loop wins. Crossing into the native call costs more than three or four XORs save, in both the mask and unmask direction. That is a real cost, not a rounding error: masking was 1.85-1.89x slower across all three runs, a tight and consistent result. Unmasking was slower too, but noisier - 1.27x in one run against 1.69-1.84x in the other two - so I'd put the real figure somewhere in that range rather than quote a single number I don't fully trust.

My own crossover for this builtin sits a little lower than the 48/32-byte thresholds ws 8.18.0 picked for bufferutil: native starts winning around 32 bytes for masking, and is roughly break-even with the loop at 32 bytes for unmasking too. I went looking for whether anyone building on top of this had measured the same gap, and found something better than a guess. ws 8.22.1, released on 31 October - two and a half weeks after Node 26.12.0 shipped the builtin - added exactly this feature detection to lib/buffer-util.js:

const { websocketMask, websocketUnmask } = require('http');
// ...
if (websocketMask) {
  module.exports.mask = function (source, mask, output, offset, length) {
    if (length < 24) _mask(source, mask, output, offset, length);
    else websocketMask(source, mask, output, offset, length);
  };
  // ...
} /* istanbul ignore else */ else if (!process.env.WS_NO_BUFFER_UTIL) {
  // ...falls through to bufferutil, then the plain loop, on older Node
}
Enter fullscreen mode Exit fullscreen mode

ws now prefers the builtin over bufferutil whenever it's available, at its own crossover of 24 bytes - lower than the 48/32 it uses for bufferutil, and close to what I measured independently. Two separate measurements, mine and the ws maintainers', landing near the same place on where a builtin call stops paying for itself. 8.23.1, the version at the top of npm right now and released two days before I wrote this, keeps the same logic.

What it refuses

I fed it the cases a real implementation would hit by mistake:

mask with 3-byte key -> TypeError: The argument 'mask' must be 4 bytes long. Received <Buffer 11 22 33> (code=ERR_INVALID_ARG_VALUE)
mask length > source.byteLength -> RangeError: The value of "length" is out of range. It must be >= 0 && <= 11. Received 21 (code=ERR_OUT_OF_RANGE)
mask offset+length > output.byteLength -> RangeError: The value of "length" is out of range. It must be <= 5. Received 11 (code=ERR_OUT_OF_RANGE)
mask with negative length -> RangeError: The value of "length" is out of range. It must be >= 0 && <= 11. Received -1 (code=ERR_OUT_OF_RANGE)
Enter fullscreen mode Exit fullscreen mode

All of these are things a WebSocket frame parser could plausibly produce from a malformed or truncated frame header, so getting a typed error with the exact bad value in it, instead of a silent out-of-bounds write, is worth having.

The docs also promise something less obvious: source and output can overlap, and the result is "the same as if source had been copied first". I tested this with two views over one buffer, offset by one byte and overlapping by nine, against masking into a fully independent copy. They matched byte for byte - an easy thing to get wrong in a hand-rolled implementation, and easy to not notice you got wrong, since it only shows up with in-place aliasing.

There's a third documented refusal I almost couldn't test at all: writing into a buffer backed by an "immutable ArrayBuffer". More on that below.

Under concurrency

Masking is pure CPU work with no I/O, so I wanted to know whether it's worth moving off the main thread under load. I wrote a worker_threads harness: spin up N workers, each masking a 64KB buffer repeatedly, measure wall-clock throughput as N goes from 1 to 8 on this box's four CPUs.

What I got wrong on the way

My first version never called worker.terminate() on a finished worker, and I ran it short: 20,000 iterations per worker, three runs. Going from 1 to 4 workers raised throughput by a median of about 2.8x, short of the 4x I expected, which looked like the feature itself might be contended somehow. It wasn't: each round left its workers running, so by the 8-worker round, idle workers from every earlier round were still alive and schedulable. I added terminate() and reran, and the fix looked like it mattered - a median of 3.9x at 4 workers instead of 2.8x. I nearly published that as the finding.

But three short runs weren't enough: a 20,000-iteration job finishes fast enough that thread start-up noise is a large share of what's being timed. I reran both versions five times each with a 200,000-iteration workload, and this time computed each run's own scaling ratio instead of just comparing medians across runs. The per-run numbers were far wider than a single clean multiplier suggests: at 4 workers, buggy ranged 1.6x-4.5x (median 3.6x) and fixed ranged 2.4x-3.6x (median 3.2x); at 8 workers, buggy ranged 3.1x-5.1x (median 4.0x) and fixed ranged 2.3x-4.4x (median 3.0x). Those ranges overlap almost completely - "within noise of each other" here means two distributions I can't confidently tell apart with five runs each, not two tidy numbers that happen to be close. The terminate() bug was still real and worth fixing, but it wasn't the explanation for the scaling shortfall I first reported - that conclusion was built on too little data running for too short a time, and more data made it fall apart into exactly the spread it had been hiding. I also can't call what happens past 4 workers "oversubscription" with any confidence: median throughput kept inching up from 4 to 8 rather than dropping, and this container's --cpus=4 is a CPU-time quota, not a pin to four specific cores.

What does hold up regardless: the per-call cost of websocketMask is tens of nanoseconds up to around fifty microseconds for the largest frame I tested, and spinning up or tearing down a worker thread costs far more than that - hundreds of milliseconds across a handful of workers in the data above. There's no good reason to hand a single connection's masking off to a worker thread.

The immutable ArrayBuffer refusal

Node's docs say websocketMask throws if output is "backed by an immutable ArrayBuffer". I went looking for how to construct one and came up empty: ArrayBuffer.prototype.transferToImmutable doesn't exist on a default Node 26.13.1 launch. I'd nearly written this off as something I couldn't verify.

It turns out it's there, just gated behind an experimental V8 flag that Node's own test suite for this feature declares at the top of the file: --js-immutable-arraybuffer. With that flag passed to node, the method appears and the documented refusal is exactly what it says:

mask into immutable -> TypeError: The argument 'output' must not be backed by an immutable ArrayBuffer. Received <Buffer 01 02 03 04 05 06 07 08> (code=ERR_INVALID_ARG_VALUE)
Enter fullscreen mode Exit fullscreen mode

So the claim in the docs is accurate, but it describes behaviour that isn't reachable without an experimental flag almost nobody will have set. Reading the test file that ships with the release, rather than trusting my own first attempt, was the only way I found that.

Run it yourself

This reproduces the correctness checks and the small-vs-large crossover with Node 26.12 or later (I used node:26-slim via Docker, since most hosts won't have 26.x yet):

const { Buffer } = require('node:buffer');
const { websocketMask, websocketUnmask } = require('node:http');

function jsMask(source, mask, output, offset, length) {
  for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
}

const key = Buffer.from([0x37, 0xfa, 0x21, 0x3d]);

for (const size of [16, 256, 4096]) {
  const source = Buffer.alloc(size, 0xab);
  const outNative = Buffer.alloc(size);
  const outJs = Buffer.alloc(size);
  const iters = 200000;

  let t = process.hrtime.bigint();
  for (let i = 0; i < iters; i++) websocketMask(source, key, outNative, 0, size);
  const nativeMs = Number(process.hrtime.bigint() - t) / 1e6;

  t = process.hrtime.bigint();
  for (let i = 0; i < iters; i++) jsMask(source, key, outJs, 0, size);
  const jsMs = Number(process.hrtime.bigint() - t) / 1e6;

  console.log(size, 'bytes:', 'native', (nativeMs * 1e6 / iters).toFixed(1), 'ns/op,',
              'js', (jsMs * 1e6 / iters).toFixed(1), 'ns/op,',
              'match:', outNative.equals(outJs));
}
Enter fullscreen mode Exit fullscreen mode
docker run --rm node:26-slim node -e "$(cat bench.js)"
Enter fullscreen mode Exit fullscreen mode

Where this leaves me

If you're already on ws 8.22.1 or later - and 8.23.1, the current release, is - you're getting most of this for free: bufferutil has quietly gone from "the thing you should install" to "the thing ws falls back to on an older Node." I'd still check which version a project is actually running before assuming that; plenty of lockfiles are older than two and a half weeks.

Below about 32 bytes, the plain loop is still the right call, same as ws's own 24-byte cutoff concludes. These two functions shipped with no prose in the changelog beyond their names - my guess is the Node team expected a library, not an application author, to pick them up directly. Given how fast ws moved on it, that guess looks about right.

Top comments (7)

Collapse
 
andrii_0308f2a18c503d78ec profile image
Andrii •

Thanks for sharing this! The benchmark clearly shows how much faster the built-in implementation is than ws's JavaScript fallback, but I'm curious about how it compares directly with bufferutil, which was the previous native optimization. Adding it as a third benchmark baseline would help establish whether the new implementation maintains or improves performance, rather than just eliminating an external dependency. Did you test the built-in functions against bufferutil using the same payload sizes and hardware?

Collapse
 
alexgeorgiev17 profile image
Alex Georgiev •

No, I didn't, and that's a fair gap. The only comparison in the post is against ws's plain JS loop, because that's what you get when bufferutil isn't installed. So "up to 50x" is a number against the fallback, not against bufferutil, and I can't say from my own data whether the builtin beats bufferutil, matches it, or just removes the dependency.

The closest thing I have is indirect: ws 8.22.1 picks the builtin over bufferutil whenever both are available. That suggests the maintainers don't see it as a step down, but it's their call, not a measurement I made. A third column with bufferutil on the same container and the same sizes is the right way to settle it, and the "Run it yourself" script would only need one more loop to do that.

Collapse
 
andrii_0308f2a18c503d78ec profile image
Andrii •

Um , I see .
Thanks you for your opinion.

Thread Thread
 
alexgeorgiev17 profile image
Alex Georgiev •

Thanks for asking it, it's the comparison the post should have had.

Collapse
 
lin7c profile image
xcl •

The overlap guarantee is the detail that matters most for a real parser, because a server reusing one receive buffer can easily pass overlapping source and output views. Did you test both directions of the one-byte offset, or only the case where output starts after source? The documentation says the result is the same as if source had been copied first, but a naive in-place loop would behave differently depending on which side starts first, so that distinction is worth pinning down. On the worker_threads section, the --cpus=4 correction is a useful catch: since that is a CPU-time quota rather than pinning to four cores, did the 3.9x figure at four workers hold when the workers were masking independent 64KB buffers, and would the transfer cost of moving frames off the main thread still make sense for the small frames where the builtin barely beats the plain loop?

Collapse
 
alexgeorgiev17 profile image
Alex Georgiev •

Good question, and the post only tested one direction. So I just ran both, on node:26-slim (which is 26.14.0 now), with a one-byte offset at 10, 64 and 4096 bytes. The builtin matched a masked independent copy in both directions at every size. The naive loop only gets it right when output starts before source. When output starts one byte after source, each write lands on the next byte it's about to read, so it's wrong at every size I tried. That's exactly the bug the docs are promising you won't hit.

On the workers, I'd drop the 3.9x. That came from three short runs and didn't survive the longer ones. With 200,000 iterations, five runs each, the fixed version ranged 2.4x to 3.6x at four workers (median 3.2x), and that's with each worker masking its own 64KB buffer, not a shared one. So no clean number, and I wouldn't read anything about the quota into it either.

And for small frames I'd say no. Even at 64KB the call costs a couple of microseconds, and a postMessage round trip to a worker costs more than that before it does any work. Down where the builtin barely beats the loop, it's a few dozen nanoseconds per call, so handing it to another thread can only make it slower.

Collapse
 
ruslan_surkisov_9fe54d728 profile image
Ruslan Surkisov •

Your small-frame results are a useful reminder to benchmark the actual workload. For a possible live-update backend for nmiu.com.ua, I’d measure incoming editor messages separately from the outgoing reader feed. Have you tested end-to-end latency and event-loop delay under realistic connection counts, beyond the masking benchmark itself?