KarimS
KarimS

Reputation: 3892

Nodejs cluster module - How it works while listening on sockets

i have some difficulty understanding this piece of code :

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

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

I don't understand the relation between the parent and the worker. The parent spawns children processes and waits for them, but how the load is split between the workers (children)

How is it possible for multiple processes to bind to the same port, in the child's process?

Upvotes: 2

Views: 933

Answers (1)

manikawnth
manikawnth

Reputation: 3229

I'm not sure if you have read this. There's a beautiful explanation.
https://nodejs.org/dist/latest/docs/api/cluster.html#cluster_how_it_works
Simply, the cluster module will take care of this. You need not worry about this.

Multiple processes are not bound to the same port

Method1 (Round robin approach - Default except on windows):
Master Primary is bound to the port, listens and accepts incoming connections and it distributes work to the slaves workers and the communication happens through ipc sockets
Here every worker gets an equal opportunity to the work load.

Method 2 (Unbalanced approach):
Primary is bound to port (Remember, it doesn't accept the connections) and the listening socket is shared to the worker processes.
Now, it is the responsibility of workers to accept the connections and process the requests.
Here it's up to the underlying OS to distribute the work across the processes. If the work is small, most of the times its the same worker that accepts most connections and does the work.

Upvotes: 4

Related Questions