A Node.js HTTP service that hashes a 50 MiB file or runs a synchronous JSON.stringify on a 200 MB object blocks the event loop for hundreds of milliseconds — during which every other request waits. The worker_threads module gives you actual OS threads with their own V8 isolate, so CPU-bound work runs in parallel without stalling request handlers. This walks through the right way to use them, the worker pool pattern, and the message-passing trap that catches teams new to threads.
How to verify
Detect event-loop stalls and confirm whether worker threads are doing what they should:
node --eval "const { performance, monitorEventLoopDelay } = require('perf_hooks'); \
const h = monitorEventLoopDelay({ resolution: 20 }); h.enable(); \
setInterval(() => console.log('p99=', h.percentile(99) / 1e6, 'ms'), 1000);"
ps -eLf | grep node # threads per process
curl -s http://127.0.0.1:3000/_metrics | grep event_loop_lag
journalctl -u myapp --since "5 min ago" | grep -i 'worker\|thread\|stalled'
If event-loop p99 lag is consistently above 100 ms on a service receiving real traffic, you have CPU work on the main thread that belongs in a worker.
What’s happening
Node has one event loop on the main thread. CPU work blocks it. The fixes in order of weight: chunk the work and yield via setImmediate, use a worker thread, use a worker pool. Workers each have their own V8 isolate, heap, and event loop — they share memory only through explicit SharedArrayBuffer or via message-passed Transferable objects (the buffer ownership moves, no copy).
A common mistake is creating a worker per request. Worker startup costs 30–50 ms — fine for one-off heavy jobs, fatal for a hot path. Use a pool (piscina is the production-grade library) that keeps N workers warm and dispatches jobs to whichever is free. Pool size should be roughly cpus - 1 so the main thread keeps a core.
The procedure
-
Identify CPU work that doesn’t belong on the main thread. Common offenders: JSON parsing of huge payloads, regex on large strings, image processing, sync crypto, sync compression, PDF/Excel generation, ML inference.
-
Extract the work into a dedicated file that the worker will load:
// workers/hash.mjs import { parentPort } from 'node:worker_threads'; import { createHash } from 'node:crypto'; parentPort.on('message', ({ data, algorithm }) => { const h = createHash(algorithm).update(data).digest('hex'); parentPort.postMessage({ hash: h }); }); -
For one-off jobs, spawn a worker, send a message, await the reply, terminate:
import { Worker } from 'node:worker_threads'; function hashInWorker(buffer, algorithm = 'sha256') { return new Promise((resolve, reject) => { const w = new Worker(new URL('./workers/hash.mjs', import.meta.url)); w.once('message', m => { resolve(m.hash); w.terminate(); }); w.once('error', reject); w.postMessage({ data: buffer, algorithm }, [buffer.buffer]); // transfer ownership }); } -
For hot paths, use
piscinafor a managed pool. Install once, configure on boot:// server.js import Piscina from 'piscina'; const pool = new Piscina({ filename: new URL('./workers/hash.mjs', import.meta.url), minThreads: 2, maxThreads: Math.max(2, os.availableParallelism() - 1), idleTimeout: 30_000, }); app.post('/hash', async (req, res) => { const hash = await pool.run({ data: req.body, algorithm: 'sha256' }); res.json({ hash }); }); -
Expose pool stats so you can see saturation:
app.get('/_pool', (req, res) => res.json({ completed: pool.completed, duration: pool.duration, waitTime: pool.waitTime, utilization: pool.utilization, queueSize: pool.queueSize, })); -
On SIGTERM, destroy the pool gracefully so in-flight jobs finish:
process.on('SIGTERM', async () => { await pool.destroy(); server.close(); });
Common pitfalls
postMessageis structured-cloned by default — a 50 MiB object is copied on send and again on reply. UseTransferable(ArrayBuffer, MessagePort) with the second argument to transfer ownership and avoid the copy.- Worker startup is expensive. A naive per-request
new Worker()is slower than the synchronous code it replaces. Use a pool. - Workers cannot share regular objects with the parent.
SharedArrayBuffershares bytes but you must coordinate withAtomics— easy to deadlock. - Native modules must be thread-safe to load in a worker. If a worker crashes with “module instance was loaded in a different thread”, the module is not worker-safe.
- Errors thrown inside a worker only surface as
'error'events on the worker handle. Forgetting to attach anerrorlistener silently loses the error.
For end-to-end profiling that points you to the right place to add a worker, see V8 profiling with pprof. In the engagements Stack Harbor runs, piscina is the default pool for any CPU-heavy path; we tune maxThreads, watch pool.utilization as part of managed operations, and alert on event-loop p99 lag so blocking code is caught before it shows up as 503s.