Worker threads
Overview
You learned in How Node.js works that your JavaScript runs on one main thread. That’s perfect for I/O-heavy servers. But some tasks are CPU-heavy: resizing images in JavaScript, generating large reports, parsing huge files, compressing data, complex calculations. While they run, the event loop is blocked and every other request waits.
Worker threads let you run JavaScript on additional threads — and therefore additional CPU cores — while the main thread stays free to handle requests.
When to use them
| Work | Use worker threads? |
|---|---|
| Waiting for a database, API or file | No — that’s already non-blocking |
Hashing a password with crypto.scrypt |
No — the async version already runs in libuv’s pool |
| A JavaScript loop that takes 300 ms of CPU | Yes |
| Parsing/transforming a large dataset in JS | Yes |
| Image or PDF processing in pure JavaScript | Yes (or a native library, or a job queue) |
The first question is always: is my code actually busy computing, or just waiting? Only computing benefits from threads.
A first worker
A worker is a separate JavaScript file that runs in its own thread:
// fib-worker.js
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));// main.js
import { Worker } from 'node:worker_threads';
function runFib(n) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./fib-worker.js', import.meta.url), {
workerData: { n },
});
worker.once('message', resolve);
worker.once('error', reject);
});
}
console.log(await runFib(40)); // computed on another threadworkerDatapasses initial input.parentPort.postMessage(value)sends a message from the worker to the main thread.- The main thread listens with
worker.on('message', …), and can send messages back withworker.postMessage(…). - The worker exits when it has nothing left to do (or call
worker.terminate()).
In an Express route
app.get('/reports/:year', async (req, res) => {
const report = await runInWorker('./report-worker.js', { year: Number(req.params.year) });
res.json(report);
});The route still awaits, but the event loop is free while the worker computes — other users’ requests are served normally.
Isolation and messages
Workers are well isolated: each has its own event loop, memory and copy of every module. Variables aren’t shared. Messages are copied using the structured clone algorithm (the same one as structuredClone) — so you can send objects, arrays, Maps, Dates and Buffers, but not functions or class instances with their methods.
Copying a 200 MB buffer is slow. You can transfer it instead — ownership moves to the other thread, with no copy:
const pixels = new Uint8Array(1024 * 1024 * 50);
worker.postMessage({ pixels }, [pixels.buffer]); // pixels is now unusable in the main threadFor truly shared memory, SharedArrayBuffer with Atomics lets threads read and write the same bytes — powerful, but you then have to think about concurrent access, so reach for it rarely.
Use a pool
Starting a worker takes tens of milliseconds and several megabytes. Starting one per request would waste that. A worker pool creates a few workers once and hands them tasks from a queue. Piscina is the popular choice:
npm install piscina// thumbnail-task.js — export the work as a function
export default function makeThumbnail({ pixels, width }) {
// …CPU-heavy work…
return result;
}// main.js
import { Piscina } from 'piscina';
import os from 'node:os';
const pool = new Piscina({
filename: new URL('./thumbnail-task.js', import.meta.url).href,
maxThreads: os.availableParallelism() - 1, // leave a core for the main thread
});
app.post('/thumbnails', async (req, res) => {
res.json(await pool.run({ pixels: req.body.pixels, width: 200 }));
});The pool queues tasks when all workers are busy, so a burst of requests can’t create a hundred threads.
Workers or a job queue?
Worker threads keep work inside the request: the user waits, but the server stays responsive. If the user doesn’t need the result immediately (sending a PDF by email, for example), a background job (see Background jobs) is often better — it survives restarts, can retry, and runs on separate machines.
| Worker threads | Background jobs | |
|---|---|---|
| User waits for the result | yes | no |
| Survives a restart | no | yes |
| Runs on other machines | no | yes |
| Good for | CPU work under a few seconds | slow, retryable, not-urgent work |
Measure first. Moving work to a worker adds complexity and message-passing overhead. Profile (see Profiling and performance) to confirm the event loop really is blocked before reaching for threads.
Offload a heavy calculation
Write primes-worker.js that counts the primes below workerData.limit and posts the result back. Then write countPrimes(limit) in the main file that runs the worker and returns a promise of the count. Show that a setInterval tick keeps running while the worker computes.
// main.js
import { Worker } from 'node:worker_threads';
export function countPrimes(limit) {
// your code here
}// primes-worker.js
import { parentPort, workerData } from 'node:worker_threads';
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i * i <= n; i++) if (n % i === 0) return false;
return true;
}
let count = 0;
for (let n = 2; n < workerData.limit; n++) if (isPrime(n)) count++;
parentPort.postMessage(count);
// main.js
import { Worker } from 'node:worker_threads';
export function countPrimes(limit) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./primes-worker.js', import.meta.url), { workerData: { limit } });
worker.once('message', resolve);
worker.once('error', reject);
worker.once('exit', (code) => {
if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}
const tick = setInterval(() => console.log('still responsive'), 200);
console.log('primes:', await countPrimes(5_000_000));
clearInterval(tick);Summary
- CPU-heavy JavaScript blocks the event loop; worker threads run it on other CPU cores.
- Each worker has its own event loop and memory; communicate with
postMessageand'message'events. - Data is copied between threads (structured clone); large buffers can be transferred instead.
- Starting a worker costs time and memory — reuse workers with a pool such as Piscina.
- Don’t use workers for I/O: Node is already asynchronous for files and networking.