Node.js Worker Threads vs Cluster: When to pick each

Last month we rewrote a thumbnail‑generation service that was choking on a single event loop. The codebase is pure JavaScript except for a native lib‑jpeg wrapper. We tried two approaches: spawning a cluster of processes and using worker_threads to run the heavy conversion.

With cluster each worker is a full Node process. Memory is duplicated, so the native addon loads separately in every worker. The upside is isolation – a crash in one worker never brings down the others, and the OS can schedule each process on a different core without any extra plumbing. The downside is higher RAM usage and a warm‑up cost for each process (the native lib takes ~30 ms to load). IPC is done via process.send, which is simple but incurs JSON serialization overhead.

With worker_threads we keep a single V8 instance and share memory buffers. The native addon can be required once in the main thread and then reused, cutting start‑up time dramatically. Threads communicate via MessageChannel or shared ArrayBuffer, which is fast for bulk data like image buffers. However, the thread pool is still limited by the worker_threads default max (usually the number of CPU cores) and a bug in the lib‑jpeg binding caused occasional segfaults when accessed from multiple threads. Debugging is also trickier because stack traces are merged.

// cluster example
const cluster = require('cluster');
if (cluster.isMaster) {
  for (let i = 0; i < require('os').cpus().length; i++) {
    cluster.fork();
  }
} else {
  require('./worker');
}

// worker_threads example
const { Worker } = require('worker_threads');
new Worker('./worker.js');

Questions

  1. How do you handle graceful shutdown of a mixed pool of worker_threads and cluster workers in production?
  2. Have you seen memory‑leak patterns when reusing native addons across threads, and what mitigations worked for you?
Backend#Node.js#Backend
0

0 Answers

Post Your Answer

Use ``` code ``` for syntax highlighting