What is Node.js cluster module and how to use it

· Category: Node.js

Short answer

The Node.js cluster module forks multiple worker processes from a master process. Workers share the same server port using the operating system's scheduler, allowing a single Node.js app to utilize all CPU cores.

Details

Because Node.js is single-threaded, one process can only use one core. The cluster module spawns child processes that run the same application code. The master process listens on a port and distributes incoming connections to workers via round-robin (on most platforms). If a worker crashes, the master can fork a replacement.

While the cluster module is built-in, many teams prefer PM2 or container orchestration for production. If you are running in containers, see How to build a Docker image to package your clustered app. For true parallelism with threads rather than processes, also read about How to use Node.js worker threads for CPU-intensive tasks.

Tips

  • Do not store in-memory session state in a clustered app unless you use sticky sessions or an external store.
  • Use cluster.isPrimary (or cluster.isMaster in older versions) to separate master logic from worker logic.
  • For monitoring multiple workers, consider How to monitor applications with Prometheus and Grafana for aggregate metrics.