← Back to Node.js, page 2

nodejs-0035 · Medium mid

When and how do you use worker_threads in Node.js, and how is data passed between threads?

worker_threads runs JavaScript in a separate thread with its own event loop and V8 instance, so CPU-heavy work does not block the main thread. Threads talk with postMessage. Data is copied with the structured clone algorithm, transferred (ArrayBuffer moves without copying), or shared (SharedArrayBuffer).

Full answer

Use worker threads for CPU-bound work: image resizing, parsing a large file, hashing, compression in JavaScript, calculations. They do not help I/O-bound work, because async I/O already runs without blocking.

How it works:

  • new Worker(filename or code, { workerData }) starts a thread. Each worker has its own event loop, its own memory heap and its own module cache. Starting one costs tens of milliseconds and some megabytes, so reuse workers with a pool.
  • The worker file uses parentPort.postMessage(data) to send and parentPort.on('message') to receive. The main thread does the same with worker.postMessage and worker.on('message').
  • workerData is the initial copy of data given to the worker.

Passing data:

  1. Copy (default): the structured clone algorithm copies objects, arrays, Maps, Dates, typed arrays. Functions and class instances with methods do not survive.
  2. Transfer: put ArrayBuffers in a transfer list, postMessage(buf, [buf]). Ownership moves with no copy, and the sender's buffer becomes empty (byteLength 0).
  3. Share: a SharedArrayBuffer is visible to both threads. Use Atomics to avoid races.

Errors: an uncaught exception in a worker emits 'error' on the Worker object, and 'exit' follows. Also available: worker.terminate(), and resourceLimits to cap memory.

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

if (isMainThread) {
  // ---- main thread ----
  let ticks = 0;
  const timer = setInterval(() => ticks++, 10); // proves the main thread stays free

  const worker = new Worker(__filename, { workerData: { n: 36 } });
  worker.once('message', (result) => {
    clearInterval(timer);
    console.log('fib(36) from the worker:', result);
    console.log('main thread kept running while waiting:', ticks > 0);

    // Transfer an ArrayBuffer: the main thread loses it.
    const buffer = new ArrayBuffer(1024);
    const second = new Worker(__filename, { workerData: { transfer: true } });
    second.once('message', (size) => {
      console.log('worker received', size, 'bytes | main copy length after transfer:', buffer.byteLength);
      second.terminate();
    });
    second.postMessage(buffer, [buffer]);
  });
  worker.once('error', (err) => console.log('worker failed:', err.message));
} else if (workerData.transfer) {
  // ---- worker that receives a transferred buffer ----
  parentPort.once('message', (buffer) => parentPort.postMessage(buffer.byteLength));
} else {
  // ---- worker that does CPU work ----
  const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
  parentPort.postMessage(fib(workerData.n));
}

The same file acts as both the main program and the worker, which keeps the example short. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): fib(36) from the worker: 14930352 main thread kept running while waiting: true worker received 1024 bytes | main copy length after transfer: 0

Key points

  • Use for CPU-bound work, not for I/O.
  • Each worker has its own event loop and heap.
  • Messages are cloned, transferred or shared.
  • Pool workers because start-up is costly.

Common mistakes

  • Using workers for network or file I/O.
  • Creating a new worker per request.
  • Sending huge objects by copy on every message.
  • Expecting functions or class instances to cross the thread boundary.

Follow-ups

  • How would you cancel a long worker task?
  • What is the difference between worker_threads and child_process.fork?
  • How do you share a counter safely between threads?

Tips

  • Say 'CPU-bound' first, then show the main thread stays responsive.
  • Describe the three ways to move data in one sentence each.
  • Bring up pooling before the interviewer asks.