As of version 0.6.0 of node, load multiple process load balancing is available for node. The concept of forking and processes isn ' t new to me. Yet, it wasn ' t obvious to me about this is implemented at first. It ' s quite easy-to-use however:
var cluster = require (' cluster ');
var http = require (' http ');
var Numcpus = require (' OS '). CPUs (). length;
if (cluster.ismaster) {
//Fork workers.
for (var i = 0; i < Numcpus; i++) {
cluster.fork ();
}
Cluster.on (' Death ', function (worker) {
Console.log (' worker ' + worker.pid + ' died ');
});
} else {
//Worker processes has a HTTP server.
http. Server (function (req, res) {
Res.writehead);
Res.end ("Hello world\n");
}). Listen (8000);
}
This was quite a beautiful API, but it hides some clever details. For instance, how are possible for all child processes to each open up port 8000 and start listening? The answer is, the cluster module is just a wrapper around child_process.fork and net. Server.listen is aware of the cluster module. Specifically, Cluster.fork uses child_process.fork to create child processes with special variable set in their environmen TS to indicate cluster was used. Specifically Process.env.NODE_WORKER_ID is non-zero for such children.envcopy[' node_worker_id '] = ID; var worker = Fork(workerfilename, Workerargs, { env: envcopy });Then net. Server.listen checks to see if Process.env.NODE_WORKER_ID is set. If So, then the current process was a child created cluster. Instead of trying to start accepting connections in this port, a file handle is requested from the parent process:
Inside Net.js
require(' cluster '). _getserver(address, Port, addresstype, function(handle) { self. _handle = handle; self. _listen2(address, Port, addresstype); }); //inside Cluster.js
Cluster. _getserver = function(address, Port, addresstype, cb) { assert(cluster. Isworker); Querymaster({ cmd: "Queryserver", address: address, Port: Port, addresstype: addresstype }, function(msg, handle) { CB(handle); });};Finally, this handle are listened on instead of creating a new handle. At which point you have another process, which is listening on the same port. Quite Clever, though I think the beauty of the API comes at the cost of some don't so hideous hacks inside the API.
How node. js multiprocess Load Balancing Works