Node.js Internals #4: Worker Threads
Part 4 of the Node.js Internals series. Part 2 showed that the libuv pool cannot run your JavaScript. Worker threads can. Every output below was run on Node v26.8.1 on a 12-core Mac.
The event loop from Part 1 has one weakness: a CPU-heavy function blocks everything. Worker threads fix that by giving you more JavaScript threads inside one process. Each worker is its own isolate: its own event loop, its own V8 heap, its own call stack.
Experiment 1: blocking vs workers
A deliberately slow function (fib(40)) plus a 10 ms timer that counts "heartbeats", so we can see whether the event loop stays alive:
1 task on main thread: 547 ms
4 tasks on main thread: 2149 ms, heartbeats during run: 0
4 tasks on 4 workers: 570 ms, heartbeats during run: 52
Four tasks on the main thread took four times as long and the timer never fired: zero heartbeats means the server could not have answered a single request for 2 seconds. Four workers finished in roughly the time of one task, and the loop kept beating (52 beats in 570 ms, close to the expected 57).
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads");
if (isMainThread) {
const w = new Worker(__filename, { workerData: 40 });
w.on("message", (result) => console.log(result));
} else {
parentPort.postMessage(fib(workerData));
}
Passing data: copy, transfer, or share
Workers do not share variables. Data crosses the boundary in one of three ways:
type Handoff =
| { kind: "copy"; how: "postMessage(value)"; cost: "proportional to size" }
| { kind: "transfer"; how: "postMessage(buf, [buf.buffer])"; cost: "near zero, sender loses it" }
| { kind: "share"; how: "SharedArrayBuffer"; cost: "zero, both sides see it" };
Measured with a 100 MB array:
copy: sender length after = 104857600 | 12.4 ms
transfer: sender length after = 0 | 0.007 ms
Copying (the structured clone algorithm) took about 12 ms, and the sender still owns its array. Transferring took 7 microseconds, but the sender's array is now length 0: ownership moved. Pick transfer for big one-way payloads such as image or file buffers.
Shared memory and why you need Atomics
A SharedArrayBuffer is the one thing two threads can both read and write. That is fast, and it brings the classic problem: counter++ is three steps (read, add, write), and two threads can interleave them. Four workers each incremented a counter one million times, once with plain ++ and once with Atomics.add:
expected: 4000000
plain counter++: 1173060
Atomics.add: 4000000
The plain counter lost about 70% of its updates. The result is different on every run, which is exactly what makes these bugs painful. Atomics.add performs the whole read-add-write as one indivisible step. The rule: shared memory is only safe through Atomics (or with a lock built from Atomics.wait and Atomics.notify).
What a worker costs
baseline process: 49 MB RSS
20 workers started and replied in 35 ms: 187 MB RSS
Roughly 7 MB of extra memory per idle worker on this machine, and startup in the low milliseconds each. Cheap compared with a process, but not free: do not spawn a worker per request. Create a small pool (about your CPU core count) and send it jobs.
Workers vs cluster vs child_process
worker_threads: threads in one process, can share memory, light. cluster: several full Node processes sharing a listening port, no shared memory, good for using all cores with an HTTP server. child_process: any external program or script, talks over pipes. Use workers for CPU-bound JavaScript, cluster (or just several containers) for scaling a server across cores, and child processes for running other programs.
Cheatsheet
| Problem | Tool |
|---|---|
| CPU-heavy JS blocks the loop (hashing, parsing, image work) | Worker thread, ideally from a pool |
| Waiting on I/O (DB, HTTP, files) | Nothing: async I/O already does not block |
| Big buffer to hand over once | Transfer it: postMessage(buf, [buf.buffer]) |
| Many threads updating one counter or flag | SharedArrayBuffer + Atomics |
| Small messages | Plain postMessage (copied) |
- A worker has its own heap and event loop, so a slow worker never freezes the main loop.
- Plain
++on shared memory loses updates. UseAtomics. - Transferred buffers are gone from the sender (length becomes 0).
- Workers help CPU-bound work. They do not speed up I/O-bound work.
Conclusion
Part 1 said never block the loop. This part is what to do when you genuinely have heavy computation: move it to a worker, move data by transfer when it is big, and treat shared memory as something that only Atomics can touch.
References
- Node.js worker_threads API
- MDN: SharedArrayBuffer
- MDN: Atomics
- Don't Block the Event Loop (or the Worker Pool), Node.js docs
Node.js Internals: Part 1 · Part 2 · Part 3 · Part 4 · Part 5