Programming languages · Advanced · 25 min
Run CPU-heavy work in Node.js with worker threads
By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · node:26 image (Debian)
You will prove that a slow calculation freezes a Node.js 26 HTTP server, then move that work into worker threads behind a small fixed-size pool so the server keeps answering while 100 jobs run.
On this page
Node.js runs your JavaScript on one thread. While a request handler is busy computing something, such as resizing an image, hashing a password with many rounds or parsing a large document, that thread cannot do anything else. Every other request waits, including the health check your load balancer uses to decide whether the server is alive.
Worker threads fix this for work that is heavy on the CPU. A worker is a second JavaScript thread inside the same process, with its own event loop and its own memory, talking to the main thread through messages. In this tutorial you build a small HTTP server with a slow /hash endpoint, measure how it freezes /health, then move the work into workers: first one worker per job, then a pool of a few workers that share a queue. Along the way you send data with workerData and postMessage, move a large ArrayBuffer without copying it, handle the error and exit events, and compare workers with child_process.
Everything uses Node's built-in modules, so there is nothing to install from npm. The files use the .mjs extension, which makes Node treat them as ES modules without a package.json.
Step 1 · Build a server that blocks
Create a demo folder and the function that does the slow work. It stands in for any CPU-bound job: it hashes the input with SHA-256 over and over until a time budget runs out, and returns the first 16 hex characters and how many rounds it managed. The input boom throws, so you can test error handling later:
mkdir -p ~/workers-demo
cd ~/workers-demo
cat > work.mjs <<'JS'
import { createHash } from 'node:crypto';
// Stand-in for real CPU work: hash the input again and again for `ms` milliseconds.
export function slowHash(input, ms) {
if (input === 'boom') throw new Error('cannot hash "boom"');
const started = performance.now();
let digest = Buffer.from(String(input));
let rounds = 0;
while (performance.now() - started < ms) {
digest = createHash('sha256').update(digest).digest();
rounds += 1;
}
return { digest: digest.toString('hex').slice(0, 16), rounds };
}
// Read ?ms= from a request: 2000 by default, never more than 5000.
export function parseMs(value) {
const ms = Number(value ?? 2000);
return Number.isFinite(ms) ? Math.min(Math.max(ms, 0), 5000) : 2000;
}
JSNow the server. It uses node:http directly so nothing hides what happens on the main thread. /hash calls slowHash inside the request handler:
cat > server-blocking.mjs <<'JS'
import http from 'node:http';
import { slowHash, parseMs } from './work.mjs';
const port = Number(process.env.PORT ?? 8001);
function send(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body) + '\n');
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/health') return send(res, 200, { status: 'ok' });
if (url.pathname === '/hash') {
const input = url.searchParams.get('input') ?? 'hello';
const ms = parseMs(url.searchParams.get('ms'));
return send(res, 200, slowHash(input, ms));
}
send(res, 404, { error: 'not found' });
});
server.listen(port, '127.0.0.1', () => {
console.log(`listening on http://127.0.0.1:${port}`);
});
JSStart it in your second terminal and leave it running:
cd ~/workers-demo
node server-blocking.mjsCheck it worked
The second terminal shows listening on http://127.0.0.1:8001. In your first terminal, call both endpoints. -w makes curl print how long the request took:
curl -s http://127.0.0.1:8001/health
curl -s -w 'took %{time_total}s\n' http://127.0.0.1:8001/hash/health answers {"status":"ok"} at once. /hash answers with something like {"digest":"5c1f0e7a9b2d4c66","rounds":1873402} and took 2.004s. The digest and the round count depend on how fast your CPU is.
Step 2 · Prove that /health stalls
Start a /hash request in the background, wait a moment so it has begun, then time /health:
curl -s -o /dev/null http://127.0.0.1:8001/hash & job=$!
sleep 0.3
curl -s -o /dev/null -w 'health answered in %{time_total}s\n' http://127.0.0.1:8001/health
wait "$job"The health check had nothing to compute, yet it waited for the hash to finish. Node only reads the next request off the socket when the current JavaScript returns to the event loop, and slowHash does not return for two seconds. Two users hashing at once would make a third wait four seconds, and so on. Making the handler async would not help: an async function still runs its synchronous loop on the same thread.
Check it worked
The output is something like health answered in 1.712s: the two seconds of hashing minus the 0.3 seconds you slept. Any value well above a few milliseconds shows the event loop was blocked.
Stop the server with Ctrl+C in the second terminal before you go on.
Step 3 · Run one job in a worker
A worker runs a separate file. It receives its starting data as workerData, a copy of whatever you passed in, and replies with parentPort.postMessage(). Create the worker file:
cat > once-worker.mjs <<'JS'
import { parentPort, workerData } from 'node:worker_threads';
import { slowHash } from './work.mjs';
parentPort.postMessage(slowHash(workerData.input, workerData.ms));
JSThe main side wraps the worker in a promise. Three events matter:
message: the worker sent a result.error: code in the worker threw and nothing caught it. The worker stops, but the main thread keeps running.exit: the worker has stopped. Code0means it finished normally. A worker that hit an uncaught error exits with code1, right after itserrorevent.
A timer prints every half second, so you can see the main thread stays free while the worker computes:
cat > run-once.mjs <<'JS'
import { Worker } from 'node:worker_threads';
function hashInWorker(input, ms) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./once-worker.mjs', import.meta.url), {
workerData: { input, ms },
});
worker.once('message', resolve);
worker.once('error', reject);
worker.once('exit', (code) => {
console.log(`worker exited with code ${code}`);
if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));
});
});
}
const timer = setInterval(() => console.log('main thread still free'), 500);
try {
console.log(await hashInWorker('hello', 2000));
await hashInWorker('boom', 100);
} catch (err) {
console.log('worker failed:', err.message);
} finally {
clearInterval(timer);
}
JS
node run-once.mjsCalling reject after the promise has already settled does nothing, so the exit handler is safe even after error has rejected it.
Check it worked
The output is something like this:
main thread still free
main thread still free
main thread still free
{ digest: '5c1f0e7a9b2d4c66', rounds: 1873402 }
worker exited with code 0
worker failed: cannot hash "boom"
worker exited with code 1The timer kept firing while the hash ran, and the error thrown inside the worker arrived in the main thread as an ordinary Error with its message intact.
Step 4 · Move large data without copying it
workerData and postMessage copy what you send, using the structured clone algorithm. For a small object that costs nothing worth measuring. For a 64 MB file you have read into memory, the copy takes time on the main thread and doubles the memory used.
An ArrayBuffer can be transferred instead. List it in the second argument of postMessage, and the memory moves to the worker. The sender's buffer becomes empty, with a byteLength of 0, so two threads can never write to it at once. Create a worker that hashes whatever buffer it receives, and a script that sends the same size of data both ways:
cat > buffer-worker.mjs <<'JS'
import { parentPort } from 'node:worker_threads';
import { createHash } from 'node:crypto';
parentPort.on('message', (buffer) => {
const digest = createHash('sha256').update(new Uint8Array(buffer)).digest('hex');
parentPort.postMessage({ bytes: buffer.byteLength, digest: digest.slice(0, 16) });
});
JS
cat > transfer.mjs <<'JS'
import { Worker } from 'node:worker_threads';
import { once } from 'node:events';
const worker = new Worker(new URL('./buffer-worker.mjs', import.meta.url));
const size = 64 * 1024 * 1024;
for (const mode of ['copy', 'transfer']) {
const buffer = new ArrayBuffer(size);
new Uint8Array(buffer).fill(7);
const started = performance.now();
worker.postMessage(buffer, mode === 'transfer' ? [buffer] : []);
const took = (performance.now() - started).toFixed(1);
const [reply] = await once(worker, 'message');
console.log(`${mode}: postMessage took ${took} ms, worker hashed ${reply.bytes} bytes (${reply.digest}), main thread still holds ${buffer.byteLength} bytes`);
}
await worker.terminate();
JS
node transfer.mjsThis worker listens with parentPort.on('message'), so it would stay alive forever. worker.terminate() stops it once the script is done.
Check it worked
You see two lines. Both report worker hashed 67108864 bytes with the same digest. The copy line ends with main thread still holds 67108864 bytes, and the transfer line ends with main thread still holds 0 bytes. The copy line usually shows a much longer postMessage time, for example tens of milliseconds against well under one. The exact numbers depend on your machine.
Sharing memory with SharedArrayBuffer and Atomics
There is a third option: a SharedArrayBuffer is neither copied nor moved. Every thread you send it to sees the same memory. That is fast, and it brings back the problems of shared memory: two threads doing counter[0] += 1 at the same moment can lose an update. The Atomics functions make single reads and writes safe. This script starts four workers from the same file, and each adds one 100,000 times:
cat > counter.mjs <<'JS'
import { Worker, isMainThread, workerData } from 'node:worker_threads';
if (isMainThread) {
const shared = new SharedArrayBuffer(4);
const counter = new Int32Array(shared);
const workers = Array.from({ length: 4 }, () =>
new Worker(new URL(import.meta.url), { workerData: shared }),
);
await Promise.all(workers.map((w) => new Promise((resolve, reject) => {
w.once('exit', resolve);
w.once('error', reject);
})));
console.log('count:', Atomics.load(counter, 0));
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < 100_000; i += 1) Atomics.add(counter, 0, 1);
}
JS
node counter.mjsIt prints count: 400000. Reach for shared memory only when messages are measurably too slow. Messages are easier to get right.
Step 5 · Build a small worker pool
Starting a worker costs time and memory: each one has its own V8 instance and loads its own modules. One worker per request also means 100 requests start 100 threads, all fighting over a few CPU cores. A pool starts a fixed number of workers once and queues jobs for them.
The pool worker stays alive and handles one message after another:
cat > pool-worker.mjs <<'JS'
import { parentPort } from 'node:worker_threads';
import { slowHash } from './work.mjs';
parentPort.on('message', ({ input, ms }) => {
parentPort.postMessage(slowHash(input, ms));
});
JSThe pool keeps idle workers in a list, busy workers in a map from worker to job, and waiting jobs in a queue. When a worker answers, its job resolves and the worker picks up the next job. When a worker dies, its job is rejected and a fresh worker takes its place, so the pool never shrinks:
cat > pool.mjs <<'JS'
import { Worker } from 'node:worker_threads';
export class WorkerPool {
#file;
#idle = [];
#busy = new Map();
#queue = [];
#closing = false;
constructor(file, size) {
this.#file = file;
this.size = size;
for (let i = 0; i < size; i += 1) this.#addWorker();
}
run(task) {
return new Promise((resolve, reject) => {
this.#queue.push({ task, resolve, reject });
this.#next();
});
}
stats() {
return {
size: this.size,
workers: this.#idle.length + this.#busy.size,
busy: this.#busy.size,
queued: this.#queue.length,
};
}
async close() {
this.#closing = true;
for (const job of this.#queue.splice(0)) job.reject(new Error('pool closed'));
await Promise.all([...this.#idle, ...this.#busy.keys()].map((w) => w.terminate()));
}
#addWorker() {
const worker = new Worker(this.#file);
worker.on('message', (result) => {
const job = this.#busy.get(worker);
this.#busy.delete(worker);
this.#idle.push(worker);
job.resolve(result);
this.#next();
});
worker.on('error', (err) => {
const job = this.#busy.get(worker);
this.#busy.delete(worker);
job?.reject(err);
});
worker.on('exit', (code) => {
const job = this.#busy.get(worker);
this.#busy.delete(worker);
job?.reject(new Error(`worker exited with code ${code}`));
this.#idle = this.#idle.filter((w) => w !== worker);
if (!this.#closing) {
this.#addWorker();
this.#next();
}
});
this.#idle.push(worker);
}
#next() {
while (this.#idle.length > 0 && this.#queue.length > 0) {
const worker = this.#idle.pop();
const job = this.#queue.shift();
this.#busy.set(worker, job);
worker.postMessage(job.task);
}
}
}
JSTwo details are easy to miss. The error handler removes the job from the busy map before the exit handler runs, so a crashed job is rejected once, with the real error. And close() sets #closing first, so terminating the workers does not start replacements.
Check it worked
Run the pool directly with three jobs on two workers, one of them boom:
cat > try-pool.mjs <<'JS'
import { WorkerPool } from './pool.mjs';
const pool = new WorkerPool(new URL('./pool-worker.mjs', import.meta.url), 2);
const results = await Promise.allSettled([
pool.run({ input: 'a', ms: 300 }),
pool.run({ input: 'boom', ms: 300 }),
pool.run({ input: 'c', ms: 300 }),
]);
console.log(results.map((r) => r.status).join(' '));
await new Promise((resolve) => setTimeout(resolve, 200));
console.log(pool.stats());
await pool.close();
JS
node try-pool.mjsThe first line is fulfilled rejected fulfilled. The second is { size: 2, workers: 2, busy: 0, queued: 0 }: the worker that crashed on boom was replaced.
Step 6 · Serve /hash from the pool
The new server is the old one with the pool in place of the direct call, plus a /stats endpoint. It uses one worker per CPU core, leaving one core for the main thread, and never more than four. os.availableParallelism() reports how many cores Node may use. Many entry-level VPS plans, including the one- and two-vCPU servers small teams across Africa often start on, give a pool of one worker. That still keeps /health fast, because the operating system shares the core between threads, but it does not make hashing faster. Throughput only grows with cores.
cat > server-pool.mjs <<'JS'
import http from 'node:http';
import os from 'node:os';
import { WorkerPool } from './pool.mjs';
import { parseMs } from './work.mjs';
const port = Number(process.env.PORT ?? 8002);
const size = Math.max(1, Math.min(4, os.availableParallelism() - 1));
const pool = new WorkerPool(new URL('./pool-worker.mjs', import.meta.url), size);
function send(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body) + '\n');
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/health') return send(res, 200, { status: 'ok' });
if (url.pathname === '/stats') return send(res, 200, pool.stats());
if (url.pathname === '/hash') {
const input = url.searchParams.get('input') ?? 'hello';
const ms = parseMs(url.searchParams.get('ms'));
pool.run({ input, ms }).then(
(result) => send(res, 200, result),
(err) => {
console.error('hash failed:', err.message);
send(res, 500, { error: 'hash failed' });
},
);
return;
}
send(res, 404, { error: 'not found' });
});
server.listen(port, '127.0.0.1', () => {
console.log(`listening on http://127.0.0.1:${port} with ${size} workers`);
});
process.once('SIGINT', async () => {
server.close();
await pool.close();
});
JSThe 500 response says only that the hash failed. The real message goes to the server log, not to the caller. On Ctrl+C the server stops accepting connections and terminates the workers, and Node exits once nothing is left running. Start it in your second terminal:
cd ~/workers-demo
node server-pool.mjsRepeat the measurement from before, on the new port:
curl -s -o /dev/null http://127.0.0.1:8002/hash & job=$!
sleep 0.3
curl -s -o /dev/null -w 'health answered in %{time_total}s\n' http://127.0.0.1:8002/health
wait "$job"Check it worked
The second terminal shows something like listening on http://127.0.0.1:8002 with 4 workers. The health check now answers in a few milliseconds, something like health answered in 0.002s, while the hash is still running.
Step 7 · Send 100 requests at once
Send 100 short jobs of 200 ms each, 20 at a time, and count the status codes. While they run, ask /stats what the pool is doing:
seq 100 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' "http://127.0.0.1:8002/hash?input={}&ms=200" > codes.txt & load=$!
sleep 1
curl -s http://127.0.0.1:8002/stats
wait "$load"
sort codes.txt | uniq -cThen check that a failing job costs one request, not the server:
curl -s -w '%{http_code}\n' 'http://127.0.0.1:8002/hash?input=boom&ms=10'
sleep 0.5
curl -s http://127.0.0.1:8002/statsCheck it worked
During the load, /stats shows something like {"size":4,"workers":4,"busy":4,"queued":16}: never more workers than the pool size, with the rest of the requests waiting in the queue. The counts at the end are 100 200, meaning every request succeeded. The boom request returns {"error":"hash failed"} and 500, the second terminal logs hash failed: cannot hash "boom", and the final /stats shows workers back at the pool size with nothing busy.
With 4 workers, 100 jobs of 200 ms take about five seconds. A real queue also needs a limit: if jobs arrive faster than the pool can finish them, reject new ones with a 503 once the queue holds, say, 100 jobs, rather than letting memory and waiting times grow without bound.
Stop the server with Ctrl+C in the second terminal.
Step 8 · Compare with child_process
child_process.fork() is the other way to get work off the main thread. It starts a whole new Node.js process with its own memory, connected to yours by an IPC channel that also uses send and message. Write a tiny echo script that works both ways, and time how soon each one answers:
cat > echo.mjs <<'JS'
import { parentPort } from 'node:worker_threads';
if (parentPort) {
parentPort.on('message', (msg) => parentPort.postMessage(`pong: ${msg}`));
} else {
process.on('message', (msg) => process.send(`pong: ${msg}`));
}
JS
cat > compare.mjs <<'JS'
import { Worker } from 'node:worker_threads';
import { fork } from 'node:child_process';
import { once } from 'node:events';
const file = new URL('./echo.mjs', import.meta.url);
let started = performance.now();
const worker = new Worker(file);
worker.postMessage('ping');
const [fromWorker] = await once(worker, 'message');
console.log(`worker thread: "${fromWorker}" after ${(performance.now() - started).toFixed(0)} ms`);
await worker.terminate();
started = performance.now();
const child = fork(file);
child.send('ping');
const [fromChild] = await once(child, 'message');
console.log(`child process: "${fromChild}" after ${(performance.now() - started).toFixed(0)} ms`);
child.kill();
JS
node compare.mjsCheck it worked
You see two lines, worker thread: "pong: ping" after … ms and child process: "pong: ping" after … ms. On most machines the worker answers sooner, because a child process has to start a complete Node.js runtime.
Which one fits
Use a worker thread when:
- the work is JavaScript, or a native addon, that keeps a CPU core busy: hashing, compression, image processing, parsing large JSON or CSV;
- you want to move large binary data in and out cheaply with transfers, or share it with
SharedArrayBuffer; - you trust the code, since a worker shares the process. A JavaScript error stays inside the worker, as you saw, but a native crash or running out of memory can take the whole process down. The
resourceLimitsoption ofnew Workercaps a worker's heap.
Use a child process when:
- the work is another program, such as
ffmpeg, ImageMagick or a Python script (usespawnorexecFilefor those); - you need strong isolation: separate memory, a separate crash, and the option to kill it hard if it hangs;
- the job runs long and rarely, so a few tens of milliseconds of start-up do not matter.
Neither helps with work that waits on the network or a disk. Node already does those without blocking, so keep them on the main thread with async/await.
Step 9 · Clean up
Make sure both servers are stopped, then remove the demo folder. Node.js stays installed:
cd ~
rm -rf ~/workers-demoCheck it worked
ls ~/workers-demo reports that there is no such file or directory.
Next steps
- Work through large files without loading them into memory, which is often the better fix for slow file handling: process big files in Node.js with streams.
- Put the pool behind a real API with validation and tests: build a REST API with Express 5.
- Find out which function is slow before you move it to a worker: debug a Node.js app with the inspector.
- The worker_threads reference at nodejs.org covers
MessageChannel,BroadcastChannel,resourceLimitsand the other options ofnew Worker.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials