How to Use Worker Threads for CPU-Bound Work
Move CPU-heavy work off the Node.js event loop with node:worker_threads: start a worker, pass data and results, handle errors and build a small worker pool.

Node.js runs your JavaScript on one thread. That is fine for work that mostly waits, such as database queries and HTTP calls, because the event loop serves other requests while the operating system does the waiting. It is a problem for work that computes: hashing a large file, parsing a huge document, resizing an image, running a tight numeric loop. While that code runs, nothing else on the thread runs, so timers fire late, requests queue up and the server looks frozen. Worker threads, in [node:worker_threads](https://nodejs.org/api/worker_threads.html), run JavaScript on separate threads so heavy work does not block the main one. This post shows the problem, a first worker, how to send data in and results out, how errors behave, and a small pool for repeated jobs. The samples use ES modules on Node.js 26.
Seeing the block
First, the problem itself. A server that computes inline cannot answer anything else during the computation.
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
const heartbeat = setInterval(() => console.log("heartbeat"), 100);
console.log("start");
console.log("fib(40) =", fib(40));
console.log("done");
clearInterval(heartbeat);start
fib(40) = 102334155
doneNo heartbeat line is ever printed, even though the timer was set to fire every 100 milliseconds. The recursive fib(40) takes the thread for as long as it takes, the timer callbacks are queued behind it, and clearInterval() runs before any of them get a turn. That is what a CPU-bound task does to an event loop. In a web server the heartbeat is every other request.
A first worker
A worker is a second JavaScript instance with its own event loop and its own memory heap, running in the same process. You give it a file to run. Messages are the only way the two sides talk by default.
Here is the worker file. It reads its input from workerData, computes and sends the answer back with parentPort.postMessage().
import { parentPort, workerData } from "node:worker_threads";
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
parentPort.postMessage(fib(workerData.n));And the main file starts it and listens for the result.
import { Worker } from "node:worker_threads";
const heartbeat = setInterval(() => console.log("heartbeat"), 100);
const worker = new Worker(new URL("./fib-worker.js", import.meta.url), {
workerData: { n: 40 },
});
worker.on("message", (result) => {
console.log("fib(40) =", result);
clearInterval(heartbeat);
});heartbeat
heartbeat
heartbeat
fib(40) = 102334155The number of heartbeat lines depends on how long the computation takes on your machine, so the count will differ. What matters is that they appear at all: the main thread stayed free to run its timer while the worker computed. The workerData option copies a value into the worker when it starts. new URL(..., import.meta.url) resolves the worker file next to the current module, which works for ES modules and does not depend on the working directory.
The worker exits on its own when it has nothing left to do, here after posting its single message and finishing the script. The main process also exits once the interval is cleared and the worker has ended.
Wrap it in a promise
Event handlers are awkward to use. Most code wants await. A small wrapper turns one job into a promise and handles all three outcomes: a result, an error and an unexpected exit.
import { Worker } from "node:worker_threads";
export function runWorker(file, data) {
return new Promise((resolve, reject) => {
const worker = new Worker(file, { workerData: data });
worker.once("message", resolve);
worker.once("error", reject);
worker.once("exit", (code) => {
if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));
});
});
}import { runWorker } from "./run-worker.js";
const file = new URL("./fib-worker.js", import.meta.url);
const [a, b] = await Promise.all([
runWorker(file, { n: 30 }),
runWorker(file, { n: 35 }),
]);
console.log(a, b);832040 9227465The two jobs run on two threads at the same time, and Promise.all() waits for both. once is used instead of on because a job produces one result. The exit handler matters: if a worker is killed or calls process.exit(1), neither message nor error fires, and without it your promise would never settle.
How errors behave
An uncaught exception inside a worker does not crash the main thread. It ends that worker and raises an error event on the Worker object in the parent.
import { parentPort, workerData } from "node:worker_threads";
if (workerData.n < 0) {
throw new RangeError("n must not be negative");
}
parentPort.postMessage(workerData.n * 2);import { runWorker } from "./run-worker.js";
try {
await runWorker(new URL("./failing-worker.js", import.meta.url), { n: -1 });
} catch (error) {
console.log(error.name + ": " + error.message);
}RangeError: n must not be negativeThe error object arrives in the parent with its original class and message, so you can handle it as you would a local one. Its stack trace points into the worker file. Resource limits are the other failure mode. A worker that allocates too much hits its own heap limit and is terminated with an ERR_WORKER_OUT_OF_MEMORY error, which you can tune with the resourceLimits option.
What crosses the boundary
Messages are copied using the structured clone algorithm, the same one structuredClone() uses. Numbers, strings, plain objects, arrays, Map, Set, Date and typed arrays all copy. Functions and class instances with methods do not: the data arrives, the behaviour does not. Copying a large object is itself work, so sending a 200 MB array to a worker can cost more than the computation.
For large binary data you can transfer an ArrayBuffer instead of copying it. Ownership moves to the receiver, and the sender's buffer becomes empty.
import { Worker } from "node:worker_threads";
const worker = new Worker(
`
const { parentPort } = require("node:worker_threads");
parentPort.once("message", (buffer) => {
parentPort.postMessage(buffer.byteLength);
});
`,
{ eval: true },
);
const buffer = new ArrayBuffer(1024);
console.log("before:", buffer.byteLength);
worker.postMessage(buffer, [buffer]);
console.log("after:", buffer.byteLength);
worker.on("message", (size) => {
console.log("worker saw:", size);
worker.terminate();
});before: 1024
after: 0
worker saw: 1024The second argument to postMessage() is the transfer list. After the call the original buffer is detached, so its byteLength is 0, and the worker has the 1024 bytes without a copy. The eval: true option runs the string as the worker's script, which keeps this sample in one file. In real code use a separate file. When many workers need to read and write the same memory at once, a SharedArrayBuffer is the tool, covered in How to Share Memory Between Worker Threads.
A small worker pool
Starting a worker costs time and memory, since each one boots a new JavaScript environment. Creating one per task is wasteful when tasks are small and frequent. A pool starts a fixed number of workers once and reuses them.
import { parentPort } from "node:worker_threads";
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
parentPort.on("message", ({ id, n }) => {
parentPort.postMessage({ id, result: fib(n) });
});import { Worker } from "node:worker_threads";
import { availableParallelism } from "node:os";
export class Pool {
#idle = [];
#queue = [];
#pending = new Map();
#nextId = 0;
constructor(file, size = availableParallelism()) {
for (let i = 0; i < size; i++) {
const worker = new Worker(file);
worker.on("message", ({ id, result }) => {
this.#pending.get(id)(result);
this.#pending.delete(id);
this.#idle.push(worker);
this.#next();
});
this.#idle.push(worker);
}
}
run(n) {
return new Promise((resolve) => {
this.#queue.push({ id: this.#nextId++, n, resolve });
this.#next();
});
}
#next() {
if (this.#idle.length === 0 || this.#queue.length === 0) return;
const worker = this.#idle.pop();
const { id, n, resolve } = this.#queue.shift();
this.#pending.set(id, resolve);
worker.postMessage({ id, n });
}
async close() {
await Promise.all(
[...this.#idle].map((worker) => worker.terminate()),
);
}
}import { Pool } from "./pool.js";
const pool = new Pool(new URL("./pool-worker.js", import.meta.url), 2);
const results = await Promise.all([20, 25, 30, 10].map((n) => pool.run(n)));
console.log(results);
await pool.close();[ 6765, 75025, 832040, 55 ]Four jobs go to a pool of two workers. The first two start at once and the other two wait in the queue until a worker reports back and becomes idle again. availableParallelism(), from node:os, is a sensible default pool size because it reports how many threads the machine can run in parallel. Results come back in the order of the input array because Promise.all() preserves order, whichever job finished first. This sample omits error handling and worker crashes for length. Production code must replace a dead worker and reject the job it was running. For real use, consider a maintained library such as Piscina, which implements this carefully.
When not to use a worker
I/O-bound work. Database calls, HTTP requests and file reads already run off the main thread in libuv. A worker adds cost and no benefit.
Tiny tasks. Message passing and copying take time. If the computation is shorter than the overhead of sending it, keep it inline.
When a native module already does it. Many built-in operations, such as
zlibandcryptofunctions with callbacks, already run on the libuv thread pool. Use those before writing your own worker.When one more process is simpler. For heavy, isolated jobs a separate process or a queue worker gives stronger isolation and can run on another machine. How to Run Background Jobs With BullMQ covers that route.


