← Back to Node.js, page 7

nodejs-0121 · Hard senior

Is a worker thread pool always worth it? How do startup cost, message copying, transferables and resource limits affect the design?

A worker costs tens of milliseconds and some memory to start, and every message is copied with the structured clone algorithm. So use long-lived workers, size the pool near the number of CPU cores, send large data as transferred ArrayBuffers (zero copy) or SharedArrayBuffer, and set resourceLimits so one task cannot take down the process. Short tasks may be faster on the main thread.

Full answer

Worker threads give real parallelism for CPU-bound work, but they have costs that shape a good pool.

Costs

  • Startup: each Worker starts a new V8 isolate and an event loop, and loads your module. It takes roughly 10 to 50 ms and several MB of memory. Create workers once and reuse them. Do not create one per request.
  • Messages: postMessage copies data with structured clone. For a 100 MB object that takes time and doubles memory. Small messages are cheap.
  • Transfer: ArrayBuffers (and MessagePorts, some streams) can be listed in the transfer list. Ownership moves to the receiver with no copy, and the sender's buffer becomes detached (byteLength 0). Use it for images, audio and big binary blocks.
  • Sharing: SharedArrayBuffer is shared, not copied, but needs Atomics for safe access.

Sizing

  • CPU bound: about os.availableParallelism() workers, or one fewer to leave room for the main thread. More workers than cores only adds switching.
  • I/O bound work does not need workers at all. The event loop and the libuv thread pool already handle it.
  • Use a bounded queue in front of the pool for backpressure and reject or delay when it is full.

Safety

  • resourceLimits ({ maxOldGenerationSizeMb, maxYoungGenerationSizeMb, stackSizeMb }) stops one task from using all memory. The worker is terminated with ERR_WORKER_OUT_OF_MEMORY, and the main thread continues.
  • Handle 'error' and 'exit' events, replace dead workers, and add a task timeout (worker.terminate()).
  • Libraries such as Piscina give you this machinery (queue, timeouts, cancellation, transfer lists) so you do not rebuild it.

Rule of thumb: if the task takes under a few milliseconds, the overhead is larger than the gain. Measure before adding a pool.

javascript
const { Worker, isMainThread, parentPort } = require('node:worker_threads');

if (!isMainThread) {
  parentPort.on('message', (msg) => {
    if (msg.type === 'size') parentPort.postMessage({ size: msg.data.byteLength });
    if (msg.type === 'spin') { const end = Date.now() + msg.ms; while (Date.now() < end) {} parentPort.postMessage('done'); }
    if (msg.type === 'ready') parentPort.postMessage('ready');
  });
} else {
  const ask = (worker, message, transfer = []) =>
    new Promise((resolve) => { worker.once('message', resolve); worker.postMessage(message, transfer); });
  const time = async (fn) => { const t = performance.now(); await fn(); return performance.now() - t; };

  (async () => {
    // 1. Startup cost
    const startup = await time(async () => { const w = new Worker(__filename); await ask(w, { type: 'ready' }); globalThis.keep = w; });
    console.log('starting a worker takes more than 5 ms:', startup > 5);
    const worker = globalThis.keep;

    // 2. Copy versus transfer of 128 MB
    const copied = new ArrayBuffer(128 * 1024 * 1024);
    const copyMs = await time(() => ask(worker, { type: 'size', data: copied }));
    const moved = new ArrayBuffer(128 * 1024 * 1024);
    const moveMs = await time(() => ask(worker, { type: 'size', data: moved }, [moved]));
    console.log('copy keeps the sender buffer:', copied.byteLength > 0, '| transfer detaches it:', moved.byteLength === 0);
    console.log('transfer is faster than copy:', moveMs < copyMs);
    await worker.terminate();

    // 3. Four CPU tasks of 150 ms: main thread versus a pool of four workers
    const mainMs = await time(async () => { for (let i = 0; i < 4; i++) { const end = Date.now() + 150; while (Date.now() < end) {} } });
    const pool = Array.from({ length: 4 }, () => new Worker(__filename));
    await Promise.all(pool.map((w) => ask(w, { type: 'ready' })));
    const poolMs = await time(() => Promise.all(pool.map((w) => ask(w, { type: 'spin', ms: 150 }))));
    await Promise.all(pool.map((w) => w.terminate()));
    console.log('main thread needs more than 500 ms:', mainMs > 500, '| pool of 4 finishes under 400 ms:', poolMs < 400);

    // 4. A memory limit stops a greedy task, and the main thread survives
    const greedy = new Worker('const keep = []; while (true) keep.push(new Array(1e5).fill(1));', { eval: true, resourceLimits: { maxOldGenerationSizeMb: 24 } });
    const err = await new Promise((resolve) => greedy.once('error', resolve));
    console.log('greedy worker stopped with:', err.code);
  })();
}

Each line prints a yes or no fact about cost: worker startup, copy versus transfer, parallel speedup and a memory limit. Exact milliseconds are not printed because they change from run to run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): starting a worker takes more than 5 ms: true copy keeps the sender buffer: true | transfer detaches it: true transfer is faster than copy: true main thread needs more than 500 ms: true | pool of 4 finishes under 400 ms: true greedy worker stopped with: ERR_WORKER_OUT_OF_MEMORY

Key points

  • Workers are costly to start, so reuse them.
  • postMessage copies; a transfer list moves ArrayBuffers without copying.
  • Pool size is about the CPU core count for CPU-bound work.
  • resourceLimits keeps one task from exhausting memory.
  • Handle errors and exits, add timeouts, and bound the queue.

Common mistakes

  • Creating a new Worker for every request.
  • Sending huge objects by copy when a transfer would do.
  • Using more workers than cores for CPU-bound work.
  • Using workers for I/O work, which the event loop already handles.
  • Not handling the worker 'error' and 'exit' events.

Follow-ups

  • How does Piscina differ from a hand-written pool?
  • What is the difference between transferring and sharing an ArrayBuffer?
  • How would you cancel a task that is running in a worker?

Tips

  • Start with the costs, then the sizing rule.
  • Mention transfer lists, which many candidates miss.
  • Say 'measure first'.