How to Run CPU-Heavy Work in a Worker Thread in Node.js
Run CPU-heavy work in a worker thread in Node.js 24 so the event loop stays free: a promise wrapper, a reusable pool, transferable buffers and error handling.

Node.js handles thousands of connections on one thread because almost everything it does is waiting: for a socket, a file, a database. That model breaks the moment your code does real computation. Hashing a large file, resizing an image, parsing a huge JSON document or computing a report all occupy the thread, and while they run, no other request is served, no timer fires and health checks fail. The answer is to run CPU-heavy work in a worker thread, which is a separate JavaScript thread with its own event loop, started from the node:worker_threads module. This post builds the pattern from the smallest example to a reusable pool, using Node.js 24, and covers how data crosses the boundary, how errors travel back and when a worker is not the right tool. For the browser equivalent, see processing a large array without freezing the UI.
See the problem first
A synchronous loop of enough iterations blocks everything else, including a timer that should fire every ten milliseconds.
const started = Date.now();
setTimeout(() => {
console.log(`timer fired after ${Date.now() - started >= 100 ? "100+" : "<100"} ms`);
}, 10);
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(38));39088169
timer fired after 100+ msThe timer was due after 10 milliseconds and ran only after the computation returned, which on typical hardware takes far longer. The result, 39,088,169, is the 38th Fibonacci number. In a server the same blocking would delay every in-flight request by that long.
The smallest worker
A worker file receives a message, computes and posts the answer back. The main file starts it, sends the input and listens for the reply.
import { parentPort } from "node:worker_threads";
function fib(n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
parentPort.on("message", (n) => {
parentPort.postMessage(fib(n));
});import { Worker } from "node:worker_threads";
const worker = new Worker(new URL("./worker.js", import.meta.url));
worker.once("message", (result) => {
console.log("fib(38) =", result);
worker.terminate();
});
const timer = setInterval(() => console.log("event loop is free"), 100);
worker.postMessage(38);
worker.once("exit", () => clearInterval(timer));event loop is free
event loop is free
fib(38) = 39088169The number of event loop is free lines depends on how long the computation takes. The point is that they appear at all: the main thread kept running its interval while the worker computed. Messages are copied between threads using the structured clone algorithm, which supports numbers, strings, arrays, plain objects, maps, sets, typed arrays and a few more types, but not functions.
Wrap the worker in a promise
Callers want await compute(38), not event handlers. Create a worker per call, resolve on the first message, reject on an error and always terminate the worker.
import { Worker } from "node:worker_threads";
export function runInWorker(file, input) {
return new Promise((resolve, reject) => {
const worker = new Worker(file, { workerData: input });
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 { parentPort, workerData } from "node:worker_threads";
parentPort.postMessage(workerData * workerData);import { runInWorker } from "./run-in-worker.js";
console.log(await runInWorker(new URL("./square-worker.js", import.meta.url), 12));144workerData carries the input at startup, so the worker needs no message handler. Starting a worker costs a new JavaScript environment, which is measured in tens of milliseconds, so this form suits jobs that last much longer than that, such as a report or an image batch. For many short jobs, reuse workers.
Reuse workers with a small pool
A pool starts a fixed number of workers once and hands them jobs. The number should not exceed the available CPU cores, which os.availableParallelism() reports in Node.js 18.14 and later.
import { Worker } from "node:worker_threads";
import { availableParallelism } from "node:os";
export class WorkerPool {
#idle = [];
#queue = [];
constructor(file, size = availableParallelism()) {
for (let i = 0; i < size; i++) this.#idle.push(new Worker(file));
}
run(input) {
return new Promise((resolve, reject) => {
this.#queue.push({ input, resolve, reject });
this.#dispatch();
});
}
#dispatch() {
while (this.#idle.length > 0 && this.#queue.length > 0) {
const worker = this.#idle.pop();
const { input, resolve, reject } = this.#queue.shift();
const done = () => {
worker.off("message", onMessage);
worker.off("error", onError);
this.#idle.push(worker);
this.#dispatch();
};
const onMessage = (value) => { done(); resolve(value); };
const onError = (error) => { done(); reject(error); };
worker.once("message", onMessage);
worker.once("error", onError);
worker.postMessage(input);
}
}
async close() {
await Promise.all(this.#idle.map((w) => w.terminate()));
}
}Each job takes an idle worker, listens for one reply, and returns the worker to the idle list afterward, which starts the next queued job. After an error event the worker is no longer usable in practice, so a production pool replaces it with a fresh one instead of returning it. Mature libraries such as Piscina implement all of this, including task cancellation and resource limits, and are worth adopting before you maintain your own.
Sharing data without copying
Copying a 200 MB buffer to a worker and back costs time and memory. Two features avoid it. A transfer list moves ownership of an ArrayBuffer: after postMessage(buffer, [buffer]), the sender's copy is detached and unusable, and the worker owns the memory. A SharedArrayBuffer is visible to both threads at once, and Atomics coordinates reads and writes.
import { Worker } from "node:worker_threads";
const worker = new Worker(
`const { parentPort } = require("node:worker_threads");
parentPort.on("message", (buf) => parentPort.postMessage(buf.byteLength));`,
{ eval: true }
);
const data = new Uint8Array(1024).buffer;
worker.once("message", (size) => {
console.log("worker saw", size, "bytes; sender sees", data.byteLength);
worker.terminate();
});
worker.postMessage(data, [data]);worker saw 1024 bytes; sender sees 0After the transfer, the sender's buffer reports a length of zero because it is detached. Use transfer for one-way handoffs and shared memory only when both sides must work on the same bytes, since shared memory needs careful synchronization.
Errors cross the boundary
An exception thrown inside the worker and not caught fires the error event on the main thread, with the original error's message and stack. A worker that exits without replying fires exit with a non-zero code. Handle both, as the wrapper above does. For jobs that can fail in expected ways, catch inside the worker and post a result object with an ok flag, which keeps expected failures out of the error channel.
When a worker is not the answer
Workers do not help with waiting. A request that spends 200 milliseconds awaiting a database is not CPU-bound, and the event loop already handles it well. They also do not help when the computation is tiny, since the cost of messaging exceeds the saving. And they share nothing implicitly, so a large in-memory structure the work depends on has to be loaded again in each worker. For work that is heavy and independent, such as per-request image processing, a worker pool is exactly right. For work that is better done elsewhere entirely, such as video encoding, a separate service or a job queue gives you scaling and isolation that threads do not.
Keeping the main thread honest
Moving work to a thread changes where the cost shows up, and it is worth knowing where. Each worker has its own heap, so ten workers each loading a 100 MB lookup table use a gigabyte. Each message you send costs a copy, so a design that sends many small messages can spend more time messaging than computing. A good workflow is to measure first: confirm that the event loop is actually blocked, for example with perf_hooks.monitorEventLoopDelay, then move the single hottest function, then measure again. If the delay does not drop, the problem was somewhere else.
Be careful with ordering. A pool runs jobs in parallel, so results may finish out of order. Callers that need ordered results should keep the promise each run call returned and await them in sequence, which Promise.all does for you. Jobs that must not run at the same time, such as two writes to the same file, should not go through a pool at all, or should be serialized with a lock before they are submitted.
Shutting down cleanly
Workers keep the process alive until they exit, so a program that creates a pool and forgets to close it never terminates. Call terminate() on every worker when the work is done, and on a server, do it in your shutdown handler after the last request drains. terminate() returns a promise and stops the thread without waiting for pending work, so finish the in-flight jobs first if their results matter. Calling worker.unref() is the alternative when the pool should not by itself prevent the process from exiting, for example in a command line tool where the main flow decides when the program is done.
Testing code that uses workers
Test the computation as an ordinary function, outside any thread, and keep the worker file a thin wrapper that reads a message, calls that function and posts the result. The wrapper then needs only one integration test: start it, send an input and check the output, plus one that sends an input which makes the function throw and checks that the promise rejects. Splitting it this way keeps the bulk of your tests fast and deterministic, and leaves thread behavior, which is the hard part to debug, covered by a handful of focused tests.


