Sub topic 5
Shared Memory in Node.js worker_threads
This chapter assumes you can create a Worker with node:worker_threads, you know how typed arrays sit on top of an ArrayBuffer, and you can write Promise-based code. It covers how Node.js passes a SharedArrayBuffer between threads, how that differs from browsers, and the mistakes that commonly break shared-memory programs in Node.
How Node.js Threads Relate to Shared Memory
A Node.js process starts with one main thread that runs your script and its event loop. Each Worker you create gets its own V8 isolate, its own event loop, and its own global scope. Workers do not share JavaScript objects. Normally, data moves between them through the structured clone algorithm, which copies it.
A SharedArrayBuffer is the exception. When it crosses a thread boundary, the receiving thread gets a new SharedArrayBuffer object that points at the same block of memory. Neither side copies anything, so a write from one thread can be read by any other thread that holds a view on the buffer.
Node.js Compared with Browsers
The core API matches the browser's, but the surrounding rules are different.
| Concern | Browsers | Node.js |
|---|---|---|
| Availability of `SharedArrayBuffer` | Only when the page is cross-origin isolated (COOP and COEP headers) | Always available, with no headers or flags |
| Worker API | `new Worker(url)`, `self.onmessage` | `new Worker(filename)`, `parentPort`, `workerData` |
| Initial data for a worker | Must be sent with `postMessage` | Can be passed in the `workerData` option at construction |
| `Atomics.wait` on the main thread | Throws, because the main thread must not block | Allowed, but it freezes the main event loop |
| `crossOriginIsolated` global | Present | Not relevant to whether shared memory works |
Node.js treats the whole process as one trust boundary. It does not need the isolation checks that browsers use to block Spectre-style attacks across origins, so none of the header setup from the browser chapter applies here.
Shared Versus Copied: Seeing the Difference
The program below sends a plain ArrayBuffer and a SharedArrayBuffer to the same worker. The worker writes 7 into both. Only the shared write is visible back on the main thread.
// copy-vs-share.js
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const plain = new ArrayBuffer(4);
const shared = new SharedArrayBuffer(4);
const worker = new Worker(__filename);
worker.postMessage({ plain, shared });
worker.once('message', () => {
console.log('plain: ', new Int32Array(plain)[0]); // 0, the worker changed a copy
console.log('shared:', Atomics.load(new Int32Array(shared), 0)); // 7
worker.terminate();
});
} else {
parentPort.once('message', ({ plain, shared }) => {
new Int32Array(plain)[0] = 7;
Atomics.store(new Int32Array(shared), 0, 7);
parentPort.postMessage('done');
});
}Run it with node copy-vs-share.js. The worker's plain is a clone, so its write disappears with the worker. The worker's shared is a second handle on the same memory.
Three Ways to Hand Over the Buffer
workerData
workerData is cloned when the Worker is constructed. A SharedArrayBuffer inside it stays shared, and every other field is copied. This is the simplest choice when you know the buffer before you start the worker.
postMessage
worker.postMessage(sab) or parentPort.postMessage(sab) shares the buffer at any later time. Use it when the buffer is created after the worker starts, or when a worker allocates memory and wants to give it back to the main thread.
Typed array views
You can also post a view such as new Int32Array(sab, 8, 2). The receiver gets a fresh Int32Array with the same offset and length, backed by the same shared memory. This is a convenient way to give each worker its own window into one large buffer.
Splitting Work Across Workers
Many threads can write into one buffer without coordination as long as each thread writes only its own region. In this program, four workers fill disjoint slices of a Float64Array. The main thread waits for all of them to exit and then sums the result.
// parallel-fill.js
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const LENGTH = 1_000_000;
const WORKERS = 4;
function runWorker(data) {
return new Promise((resolve, reject) => {
const w = new Worker(__filename, { workerData: data });
w.once('error', reject);
w.once('exit', (code) => {
if (code === 0) resolve();
else reject(new Error(`worker exited with code ${code}`));
});
});
}
async function main() {
const sab = new SharedArrayBuffer(LENGTH * Float64Array.BYTES_PER_ELEMENT);
const chunk = Math.ceil(LENGTH / WORKERS);
const jobs = [];
for (let i = 0; i < WORKERS; i++) {
const start = i * chunk;
const end = Math.min(start + chunk, LENGTH);
jobs.push(runWorker({ sab, start, end }));
}
await Promise.all(jobs);
const data = new Float64Array(sab);
let sum = 0;
for (let i = 0; i < LENGTH; i++) sum += data[i];
console.log(sum); // 333332833333500000, the sum of i*i for i below 1,000,000
}
if (isMainThread) {
main().catch((err) => {
console.error(err);
process.exitCode = 1;
});
} else {
const { sab, start, end } = workerData;
const data = new Float64Array(sab);
for (let i = start; i < end; i++) {
data[i] = i * i;
}
}Plain writes are safe here because no two threads touch the same index, and the main thread reads only after every worker has exited. Waiting for a thread to finish gives the same "everything it wrote is now visible" handoff that a message does.
Many Writers, One Slot
The partitioning trick fails as soon as threads update the same location. The next program has four workers each add 1 to a shared counter 100,000 times.
// shared-counter.js
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 100000;
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: sab });
w.on('exit', () => {
if (++finished === WORKERS) {
console.log(Atomics.load(counter, 0)); // 400000
}
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
Atomics.add(counter, 0, 1);
}
}With Atomics.add, the total is always 400000. Replace that line with counter[0]++ and run it a few times. You will usually get a smaller number that changes between runs. The next chapter explains why ++ loses updates.
Interop with Node.js Buffer
Buffer.from(arrayBuffer, byteOffset, length) accepts a SharedArrayBuffer and returns a Buffer that views the same memory without copying. This lets you use Node's string and binary helpers on shared memory.
// buffer-view.js
const sab = new SharedArrayBuffer(16);
const buf = Buffer.from(sab);
buf.write('hi', 0, 'utf8');
console.log(new Uint8Array(sab)[0].toString(16)); // 68, the byte for 'h'
console.log(buf.buffer === sab); // trueBe careful with the reverse direction. Buffer.alloc and Buffer.allocUnsafe return memory backed by an ordinary ArrayBuffer, and small allocUnsafe buffers come from an internal pool. Posting such a buffer copies it and does not share it. If you need shared bytes, start from a SharedArrayBuffer.
Gotchas Specific to Node.js
Blocking the main thread is allowed but costly
Node.js lets the main thread call Atomics.wait. While it waits, timers, I/O callbacks, and 'message' and 'exit' events from workers cannot run. If the worker you are waiting for needs the main thread to answer a message first, the program deadlocks. Prefer Atomics.waitAsync or events on the main thread, and keep blocking waits inside workers.
Lifetime of the memory
Shared memory stays allocated while any thread holds a reference to it. Terminating a worker does not free a buffer that the main thread still uses. If a worker is terminated partway through a write, the memory may be left half-updated, so design your layout so that readers can detect incomplete data, for example with a status flag that is set last.
Unhandled worker errors
An exception thrown inside a worker emits 'error' on the Worker object and then 'exit' with a nonzero code. If you count 'exit' events to decide when results are ready, as shared-counter.js does, check the exit code too. Otherwise you will read a buffer that was never filled.
Sharing between two workers
Workers can share memory with each other without routing every update through the main thread. Pass the same SharedArrayBuffer in each worker's workerData, or create a MessageChannel, transfer one port to each worker, and post the buffer over that channel.
Exercise
A main thread creates const ab = new ArrayBuffer(8) and starts a worker with new Worker(file, { workerData: { ab } }). The worker sets new Float64Array(workerData.ab)[0] = 3.5 and exits. What does the main thread read from new Float64Array(ab)[0], and what one change makes it read 3.5?
Show answer
It reads 0, because workerData is cloned and the worker wrote into its own copy. Allocating the buffer as new SharedArrayBuffer(8) makes both threads view the same memory, so after the worker exits the main thread reads 3.5.
Exercise
In parallel-fill.js, why is it safe for workers to use plain assignment data[i] = i * i while shared-counter.js needs Atomics.add?
Show answer
In the fill program each worker writes a separate range of indexes and the main thread reads only after all workers have exited, so no two threads access the same element at the same time. In the counter program all workers do read-modify-write updates on index 0 concurrently, so non-atomic increments can overwrite each other and lose updates.
Exercise
A Node.js main thread calls Atomics.wait(flag, 0, 0) and waits for a worker to set the flag. The worker first sends a message asking the main thread for configuration, and sets the flag only after it gets the reply. What happens, and how would you fix it?
Show answer
The program deadlocks. The blocked main thread cannot run its event loop, so it never handles the worker's message, and the worker never sets the flag. Fix it by waiting on the main thread with Atomics.waitAsync or a 'message' event instead of a blocking wait, or by sending the configuration through workerData before the worker starts.