Advertisement
Intermediate Node.js, Clustering & Worker Threads

Why does Node.js provide a cluster module, given that a single Node.js process is single-threaded?

Short answer

A single process runs JavaScript on one main thread, using only one CPU core -- the cluster module forks multiple worker processes (typically one per core), each an independent copy of the app sharing the same listening port, letting a Node.js app utilize all available cores.

Save Node.js mock interview
Advertisement
AModel answer
A single process runs JavaScript on one main thread, using only one CPU core -- the cluster module forks multiple worker processes (typically one per core), each an independent copy of the app sharing the same listening port, letting a Node.js app utilize all available cores.
const cluster = require('node:cluster');
const os = require('node:os');
if (cluster.isPrimary) {
  for (let i = 0; i < os.cpus().length; i++) cluster.fork();
} else {
  require('./server');
}
Real-world example
An API deployed to an 8-core server using only one core adds cluster.fork() to spawn eight workers, roughly increasing throughput eight-fold under CPU-bound load.
Likely follow-ups
  • How does the cluster module's shared-port mechanism distribute connections across workers?
  • What state can be shared between cluster workers, given they're separate OS processes?
Related topics