Worker threads
Move CPU-heavy work off the event loop with worker_threads, pass data by copy, transfer or sharing, and why thread pools like piscina exist.
Worker threads
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Worker threads run JavaScript on other OS threads in the same process, each with its own event loop and V8 heap. They are for CPU-bound work, not I/O, which the event loop already handles.
- Data moves by `postMessage` with structured clone (a copy), by transfer (`postMessage(msg, [arrayBuffer])`, which moves ownership and empties the sender's buffer), or by sharing a `SharedArrayBuffer`.
- Shared memory needs `Atomics` for safe updates: four workers each doing `Atomics.add` 10,000 times produce exactly 40,000, where plain `+= 1` would lose updates.
- Starting a worker costs tens of milliseconds and memory, so reuse them through a pool such as `piscina` rather than spawning one per task.
- Handle three events: `message`, `error` (an uncaught exception in the worker) and `exit`. An error ends the worker and the main thread must decide what to do.
When the event loop is the bottleneck
Node’s single JavaScript thread handles thousands of connections because I/O is delegated: while a query or file read is in flight, the thread serves other work (see blocking vs non-blocking I/O). That breaks down when the work is JavaScript itself. A loop that spends 400 ms hashing or resizing an image holds the thread for 400 ms, and everything else waits.
A worker thread is a second JavaScript thread, started from the first. It has its own event loop and its own V8 heap, so a long computation there does not block the main thread. Workers are for CPU-bound work. For I/O they add cost and no benefit.
A worker in one file
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
if (isMainThread) {
const run = (n) => new Promise((resolve, reject) => {
const w = new Worker(new URL(import.meta.url), { workerData: { n } });
w.once('message', resolve);
w.once('error', reject);
w.once('exit', (c) => c !== 0 && reject(new Error(`exit ${c}`)));
});
console.log(await Promise.all([run(38), run(38), run(38)]));
} else {
parentPort.postMessage(fib(workerData.n));
}
The same file is the main program and the worker, split by isMainThread. workerData is the starting input, and parentPort.postMessage sends the result back. On my 10-core machine, three fib(38) calls in parallel finished in about 221 ms, almost the same as one on the main thread (204 ms), and a timer kept ticking while they ran. Three in the main thread would have taken about 600 ms and frozen the loop.
Three ways to move data
-
Copy (structured clone).
postMessage(obj)clones the object. Safe, but costly for big data. -
Transfer.
postMessage({ buf }, [buf])moves anArrayBufferto the other thread with no copy. The sender’s buffer is left detached:const ab = new ArrayBuffer(1024); worker.postMessage({ buf: ab }, [ab]); console.log(ab.byteLength); // 0 -
Share. A
SharedArrayBufferis visible to both threads at once. That is fast and dangerous, because unsynchronised writes race.Atomicsgives atomic operations:const sab = new SharedArrayBuffer(4); const counter = new Int32Array(sab); // four workers each run: for (let i = 0; i < 10000; i++) Atomics.add(c, 0, 1); console.log(Atomics.load(counter, 0)); // 40000
Functions and most class instances cannot be cloned. Pass plain data, typed arrays and Map/Set.
Errors and lifecycle
An uncaught exception inside a worker fires error on the Worker object and terminates that worker (exit code 1). A worker that never finishes stays alive until you terminate() it. A message handler that never gets a reply can leave the main thread waiting, so pair requests with timeouts or abort signals.
Pools: do not spawn per task
Creating a worker takes real time and memory, because each one boots its own V8 isolate and Node environment. Spawning one per request is the typical first mistake. Keep a fixed set of workers and queue tasks onto them, which is what piscina does:
import Piscina from 'piscina';
const pool = new Piscina({ filename: new URL('./task.mjs', import.meta.url).href, maxThreads: 2 });
console.log(await Promise.all([1, 2, 3, 4].map((i) => pool.run({ a: i, b: 10 }))));
// [ 11, 12, 13, 14 ]
// task.mjs: export default ({ a, b }) => a + b;
I ran this with piscina 5. The pool sizes itself and queues work for you.
What the video covers
ByteMonk’s April 2025 video is chaptered: why worker threads matter, CPU-heavy tasks blocking the event loop (0:57), libuv as Node’s hidden thread pool (1:44), async/await and non-blocking I/O (3:17), why libuv threads cannot run JavaScript (5:01), worker threads as true parallelism (5:44), and a code example (7:19). It is a short overview that motivates the feature well. It does not, going by its chapters, get into transfer lists, SharedArrayBuffer/Atomics, or pools, so those are carried above. I could not read a transcript.
Where this fits
Workers sit between child processes (isolated, heavier) and the cluster module (many server copies). They are the usual answer once profiling shows a CPU hot spot. Typed-array background is in typed arrays and ArrayBuffer.
Check yourself
A route computes a PDF thumbnail in pure JavaScript for 400 ms and the server stalls for everyone. Why, and what is the fix?
The computation runs on the main thread and blocks the event loop, so no other request is served during those 400 ms. Move it to a worker thread (usually through a pool), and the main thread stays free to handle requests while the worker computes.
Should you use a worker thread to speed up 50 concurrent database queries?
No. Queries are I/O. The event loop and libuv already run them concurrently without blocking, and a worker would add copying and startup costs. Workers help only when JavaScript itself is the bottleneck, like hashing, parsing, image processing, or heavy math.
What happens to an `ArrayBuffer` after you pass it in a transfer list, and why use that?
Ownership moves to the receiving thread and the sender's buffer becomes empty; `byteLength` read back as 0 in my test. It avoids copying large binary data, at the price that the sender can no longer use it.
How do worker threads differ from child processes?
Threads live inside one process and can share memory through `SharedArrayBuffer`, and are cheaper to start. Child processes are separate programs with separate memory, stronger isolation, and can run non-Node commands. Choose threads for in-process CPU work and processes for isolation or external tools.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.