Node.js Course
Node.js
/
Advanced

Cluster Module

Definition

The core Node.js module used to fork the main process into multiple child processes that can all share the same server ports.

Explain Like I'm New

The built-in mechanism that makes Clustering possible. The `cluster` module is essentially a specialized wrapper around the `child_process.fork()` method, specifically designed to allow multiple clones to listen on port 3000 simultaneously without throwing an 'Address in use' error.

Real World Example

It is the exact underlying technology that PM2 uses to scale your application across CPU cores.

Common Use Cases

  • •Building custom load balancers
  • •High-performance API servers

Interactive Example

const cluster = require('cluster');
const http = require('http');

// The Master acts as the traffic cop
if (cluster.isPrimary) {
  console.log(`Primary ${process.pid} is running`);

  // Fork 2 workers
  cluster.fork();
  cluster.fork();

  cluster.on('exit', (worker, code, signal) => {
    console.log(`Worker ${worker.process.pid} died`);
  });
} 
// The Workers do the actual HTTP processing
else {
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Hello from Worker ${process.pid}\n`);
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}

// If you hit localhost:8000 multiple times, you will see different PIDs responding!

Interview Questions

basic

  • What boolean property checks if the current code is running in the main orchestrator process?

intermediate

  • How does the Cluster module magically allow 8 clones to share port 3000?

Flash Cards

Question

What property?

Click to reveal answer
Answer

`cluster.isMaster` (or `cluster.isPrimary` in newer Node versions).

Question

How do they share a port?

Click to reveal answer
Answer

The clones don't actually bind to the port! The Master process binds to port 3000. When a request hits the port, the Master intercepts it and uses a Round-Robin algorithm to silently hand the TCP connection to one of the worker clones via IPC (Inter-Process Communication).