Sub topic 16
When to Use Shared Memory Instead of Message Passing
This chapter assumes you have worked through the earlier chapters. You should know how to create a SharedArrayBuffer, how to read and write it with Atomics, how to block a thread with Atomics.wait, and how the mutex and ring buffer patterns work. It also assumes you know how postMessage uses the structured clone algorithm to copy data. The question here is when to use any of it. Shared memory is a specialist tool. Most worker code should still use messages.
The Three Ways to Move Data Between Agents
JavaScript gives you three ways to get bytes from one agent to another. Each has a different cost.
- Structured clone (copy).
postMessage(value)serializes the value and builds a copy on the receiving side. Each side owns its own copy, so a race is impossible. The cost grows with the size of the data: cloning 50 MB means touching 50 MB twice. - Transfer (move).
postMessage(buffer, [buffer])hands over ownership of anArrayBufferwithout copying the bytes. The sender's buffer is detached, meaning its length becomes 0 and it can no longer be used. Only one agent owns the bytes at any moment, so a transfer is cheap and still race-free. - Share. Posting a
SharedArrayBuffergives both agents a view of the same memory. Nothing is copied or detached. Both sides can read and write at any time, which is where data races and the need forAtomicscome from.
You can see detachment directly with structuredClone, which uses the same algorithm as postMessage:
const buf = new ArrayBuffer(1024);
const moved = structuredClone(buf, { transfer: [buf] });
console.log(buf.byteLength); // 0, the original is detached
console.log(moved.byteLength); // 1024, the new owner has the bytesTransfer is often overlooked, and it covers many cases people use shared memory for. If you produce a large buffer, hand it off, and never touch it again, transferring it gets you zero-copy handoff without any synchronization code.
| Mechanism | Copies bytes | Both sides access at once | Needs Atomics | Needs cross-origin isolation | Works with objects |
|---|---|---|---|---|---|
| Structured clone | Yes | No | No | No | Yes |
| Transfer | No | No (ownership moves) | No | No | Only transferable types |
| SharedArrayBuffer | No | Yes | Yes | Yes (browsers) | No, raw bytes only |
What Message Passing Really Costs
A postMessage call has a fixed cost on top of the clone. The message is queued as a task on the receiver's event loop. The receiver handles it only when its current task finishes and the loop gets to it. Two consequences follow.
- Latency depends on the receiver's event loop. If a worker is in a 200 ms computation, your message waits 200 ms. There is no way to interrupt it.
- Per-message overhead dominates small, frequent messages. Sending one number 60,000 times a second spends most of its time on queueing and serialization rather than on the data.
Shared memory avoids both problems. A worker in a tight loop can check a shared flag with Atomics.load on every iteration, and the check costs a few nanoseconds. A consumer blocked in Atomics.wait wakes up as soon as Atomics.notify runs, without waiting for an event loop turn.
Decision Criteria
Ask these questions in order. Stop at the first one that settles it.
Good fits for shared memory
- Streaming audio and video. An
AudioWorkletcannot wait for messages without risking glitches. A single-producer single-consumer ring buffer in shared memory lets the main thread or a worker feed samples with predictable latency. - WebAssembly threads. Compiled C, C++, or Rust code that uses pthreads needs a shared linear memory. In that case you have no alternative.
- Cancellation and progress flags. A long computation can poll a shared
Int32Arrayslot to learn it should stop, or write its progress there for the main thread to read on each animation frame. - Parallel work on one large data set. Several workers can process separate slices of one image or matrix without copying it out and back.
- Synchronous calls across threads. A worker can make a request and then block in
Atomics.waituntil the reply arrives. Some tools use this to run synchronous APIs on top of asynchronous ones.
Poor fits
- Structured data. Shared memory holds bytes. To share objects, strings, or maps, you have to design a binary layout, encode into it, and decode out of it. Most of the time this costs more than cloning would.
- Infrequent, request-response work. If a worker gets one job a second, the clone cost is too small to measure, and messages are much easier to reason about.
- Sites that cannot be cross-origin isolated.
Cross-Origin-Embedder-Policy: require-corpblocks cross-origin resources that don't opt in. That can break third-party ads, embeds, and some login popups. If you can't fix those, you can't useSharedArrayBufferin the browser.
Failure Modes Unique to Shared Memory
Message passing has bugs too, but they are mostly logic bugs. Shared memory adds bugs that depend on timing.
| Failure mode | Cause | How it shows up |
|---|---|---|
| Data race | A plain read or write where an atomic one was needed | Lost updates, torn values, results that differ between runs |
| Deadlock | Two threads each wait for a lock the other holds, or `wait` without a matching `notify` | A worker hangs forever with no error |
| Frozen UI | Blocking on the main thread | `Atomics.wait` throws in browser windows; a spinning CAS loop freezes the page |
| Torn record | Publishing a multi-field record without an atomic "ready" flag written last | The reader sees half-old, half-new data |
| Layout drift | Two files disagree on byte offsets | Silent corruption that is hard to trace |
The Hybrid Pattern
In practice the strongest designs combine both mechanisms. Use messages for control: starting jobs, configuration, errors, and results that are objects. Use shared memory for the bulk data and for the few integers that have to be seen immediately. Put the layout in one place and publish completion with an atomic store, so the reader never sees a half-written buffer.
const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
const LENGTH = 1_000_000;
const HEADER_BYTES = 8; // Int32 status at index 0, padding keeps Float64 aligned
const READY = 1;
function views(sab) {
return {
status: new Int32Array(sab, 0, 2),
samples: new Float64Array(sab, HEADER_BYTES, LENGTH),
};
}
if (isMainThread) {
const sab = new SharedArrayBuffer(HEADER_BYTES + LENGTH * Float64Array.BYTES_PER_ELEMENT);
const { status, samples } = views(sab);
const worker = new Worker(__filename, { workerData: sab });
worker.on('message', (msg) => {
if (msg.type === 'done' && Atomics.load(status, 0) === READY) {
console.log(`filled ${msg.count} samples, last = ${samples[LENGTH - 1].toFixed(3)}`);
worker.terminate();
}
});
} else {
const { status, samples } = views(workerData);
for (let i = 0; i < samples.length; i++) {
samples[i] = Math.sqrt(i);
}
Atomics.store(status, 0, READY); // publish after all plain writes
parentPort.postMessage({ type: 'done', count: samples.length });
}The data itself moves with no copy. The control message is a small object, and the atomic status store guarantees that the plain writes to samples are visible once the main thread loads READY. The views function is the only place that defines the layout, which prevents layout drift.
Summary of the Trade-off
Message passing gives you isolation: each agent owns its data, and the event loop serializes all access. You pay for that with copies and with latency that depends on the receiver's event loop. Transfer removes the copy and keeps the isolation. Shared memory removes both costs but gives up the isolation. You then have to reconstruct safety yourself with atomics, locks, and careful layouts, and in browsers you also have to meet the cross-origin isolation requirements.
Exercise
A photo editor sends a 40 MB image buffer to a worker, the worker applies a filter, and sends the result back. The main thread never reads the image while the worker is working. Which mechanism fits best, and why not SharedArrayBuffer?
Show answer
Transfer the ArrayBuffer in each direction. Only one side uses the data at a time, so transfer gives zero-copy handoff with no races, no Atomics, and no COOP/COEP requirement. SharedArrayBuffer would add synchronization work and deployment constraints without any benefit.
Exercise
An AudioWorklet must receive 128-sample blocks from a worker every 2.9 ms and must never stall. Why is postMessage a poor fit, and what should you build instead?
Show answer
Each message waits in the worklet's task queue and has per-message overhead, so delivery timing is unpredictable at that rate. Use a single-producer single-consumer ring buffer in a SharedArrayBuffer with atomic read and write indices. The worklet reads whatever samples are available without blocking.
Exercise
In the hybrid example, the worker writes samples with plain assignments. What would go wrong if it called postMessage but skipped Atomics.store(status, 0, READY), and the main thread read samples without the Atomics.load check?
Show answer
Nothing would guarantee that the plain writes are visible to the main thread when it reads, so the code would depend on host-specific behavior and could see stale or partial data. The atomic store after the writes and the atomic load before the reads create the happens-before edge that makes all the sample writes visible.