More Node.js answers

by Danny
Published 2 min read

Use worker threads for heavy CPU work like image processing, parsing or hashing that would block the event loop. They do not speed up I/O such as database or network calls.

The short answer

#

Use worker threads when a piece of synchronous, CPU-heavy JavaScript blocks the event loop long enough to slow down other requests. Do not use them for I/O such as database queries, file reads or HTTP calls, because Node.js already handles those without blocking.


_10
import { Worker } from 'node:worker_threads';
_10
_10
const worker = new Worker(new URL('./resize.js', import.meta.url), {
_10
workerData: { path: 'photo.jpg' },
_10
});
_10
_10
worker.once('message', (result) => console.log('Done', result));
_10
worker.once('error', (err) => console.error(err));

Why it happens

#

Node.js runs your JavaScript on a single thread with an event loop. While one callback runs, nothing else does. That is fine for I/O, because a call like fetch or readFile hands the work to the operating system or libuv's thread pool and returns straight away. Your thread is free to serve other requests while it waits.

CPU work is different. Parsing a 50 MB JSON file, resizing an image in pure JavaScript, compressing data synchronously or running a slow regular expression keeps the thread busy. Every other request waits until it finishes. If one request takes 2 seconds of CPU, every other user waits 2 seconds too.

A worker thread is a separate JavaScript environment with its own event loop and memory, running in parallel on another CPU core in the same process. Moving the heavy work there keeps the main thread responsive.

How to fix it

#

Move CPU work into a worker

The worker file receives input through workerData and replies with postMessage.


_10
// fib-worker.js
_10
import { parentPort, workerData } from 'node:worker_threads';
_10
_10
function fib(n) {
_10
return n < 2 ? n : fib(n - 1) + fib(n - 2);
_10
}
_10
_10
parentPort.postMessage(fib(workerData.n));

Wrap it in a promise so the rest of your code can await it:


_17
// main.js
_17
import { Worker } from 'node:worker_threads';
_17
_17
function runFib(n) {
_17
return new Promise((resolve, reject) => {
_17
const worker = new Worker(new URL('./fib-worker.js', import.meta.url), {
_17
workerData: { n },
_17
});
_17
worker.once('message', resolve);
_17
worker.once('error', reject);
_17
worker.once('exit', (code) => {
_17
if (code !== 0) reject(new Error(`Worker stopped with code ${code}`));
_17
});
_17
});
_17
}
_17
_17
console.log(await runFib(40));

Use a pool for repeated work

Starting a worker takes time and memory, since each one boots its own JavaScript engine instance. Creating one per request is wasteful. For a server, keep a fixed pool of workers, usually about one per CPU core, and send jobs to them. The Piscina library is a popular, well maintained pool, so you do not need to write the queueing yourself.

You can check how many cores are available with os.availableParallelism().

Share or transfer large data

Messages between threads are copied using the structured clone algorithm. For large binary data, transfer it instead of copying, so the worker takes ownership of the memory:


_10
const buffer = new ArrayBuffer(100 * 1024 * 1024);
_10
worker.postMessage({ buffer }, [buffer]);
_10
// buffer is now unusable on the main thread

If several threads need the same data at once, use a SharedArrayBuffer with Atomics for coordination.

Know the alternatives

  • I/O-bound work: stay on the main thread and use async code. Workers add overhead and no speed.
  • Running another program: use child_process, for example to call ffmpeg.
  • Using every core for an HTTP server: run several processes with the cluster module, a process manager, or more containers. Each process handles its own requests.
  • Built-in heavy tasks: many APIs already run off the main thread, such as the async versions of crypto.pbkdf2, crypto.scrypt and zlib functions. Use those before reaching for a worker.

Common pitfalls

#
  • Expecting faster database calls. Workers do not make I/O quicker. Measure first: if the event loop is not blocked, workers will not help.
  • Sending functions or class instances. Structured clone cannot copy functions, and class instances lose their methods. Send plain data.
  • Forgetting error handling. An uncaught exception in a worker emits error on the Worker object. Listen for it, or the promise never settles.
  • One worker per request. Under load this creates hundreds of threads and lots of memory use. Use a pool.
  • Assuming shared state. Each worker has its own globals and module cache. A variable changed in a worker does not change in the main thread.
#

Was this resource helpful?