CPU-heavy work in Node: worker threads, cluster or a queue?
Node is great at waiting: on databases, on APIs, on files. It's bad at computing on the main thread, because while it computes, it can't do anything else.
Node is great at waiting: on databases, on APIs, on files. It’s bad at computing on the main thread, because while it computes, it can’t do anything else. Resizing images, hashing passwords, generating PDFs, parsing a huge spreadsheet: put any of these in a request handler and every other request waits.
There are three common ways out, and they solve different problems.
How bad is it?
Here’s a quick test: four password hashes with pbkdf2Sync, and a timer that measures how late the event loop is running.
main thread, 4 hashes: 1059 ms max event loop lag while hashing on main thread: 1009 ms
For about a second, the server can’t answer anything, not even a health check. Under real traffic, that’s how a few heavy requests make the whole API look down.
Option 1: worker threads
Worker threads run JavaScript on other threads, each with its own V8 instance and event loop. The main thread hands work over and stays free:
// hash-worker.js
import { parentPort } from 'node:worker_threads';
import { pbkdf2Sync } from 'node:crypto';
parentPort.on('message', ({ id, password, salt }) => {
const hash = pbkdf2Sync(password, salt, 600_000, 64, 'sha512').toString('hex');
parentPort.postMessage({ id, hash });
});
Starting a worker isn’t free. Around 30 ms on a small machine, plus memory for another V8 instance. So don’t create one per request. Keep a pool and reuse the workers:
// pool.js
import { Worker } from 'node:worker_threads';
import { availableParallelism } from 'node:os';
export class WorkerPool {
#idle = [];
#queue = [];
#pending = new Map();
#nextId = 0;
constructor(file, size = availableParallelism() - 1) {
for (let i = 0; i < size; i++) {
const worker = new Worker(file);
worker.on('message', ({ id, ...result }) => {
this.#pending.get(id).resolve(result);
this.#pending.delete(id);
this.#idle.push(worker);
this.#runNext();
});
this.#idle.push(worker);
}
}
run(data) {
return new Promise((resolve, reject) => {
const id = this.#nextId++;
this.#pending.set(id, { resolve, reject });
this.#queue.push({ id, ...data });
this.#runNext();
});
}
#runNext() {
if (this.#queue.length === 0 || this.#idle.length === 0) return;
this.#idle.pop().postMessage(this.#queue.shift());
}
}
const pool = new WorkerPool(new URL('./hash-worker.js', import.meta.url));
app.post('/register', async (req, res) => {
const { hash } = await pool.run({ password: req.body.password, salt: newSalt() });
// ...
});
The same four hashes on a two-core machine with a small pool:
worker pool (3), 4 hashes: 775 ms
max event loop lag with workers: 4 ms
The total time only improves as much as you have cores. The event loop lag is the real win: 4 ms instead of a full second. The server keeps answering other requests while the hashing happens.
This pool is deliberately minimal, with no error recovery and no timeouts. In production, use piscina, which handles crashed workers, task cancellation and queue limits.
Sending data to a worker copies it. For large binary data like image buffers, pass the ArrayBuffer in the transfer list so it’s moved instead of copied.
Option 2: cluster (or just more processes)
cluster forks your whole app into several processes that share one port. It doesn’t make a single heavy request faster. What it does is let other requests land on a process that isn’t busy.
It makes sense when you want to use every core on one machine for normal request handling. In practice, most deployments now get the same effect by running several containers or instances behind a load balancer, which is easier to scale and monitor. cluster is still handy on a single VM. But it’s not a fix for heavy work: a process busy hashing for a second still drops every request sent its way during that second.
Option 3: a job queue
Some work shouldn’t happen inside a request at all. Generating a big report, transcoding a video, sending 10,000 emails. The user doesn’t need to wait for it, and the work shouldn’t be lost if a server restarts halfway.
That’s what a queue is for. The API adds a job and responds right away. Separate worker processes pick up jobs and run them, often on different machines:
// in the API
import { Queue } from 'bullmq';
const reports = new Queue('reports', { connection: redis });
app.post('/reports', async (req, res) => {
const job = await reports.add('monthly', { accountId: req.user.accountId });
res.status(202).json({ jobId: job.id });
});
// in a separate worker process
import { Worker } from 'bullmq';
new Worker('reports', async (job) => {
return generateMonthlyReport(job.data.accountId);
}, { connection: redis });
You get retries, persistence and the ability to scale workers on their own. The cost is more moving parts: Redis to run, job status to show the user, failures to monitor.
Choosing
| Situation | Use |
|---|---|
| A few hundred ms of CPU work, and the user waits for the result | worker threads, in a pool |
| Plain request handling that should use all cores on one machine | cluster, or more instances |
| Seconds or minutes of work, or work that must survive a restart | a job queue |
They also combine well. A queue worker can use a thread pool internally, and an app running in several containers can still offload hashing to workers.
Whatever you pick, measure the event loop delay first (monitorEventLoopDelay from node:perf_hooks). If it’s low, your problem is somewhere else.