Node.js Developer interview question · Most asked

Compare `worker_threads`, `cluster` and `child_process`.

Summary

worker_threads run JavaScript in parallel threads within one process (with message passing and optional shared memory), good for CPU-bound tasks. cluster forks multiple processes sharing a server port to use all CPU cores for request handling. child_process spawns separate programs or Node scripts (spawn, exec, fork).

Longer Answer

In containerized deployments, many teams skip cluster and run one process per container, scaling with the orchestrator. Worker pools (e.g., Piscina) manage reusable workers. Workers have their own event loop and V8 isolate; transfer large buffers with transferables or SharedArrayBuffer.

Code Example

// main.js
import { Worker } from "node:worker_threads";

function runHash(data) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(new URL("./hash-worker.js", import.meta.url), { workerData: data });
    worker.once("message", resolve);
    worker.once("error", reject);
  });
}

// hash-worker.js
import { parentPort, workerData } from "node:worker_threads";
import { createHash } from "node:crypto";
parentPort.postMessage(createHash("sha256").update(workerData).digest("hex"));

Key Points

  • Workers: threads for CPU work
  • Cluster: multi-process servers
  • child_process: external programs
  • Containers: often one process per container

More most-asked Node.js Developer questions

← All Node.js Developer questions