Sub topic 15
Moving Buffers Between Workers with postMessage
This chapter assumes you know how ArrayBuffer and typed array views work, including how several views can share one buffer. It also assumes you know the basics of Web Workers or Node's worker_threads: a worker runs code on another thread and talks to the main thread only through messages. The previous chapter introduced detached buffers through ArrayBuffer.prototype.transfer(). This chapter applies the same idea across threads.
Copying Is the Default
When you call postMessage(value), the runtime serializes value with the structured clone algorithm and rebuilds it on the other side. For an ArrayBuffer, every byte is copied. A 200 MB buffer costs 200 MB of copying, and for a short time it uses about twice the memory. Copying also blocks the sending thread while it runs.
Transferring avoids the copy. You list the buffer in a transfer list. The runtime then hands the underlying memory block to the receiver and detaches the sender's ArrayBuffer object. Only one thread owns the memory at any moment, so the two threads can never race on it.
| Aspect | Copy (default) | Transfer |
|---|---|---|
| Cost | Proportional to byte length | Roughly constant |
| Sender after the call | Still has its data | Buffer is detached, `byteLength` is 0 |
| Peak memory | About twice the data size | Unchanged |
| Both sides usable afterwards | Yes, independently | Only the receiver |
| How to request it | `postMessage(msg)` | `postMessage(msg, [buf])` or `postMessage(msg, { transfer: [buf] })` |
The Transfer List
The second argument to postMessage is either an array of transferable objects or an options object with a transfer property. The message itself is still structured-cloned. Each object it references that also appears in the transfer list is moved instead of copied.
// main.js (browser)
const worker = new Worker('worker.js');
const pixels = new Uint8ClampedArray(4 * 1920 * 1080);
worker.postMessage({ width: 1920, height: 1080, pixels }, [pixels.buffer]);
console.log(pixels.length); // 0, the view now sits on a detached buffer
console.log(pixels.buffer.byteLength); // 0// worker.js
self.onmessage = (event) => {
const { width, height, pixels } = event.data;
console.log(width, height, pixels.length); // 1920 1080 8294400
};Notice what is being transferred. The transfer list holds pixels.buffer, the ArrayBuffer. A typed array is not transferable on its own. You put the view in the message and its buffer in the transfer list. The receiver gets a new view of the same type, with the same byteOffset and length, over the moved buffer.
Observing Detachment Without a Worker
structuredClone(value, { transfer }) runs the same algorithm in a single thread, so you can study transfer behaviour in one file. This runs in modern browsers and in Node 17 or later.
const buf = new ArrayBuffer(16);
const view = new Uint8Array(buf, 4, 8);
view.fill(7);
const clone = structuredClone(view, { transfer: [buf] });
// Sender side: everything collapses to zero
console.log(buf.byteLength, buf.detached); // 0 true
console.log(view.length, view.byteOffset); // 0 0
console.log(view[0]); // undefined
// Receiver side: same shape, same data, whole buffer moved
console.log(clone.byteOffset, clone.length); // 4 8
console.log(clone.buffer.byteLength, clone[0]); // 16 7
// Writes to a detached view are silently ignored
view[0] = 42;
console.log(view[0]); // undefined
// Most methods throw instead
try {
view.fill(1);
} catch (e) {
console.log(e instanceof TypeError); // true
}A detached view does not behave consistently. Indexed reads return undefined and indexed writes do nothing, but methods such as fill, set, map, and slice throw a TypeError. A bug that leaves a detached view in use can therefore fail quietly in one place and loudly in another.
The Whole Buffer Moves
Transfer works on buffers, not on views. In the example above, view covered only 8 of the 16 bytes, yet all 16 bytes moved. Every other view over buf in the sender is now dead as well.
This matters when you send part of a larger buffer:
const big = new Uint8Array(1024);
const header = big.subarray(0, 16);
const body = big.subarray(16);
const received = structuredClone(body, { transfer: [body.buffer] });
console.log(received.length, received.buffer.byteLength); // 1008 1024
console.log(header.length); // 0, header shared the buffer and is gone tooIf you need to send only a slice and keep the rest, copy that slice first with slice(), which creates its own buffer, and transfer the copy. The receiver then also gets a buffer of the right size and not the full 1024 bytes.
Transfer Errors
The runtime checks the transfer list before it moves anything. A bad list throws a DOMException named DataCloneError, and nothing is transferred.
function tryClone(value, transfer) {
try {
structuredClone(value, { transfer });
return 'ok';
} catch (e) {
return e.name;
}
}
const a = new ArrayBuffer(8);
console.log(tryClone(a, [a, a])); // "DataCloneError", listed twice
const b = new ArrayBuffer(8);
structuredClone(b, { transfer: [b] }); // b is now detached
console.log(tryClone(b, [b])); // "DataCloneError", already detached
const s = new SharedArrayBuffer(8);
console.log(tryClone(s, [s])); // "DataCloneError", shared memory cannot be transferredOther cases to know:
- A
SharedArrayBufferin the message without a transfer list is not copied. Both sides get access to the same memory, which is the topic of the next chapter. - Some buffers cannot be detached, such as
WebAssembly.Memory.prototype.buffer. Listing one throws. - A buffer in the transfer list is detached even if the message does not reference it. The receiver has no way to reach it, so the memory is lost to both sides. Keep the transfer list in sync with the message.
Round-Tripping: Ping-Pong Ownership
Since only one side owns a transferred buffer, a common pattern passes the same buffer back and forth. The main thread fills it, transfers it to the worker, and the worker processes it and transfers it back. The memory is allocated once and is never copied.
This Node example runs as a single file with node pingpong.mjs:
// pingpong.mjs
import { Worker, isMainThread, parentPort } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url));
const data = new Float64Array(1_000_000).fill(1);
worker.postMessage(data, [data.buffer]);
console.log('main after send:', data.length); // 0
worker.once('message', (result) => {
console.log('main got back:', result.length, result[0]); // 1000000 2
worker.terminate();
});
} else {
parentPort.once('message', (arr) => {
for (let i = 0; i < arr.length; i++) arr[i] *= 2;
parentPort.postMessage(arr, [arr.buffer]);
});
}For a steady stream of work, keep a small pool of buffers. While the worker processes one, the main thread fills another. Buffers that come back go into the pool. This gives you pipelining without allocating new memory per message.
Deciding Between Copy, Transfer, and Sharing
- Copy when the payload is small (a few kilobytes) or the sender still needs its data. The copy is cheap and the code stays simple.
- Transfer when the payload is large and the sender is done with it, or when ownership can pass back and forth. Typical cases are image frames, audio blocks, decoded files, and mesh data.
- Share with
SharedArrayBufferwhen both threads must read or write the same memory at the same time. That needsAtomicsfor coordination and, in browsers, a cross-origin isolated page.
Transfer is the right choice most of the time. It gives you zero-copy performance with no risk of data races, and it works on any page without special headers.
Exercise
You run worker.postMessage({ frame: view }, [view.buffer]), where view is new Uint16Array(buf, 8, 100) and buf is 1000 bytes long. What do view.length, buf.byteLength, and, in the worker, event.data.frame.byteOffset, event.data.frame.length, and event.data.frame.buffer.byteLength print?
Show answer
In the sender, view.length is 0 and buf.byteLength is 0, because buf is detached. In the worker, frame.byteOffset is 8 and frame.length is 100, because the view keeps its shape. frame.buffer.byteLength is 1000, because the whole buffer is transferred and not only the 200 bytes the view covers.
Exercise
A teammate's code calls worker.postMessage(bytes) with a 50 MB Uint8Array and then never touches bytes again. Profiling shows the call takes about 30 ms. What is wrong, how do you fix it, and how can you confirm the fix in code?
Show answer
Without a transfer list the buffer is structured-cloned, so all 50 MB are copied. Change the call to worker.postMessage(bytes, [bytes.buffer]). To confirm the transfer, check that bytes.buffer.byteLength === 0 (or bytes.buffer.detached === true) right after the call.
Exercise
Why does structuredClone(buf, { transfer: [buf, buf] }) fail, and is buf detached afterwards?
Show answer
Listing the same buffer twice is invalid, so the call throws a DOMException named "DataCloneError". The runtime validates the transfer list before it moves anything, so buf is not detached and keeps its original byteLength.