Worker Threads in Node: Parallel JavaScript, Messages and Shared Memory
Run CPU-heavy JavaScript in parallel with node:worker_threads: when workers help, creating workers with workerData, messages and structured cloning, transferring buffers and MessagePorts, the worker environment, SharedArrayBuffer and Atomics, worker pools, and workers vs processes.
kvi5hnuCode Sprout team member8 min readOn this page
Node runs your JavaScript on one thread, which is ideal for I/O but leaves other CPU cores idle and lets a long computation freeze everything (article 123). Worker threads run JavaScript in parallel inside the same process. They follow the same model as browser web workers (article 120): each worker has its own memory and event loop, and threads communicate by passing messages rather than sharing variables, which avoids most of the classic multithreading bugs.
When workers help
- CPU-bound work: image or video processing, compression, parsing very large JSON or CSV files, hashing, cryptography in JavaScript, machine learning inference, or simulations. Split across workers, it can use every core.
- Keeping a server responsive: even one expensive computation on the main thread delays every other request. Moving it to a worker keeps the main thread free.
- Making blocking code non-blocking: a synchronous library you can't change can run in a worker while the main thread awaits a message.
Workers don't speed up I/O. Node's file and network operations are already asynchronous, so a database-heavy server gains nothing from them.

Creating workers
new Worker(filename, options) from node:worker_threads starts a thread that runs the given file. Pass input with the workerData option; the worker reads it from workerData and replies with parentPort.postMessage(). On the main thread, the Worker object emits message, error (an uncaught exception in the worker) and exit:
const { Worker } = require("node:worker_threads");
// Worker code is normally a separate file: new Worker("./primes-worker.js", ...)
// Here it is passed as a string with eval: true so the example is self-contained.
const workerCode = `
const { parentPort, workerData, threadId } = require("node:worker_threads");
const { from, to } = workerData;
let count = 0;
for (let n = Math.max(2, from); n < to; n++) {
let prime = true;
for (let d = 2; d * d <= n; d++) if (n % d === 0) { prime = false; break; }
if (prime) count++;
}
parentPort.postMessage({ from, to, count, threadId });
`;
function countPrimes(from, to) {
return new Promise((resolve, reject) => {
const worker = new Worker(workerCode, { eval: true, workerData: { from, to } });
worker.once("message", resolve);
worker.once("error", reject); // an exception thrown inside the worker
worker.once("exit", (code) => {
if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));
});
});
}
async function main() {
// Split one big job into 4 ranges that run in parallel on separate threads
const ranges = [[0, 250_000], [250_000, 500_000], [500_000, 750_000], [750_000, 1_000_000]];
const results = await Promise.all(ranges.map(([a, b]) => countPrimes(a, b)));
for (const r of results) console.log(`${r.from}-${r.to}: ${r.count} primes`);
console.log("total:", results.reduce((sum, r) => sum + r.count, 0));
}
main();
0-250000: 22044 primes
250000-500000: 19494 primes
500000-750000: 18700 primes
750000-1000000: 18260 primes
total: 78498
Wrapping each worker in a promise lets Promise.all wait for all of them. On a machine with four or more cores, the four ranges are computed at the same time, roughly four times faster than one thread.
Normally the worker is its own file: new Worker("./primes-worker.js") in CommonJS (a relative path is resolved against the current working directory, so path.join(__dirname, ...) is safer), or new Worker(new URL("./primes-worker.js", import.meta.url)) in ES modules. The eval: true option used here runs a string of code instead, which keeps the examples self-contained. A worker can also check isMainThread to let one file contain both sides, a pattern you'll often see in examples.
Messages: copy, transfer, or channel
const { Worker, MessageChannel } = require("node:worker_threads");
const code = `
const { parentPort } = require("node:worker_threads");
parentPort.on("message", (msg) => {
if (msg.type === "port") {
// A private channel handed over by the main thread
msg.port.on("message", (text) => msg.port.postMessage(text.toUpperCase()));
} else if (msg.type === "pixels") {
const px = new Uint8Array(msg.buffer); // the transferred memory, now ours
for (let i = 0; i < px.length; i++) px[i] = 255 - px[i];
parentPort.postMessage({ type: "pixels", buffer: msg.buffer }, [msg.buffer]); // send it back
} else if (msg.type === "date") {
parentPort.postMessage({ type: "date", isDate: msg.when instanceof Date, keys: [...msg.tags] });
}
});
`;
async function main() {
const worker = new Worker(code, { eval: true });
const reply = () => new Promise((resolve) => worker.once("message", resolve));
// 1. Structured clone: Dates, Sets and Maps survive the trip (functions would not)
worker.postMessage({ type: "date", when: new Date(0), tags: new Set(["a", "b"]) });
console.log(await reply());
// 2. Transfer an ArrayBuffer: moved, not copied
const pixels = new Uint8Array([0, 100, 255]);
worker.postMessage({ type: "pixels", buffer: pixels.buffer }, [pixels.buffer]);
console.log("after transfer, main thread sees length", pixels.length);
const back = await reply();
console.log("returned:", [...new Uint8Array(back.buffer)]);
// 3. A MessageChannel: transfer one port to the worker, keep the other
const { port1, port2 } = new MessageChannel();
worker.postMessage({ type: "port", port: port2 }, [port2]);
port1.postMessage("private channel");
port1.once("message", (text) => {
console.log("via port:", text);
port1.close();
worker.terminate();
});
}
main();
{ type: 'date', isDate: true, keys: [ 'a', 'b' ] }
after transfer, main thread sees length 0
returned: [ 255, 155, 0 ]
via port: PRIVATE CHANNEL
- Copying:
postMessage(value)serializes the value with the structured clone algorithm, the same onestructuredClone()uses (article 116). Unlike JSON, it handlesDate,Map,Set,RegExp, typed arrays,BigIntand circular references. Functions, class prototypes, symbols and DOM-like objects can't be cloned and cause aDataCloneError, so instances arrive as plain objects. - Transferring: a second argument, the transfer list, moves
ArrayBuffers andMessagePorts instead of copying them. A transfer is fast even for huge buffers, but the sender loses access: its view now has length 0. - Channels:
new MessageChannel()creates two connectedMessagePorts. Transfer one to a worker to set up a dedicated line, for example for one kind of message or for direct worker-to-worker communication without going through the main thread. Close ports you no longer need, because an open port keeps its thread alive.
Each message is copied or moved, never shared, so neither side can see the other modify an object halfway.
The worker's environment
Inside a worker, almost everything works as on the main thread: require and import, fs, fetch, timers and its own event loop. The differences:
isMainThreadisfalse;parentPortandworkerDataare available.threadIdis a number above 0.process.envis a copy of the parent's environment by default. Changes stay in the worker.process.exit()stops only that worker, which then emitsexit. From the main thread,worker.terminate()stops it.- Process-wide operations, such as changing the working directory or handling signals, belong to the main thread.
consoleoutput from workers is forwarded to the main thread asynchronously.- Each worker has a separate V8 heap;
resourceLimitscan cap its memory.
Shared memory and Atomics
One kind of memory can be shared: a SharedArrayBuffer. Posting it gives the worker access to the same bytes, not a copy. That brings back the classic multithreading problem, race conditions: counters[0]++ reads, adds and writes in separate steps, so two threads can read the same old value and one increment is lost.
const { Worker } = require("node:worker_threads");
const code = `
const { workerData, parentPort } = require("node:worker_threads");
const { counters, useAtomics } = workerData;
for (let i = 0; i < 1_000_000; i++) {
if (useAtomics) Atomics.add(counters, 0, 1); // indivisible read-modify-write
else counters[0]++; // read, add, write: can interleave
}
parentPort.postMessage("done");
`;
function run(useAtomics) {
const counters = new Int32Array(new SharedArrayBuffer(4)); // memory shared by all threads
const workers = Array.from({ length: 4 }, () =>
new Worker(code, { eval: true, workerData: { counters, useAtomics } }));
return Promise.all(workers.map((w) => new Promise((resolve) => w.once("message", resolve))))
.then(() => counters[0]);
}
async function main() {
const plain = await run(false);
const atomic = await run(true);
console.log("expected:", 4_000_000);
console.log("Atomics.add:", atomic);
// The plain total varies from run to run; on a multi-core machine it is almost always too low
console.log("plain ++ never exceeds the expected total:", plain <= 4_000_000);
}
main();
expected: 4000000
Atomics.add: 4000000
plain ++ never exceeds the expected total: true
Atomics.add, Atomics.load, Atomics.store, Atomics.compareExchange and the other Atomics functions perform each operation indivisibly. Atomics.wait and Atomics.notify let threads block until a value changes, which is the basis for locks. Shared memory makes sense for large numeric data processed in place, such as pixel buffers or matrices. For anything else, use messages, which are much harder to get wrong.
Waiting without blocking: waitAsync and pause
Atomics.wait blocks the calling thread, so browsers forbid it on the main thread. Atomics.waitAsync returns a promise instead, which works anywhere. Atomics.pause() (ES2027) is a hint to the CPU inside short spin-wait loops. It makes spinning cheaper but doesn't sleep.
// Atomics.waitAsync waits on shared memory without blocking the thread,
// so it also works on the main thread. Atomics.pause() is a CPU hint for
// short spin-wait loops.
const shared = new Int32Array(new SharedArrayBuffer(4));
const { async, value } = Atomics.waitAsync(shared, 0, 0); // wait while shared[0] === 0
console.log("async:", async);
value.then((outcome) => console.log("woken:", outcome, "value is now", Atomics.load(shared, 0)));
setTimeout(() => {
Atomics.store(shared, 0, 42);
Atomics.notify(shared, 0); // wakes the waiter
}, 10);
let spins = 0;
while (spins < 100) { Atomics.pause(); spins++; } // a polite busy-wait
console.log("spun", spins, "times");
async: true
spun 100 times
woken: ok value is now 42
Pools and practical advice
- Reuse workers. Starting a worker takes milliseconds and several megabytes, so create a pool, about
os.availableParallelism()workers, once at startup, and send jobs to free workers, as the browser example in article 121 did. Libraries such as Piscina provide production-ready pools for Node. - Move only the heavy part. Messages have a cost: copying a 100 MB object can take longer than the computation. Transfer buffers, or send just the inputs.
- Handle
errorandexit. An exception in a worker doesn't crash the main thread, but you must notice it and reject the job, ascountPrimesdoes.
Threads or processes?
| Worker threads | Child processes (fork, article 131) | |
|---|---|---|
| Startup and memory | lighter (same process) | heavier (a whole new Node) |
| Data exchange | structured clone, transfer, shared memory | JSON or advanced serialization over IPC |
| Isolation | a native crash kills the whole process | fully isolated |
| Can run | JavaScript only | any program |
Use workers for CPU-bound JavaScript; use processes for running other programs, stronger isolation, or scaling a server across cores (node:cluster).
Common questions
Will worker threads make my Express API faster?
Only if the slow part is CPU-bound JavaScript. Database queries, HTTP calls and file I/O are already non-blocking, and workers add messaging overhead to them.
Why can't I send a class instance or a function to a worker?
Messages are structured clones. Functions can't be cloned, and class instances arrive as plain objects without their prototype. Send plain data and rebuild objects on the other side.
Why does the process stay alive after the work is done?
A worker, or an open MessagePort, keeps the process running. End workers with worker.terminate() or let them finish their code, and close ports you created.
Summary
new Worker(file, { workerData })runs JavaScript on another thread with its own heap and event loop; the worker replies withparentPort.postMessage, and the main thread listens formessage,errorandexit.- Messages are copied with structured clone. The transfer list moves
ArrayBuffers andMessagePorts;MessageChannelcreates extra channels. SharedArrayBufferis shared memory; useAtomicsto avoid race conditions.- Use a pool of reused workers for CPU-bound JavaScript; use processes for isolation or other programs.
Review quiz
You've finished Part 16: Server-Side JavaScript with Node. Test yourself with the Part 16 review quiz: 20 questions on arguments and modules, the event loop, Buffers, events, streams and backpressure, files, HTTP, TCP, child processes and worker threads.
Practice Questions
A server resizes uploaded images in JavaScript, and all requests slow down during uploads. How do worker threads help?
Answer
Resizing is CPU-bound, so it blocks the main thread's event loop and delays every request. Sending the image buffer, transferred rather than copied, to a pool of workers does the resizing on other cores, while the main thread keeps handling requests.
What does this print, and why?
const buf = new ArrayBuffer(8);
worker.postMessage(buf, [buf]);
console.log(buf.byteLength);
Answer
0. Listing the buffer in the transfer list moves it to the worker, and the sender's buffer is detached.
Two workers each run shared[0]++ a million times on the same Int32Array over a SharedArrayBuffer. Why is the final value usually below two million, and how do you fix it?
Answer
++ is a separate read, add and write. When both threads read the same value before either writes, one increment is lost: a race condition. Use Atomics.add(shared, 0, 1), which performs the whole update indivisibly.
Write the worker side of a job that receives a number n through workerData and sends back n * n.
Answer
const { workerData, parentPort } = require("node:worker_threads");
parentPort.postMessage(workerData * workerData);
The main thread creates it with new Worker(file, { workerData: 12 }) and listens with worker.once("message", ...).
Previous: TCP Networking with net and Running Child Processes
Next: JavaScript Tooling: Linting with ESLint and Formatting with Prettier

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.