Explain it simply
Worker threads in plain language
Node.js runs your JavaScript on a single main thread. For I/O such as waiting on a database or reading a file this is fine, because other requests are handled while it waits. But heavy computation, such as resizing an image or generating a PDF, on the main thread means no request is answered until that calculation finishes.
A worker thread is another JavaScript thread with its own event loop and its own memory. It is like a restaurant cashier who passes a slow dish to the kitchen and keeps serving the next customer.
Problem → Why → Solution
The problem: one report freezes the whole API
Every time an admin clicks 'generate yearly report', the API's /health endpoint stops answering for about five seconds. The load balancer marks the server unhealthy and pulls it, so every user sees errors. The report code has awaits in it, but the part that loops over hundreds of thousands of rows and calculates totals is synchronous.
app.get('/reports/yearly', async (req, res) => {
const rows = await db.loadYear(2025); // fine: waiting on I/O
const totals = buildTotals(rows); // 5 s of pure CPU: the whole server freezes
res.json(totals);
});
app.get('/health', (req, res) => res.send('ok')); // cannot answer meanwhileWhy async does not save you
async/await frees the main thread while waiting on I/O, but it does not split up CPU work. While a synchronous loop runs, no timer, socket or request callback can run, so one long calculation raises the latency of every request at once. The fix is to move that calculation to another thread.
Core concept: measure, then move work to bounded workers
First, find out whether the problem is CPU or I/O. fs, networking and most database drivers already use native code and the libuv thread pool, so moving I/O into a worker adds overhead without benefit. Workers are for synchronous work that keeps the main thread busy for tens of milliseconds or more: parsing huge JSON, image processing, compression written in JavaScript, complex calculations. Do not guess; measure event-loop delay with monitorEventLoopDelay from perf_hooks, or take a profile with node --cpu-prof.
new Worker(fileUrl, { workerData }) runs a file in a new thread. Inside the worker you read the input from workerData and send the result back with parentPort.postMessage. Data crossing threads is copied with structured clone, so functions and class instances cannot be sent, and copying large data has a cost; an ArrayBuffer can be transferred instead of copied.
Each worker boots its own V8 isolate, which costs startup time and memory. So instead of creating a worker per job, reuse a bounded pool sized around os.availableParallelism() and queue extra jobs. Bound the queue too, or memory runs out under heavy traffic. Every job must end in exactly one of four ways: message, error, exit or timeout.
Take timeouts seriously. If a loop inside a worker never ends, worker.terminate() stops its JavaScript as soon as possible and shuts the thread down. The main thread has no such emergency switch: once a synchronous loop is stuck there, the only remedy is restarting the whole process.
| Work | Where it should run |
|---|---|
| database query, HTTP call, file read | main thread, with async/await |
| a calculation of a few ms | main thread (worker overhead costs more) |
| long CPU work (resize, parse, hash) | a bounded worker pool |
| many processes on one port | cluster or container replicas |
- Measure event-loop delay
- Send the CPU job to a pool
- Worker computes from workerData
- Ends: message/error/exit/timeout
The cashier (main thread) never cooks, and the kitchen (pool) has a fixed number of cooks.
General pattern
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(new URL(import.meta.url), { workerData: input });
worker.once('message', onResult);
worker.once('error', onError);
worker.once('exit', (code) => { /* non-zero: failed */ });
} else {
parentPort.postMessage(heavyWork(workerData));
}isMainThread lets one file act as both the main side and the worker side. Larger projects usually keep the worker code in its own file, such as ./worker.mjs.
Worked example: counting primes in two workers
runCpuJob wraps one worker in a promise: it resolves on a message and rejects on an error or a non-zero exit. Two jobs run at the same time with Promise.all while a setInterval on the main thread proves it keeps ticking. Finally, watch how a RangeError thrown inside a worker arrives back on the main thread.
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
function countPrimes(limit) {
if (!Number.isInteger(limit) || limit < 2) throw new RangeError(`bad limit: ${limit}`);
let count = 0;
for (let n = 2; n <= limit; n++) {
let prime = true;
for (let d = 2; d * d <= n; d++) {
if (n % d === 0) { prime = false; break; }
}
if (prime) count++;
}
return count;
}
function runCpuJob(limit) {
return new Promise((resolve, reject) => {
// Start this same file again, but inside a new thread.
const worker = new Worker(new URL(import.meta.url), { workerData: { limit } });
worker.once('message', resolve);
worker.once('error', reject); // an exception thrown inside the worker
worker.once('exit', (code) => {
if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));
});
});
}
if (!isMainThread) {
parentPort.postMessage(countPrimes(workerData.limit)); // worker side
} else {
let ticks = 0;
const heartbeat = setInterval(() => ticks++, 1); // proves the main thread is free
const [small, large] = await Promise.all([runCpuJob(50_000), runCpuJob(500_000)]);
clearInterval(heartbeat);
console.log(`primes up to 50,000: ${small}`);
console.log(`primes up to 500,000: ${large}`);
console.log(`main thread kept ticking: ${ticks > 0}`);
try {
await runCpuJob(1);
} catch (error) {
console.log(`job rejected: ${error.name}: ${error.message}`);
}
}Code breakdown
- Same file, new thread
const worker = new Worker(new URL(import.meta.url), { workerData: { limit } });new URL(import.meta.url) points at the current ES module file, and workerData is copied to the worker with structured clone.
- Worker side
parentPort.postMessage(countPrimes(workerData.limit)); // worker sideInside the worker isMainThread is false, so only this branch runs. After postMessage there is nothing left to do, so the worker exits with code 0.
- Errors cross the boundary
worker.once('error', reject); // an exception thrown inside the workerAn uncaught exception in the worker arrives as an 'error' event on the main thread with its name and message intact, which is why RangeError: bad limit: 1 is printed.
- Crashes without an error
if (code !== 0) reject(new Error(`worker stopped with exit code ${code}`));Catches endings that emit no error event, such as process.exit(1) inside the worker or a termination. Without it, the promise could stay pending forever.
- Proof the main thread is free
const heartbeat = setInterval(() => ticks++, 1); // proves the main thread is freeHad countPrimes(500_000) been called directly on the main thread, the interval would not fire even once and ticks would stay 0.
primes up to 50,000: 5133
primes up to 500,000: 41538
main thread kept ticking: true
job rejected: RangeError: bad limit: 1Measuring event-loop blocking
Before adding workers, prove there is a problem. monitorEventLoopDelay records, as a histogram, how late a timer runs compared with when it was scheduled. The snippet below blocks the main thread for 200 ms, so the maximum delay comes out around 200 ms; the exact number depends on the machine and OS.
import { monitorEventLoopDelay } from 'node:perf_hooks';
import { setTimeout as sleep } from 'node:timers/promises';
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
await sleep(50); // a healthy, idle event loop
const end = Date.now() + 200;
while (Date.now() < end); // 200 ms of synchronous CPU work: nothing else can run
await sleep(50);
histogram.disable();
// Values are in nanoseconds; the worst delay is close to the 200 ms block.
console.log(`max event-loop delay: ~${Math.round(histogram.max / 1e6)} ms`);In production the histogram's p99 is often exported as a metric with an alert on it. When p99 creeps up, profile the app to find the synchronous code on the event loop.
In real projects
How workers are used in production
Real APIs rarely create workers one by one; they use a pool library such as piscina, which lets you set the thread count, queue size and timeouts. Whatever you choose, the underlying rules are the ones in this lesson.
- Thumbnailing uploaded images, rendering PDF invoices and slow password hashing such as bcrypt run in the pool while the main thread keeps answering requests.
- When the pool and its queue are full, refuse new jobs with 503 or 429 instead of queueing forever, so the whole server does not fall over.
- Very large jobs, such as video encoding or hour-long batches, leave the web process entirely and go to a separate worker service that reads from a queue.
Common mistakes
Common mistakes with worker threads
Moving I/O work into workers
Putting a database query or a fetch inside a worker saves no CPU on the main thread; it only adds worker startup and data-copying costs. Measure event-loop delay and move only synchronous CPU work.
Creating a new worker for every job
Calling new Worker() per request spawns hundreds of threads under load; they fight over CPU cores and exhaust memory, and the startup cost makes small jobs slower. Reuse a pool with a fixed size.
Ignoring 'exit' or having no timeout
Listening only to 'message' and 'error' leaves the promise pending forever when a worker exits without an error. A worker stuck in an endless loop never stops without a timeout; stop it with worker.terminate().
Best practices
Best practices
- Base the decision to add workers on event-loop delay and CPU profile data, not on a hunch.
- Send workers only the data they need, and move large buffers with a transfer list.
- Give every job a timeout and track the pool's queue length as a metric.
- Remember to terminate the pool's workers when the process shuts down.
Mini challenge
Mini challenge: a worker job with a timeout
Write runWithTimeout(limit, ms), which sums the primes below a limit inside a worker. If it takes longer than ms, terminate the worker and reject the promise. Try it with one small job and one that takes far too long.
- Start the worker with new URL(import.meta.url)
- Handle message, error and exit
- On timeout, call worker.terminate() and reject with 'timed out after <ms> ms'
- Clear the timer with clearTimeout whenever the job ends
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
if (!isMainThread) {
// TODO: sum every prime n with 2 <= n < workerData.limit
// TODO: send the sum with parentPort.postMessage
} else {
function runWithTimeout(limit, ms) {
return new Promise((resolve, reject) => {
// TODO: start the worker with workerData: { limit }
// TODO: setTimeout -> terminate the worker and reject
// TODO: message -> clear the timer, resolve
// TODO: error / non-zero exit -> clear the timer, reject
});
}
// TODO: try [10_000, 5_000] and [50_000_000, 200]; print each result or error
}Expected: It prints sum of primes below 10000: 5736396, then limit 50000000: timed out after 200 ms.
Show hint
Once a promise is settled, later resolve or reject calls do nothing, so the exit event that follows terminate() may safely call reject again.
Show solution
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
if (!isMainThread) {
// Sum of primes below a limit: slow on purpose for big limits.
const { limit } = workerData;
let sum = 0;
for (let n = 2; n < limit; n++) {
let prime = true;
for (let d = 2; d * d <= n; d++) if (n % d === 0) { prime = false; break; }
if (prime) sum += n;
}
parentPort.postMessage(sum);
} else {
function runWithTimeout(limit, ms) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), { workerData: { limit } });
const timer = setTimeout(() => {
worker.terminate(); // stops the thread even in the middle of a loop
reject(new Error(`timed out after ${ms} ms`));
}, ms);
worker.once('message', (sum) => {
clearTimeout(timer);
resolve(sum);
});
worker.once('error', (error) => {
clearTimeout(timer);
reject(error);
});
worker.once('exit', (code) => {
clearTimeout(timer);
if (code !== 0) reject(new Error(`worker exited with code ${code}`));
});
});
}
for (const [limit, ms] of [[10_000, 5_000], [50_000_000, 200]]) {
try {
console.log(`sum of primes below ${limit}: ${await runWithTimeout(limit, ms)}`);
} catch (error) {
console.log(`limit ${limit}: ${error.message}`);
}
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Synchronous CPU work blocks the event loop and slows every request; async/await does not help.
- Measure with monitorEventLoopDelay or a profiler before adding workers, and never move I/O into them.
- Every worker job must end in exactly one of: message, error, exit or timeout.
- Use a bounded pool and queue instead of a new worker per job.
Worker threads — Node.js