{ "source": "doc/api/cluster.markdown", "modules": [ { "textRaw": "Cluster", "name": "cluster", "stability": 2, "stabilityText": "Unstable", "desc": "

A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

\n

The cluster module allows you to easily create child processes that\nall share server ports.\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(worker, code, signal) {\n    console.log('worker ' + worker.process.pid + ' died');\n  });\n} else {\n  // Workers can share any TCP connection\n  // In this case its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
\n

Running node will now share port 8000 between the workers:\n\n

\n
% NODE_DEBUG=cluster node server.js\n23521,Master Worker 23524 online\n23521,Master Worker 23526 online\n23521,Master Worker 23523 online\n23521,Master Worker 23528 online
\n

This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

\n

Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

\n", "miscs": [ { "textRaw": "How It Works", "name": "How It Works", "type": "misc", "desc": "

The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

\n

The cluster module supports two methods of distributing incoming\nconnections.\n\n

\n

The first one (and the default one on all platforms except Windows),\nis the round-robin approach, where the master process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.\n\n

\n

The second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.\n\n

\n

The second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.\n\n

\n

Because server.listen() hands off most of the work to the master\nprocess, there are three cases where the behavior between a normal\nnode.js process and a cluster worker differs:\n\n

\n
    \n
  1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  4. \n
  5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

There is no routing logic in Node.js, or in your program, and no shared\nstate between the workers. Therefore, it is important to design your\nprogram such that it does not rely too heavily on in-memory data objects\nfor things like sessions and login.\n\n

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

\n" } ], "properties": [ { "textRaw": "cluster.schedulingPolicy", "name": "schedulingPolicy", "desc": "

The scheduling policy, either cluster.SCHED_RR for round-robin or\ncluster.SCHED_NONE to leave it to the operating system. This is a\nglobal setting and effectively frozen once you spawn the first worker\nor call cluster.setupMaster(), whatever comes first.\n\n

\n

SCHED_RR is the default on all operating systems except Windows.\nWindows will change to SCHED_RR once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.\n\n

\n

cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are "rr" and "none".\n\n

\n" }, { "textRaw": "`settings` {Object} ", "name": "settings", "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the node executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "list of string arguments passed to the node executable." }, { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" } ], "desc": "

After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.\n\n

\n

It is effectively frozen after being set, because .setupMaster() can\nonly be called once.\n\n

\n

This object is not supposed to be changed or set manually, by you.\n\n

\n" }, { "textRaw": "`isMaster` {Boolean} ", "name": "isMaster", "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

\n" }, { "textRaw": "`isWorker` {Boolean} ", "name": "isWorker", "desc": "

True if the process is not a master (it is the negation of cluster.isMaster).\n\n

\n" }, { "textRaw": "`worker` {Object} ", "name": "worker", "desc": "

A reference to the current worker object. Not available in the master process.\n\n

\n
var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
\n" }, { "textRaw": "`workers` {Object} ", "name": "workers", "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

\n

A worker is removed from cluster.workers after the worker has disconnected and\nexited. The order between these two events cannot be determined in advance.\nHowever, it is guaranteed that the removal from the cluster.workers list happens\nbefore last 'disconnect' or 'exit' event is emitted.\n\n

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
\n

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

\n
socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
\n" } ], "events": [ { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "params": [], "desc": "

When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create your own timeout.\n\n

\n
var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "params": [], "desc": "

After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.\n\n

\n
cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

After calling listen() from a worker, when the 'listening' event is emitted on\nthe server, a listening event will also be emitted on cluster in the master.\n\n

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

\n
cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
\n

The addressType is one of:\n\n

\n\n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "params": [], "desc": "

Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).\n\n

\n

There may be a delay between the disconnect and exit events. These events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.\n\n

\n
cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

When any of the workers die the cluster module will emit the 'exit' event.\n\n

\n

This can be used to restart the worker by calling .fork() again.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  console.log('worker %d died (%s). restarting...',\n    worker.process.pid, signal || code);\n  cluster.fork();\n});
\n

See child_process event: 'exit'.\n\n

\n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "params": [], "desc": "

Emitted every time .setupMaster() is called.\n\n

\n

The settings object is the cluster.settings object at the time\n.setupMaster() was called and is advisory only, since multiple calls to\n.setupMaster() can be made in a single tick.\n\n

\n

If accuracy is important, use cluster.settings.\n\n

\n" } ], "methods": [ { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.\n\n

\n

Note that:\n\n

\n\n

Example:\n\n

\n
var cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker
\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "return {Worker object} ", "name": "return", "type": "Worker object" }, "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment. ", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

Spawn a new worker process.\n\n

\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} called when all workers are disconnected and handles are closed ", "name": "callback", "type": "Function", "desc": "called when all workers are disconnected and handles are closed", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

Calls .disconnect() on each worker in cluster.workers.\n\n

\n

When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.\n\n

\n

The method takes an optional callback argument which will be called when finished.\n\n

\n

This can only be called from the master process.\n\n

\n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "desc": "

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

\n", "properties": [ { "textRaw": "`id` {String} ", "name": "id", "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.\n\n

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

\n" }, { "textRaw": "`process` {ChildProcess object} ", "name": "process", "desc": "

All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.\n\n

\n

See: Child Process module\n\n

\n

Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .suicide is not true. This protects against accidental\ndisconnection.\n\n

\n" }, { "textRaw": "`suicide` {Boolean} ", "name": "suicide", "desc": "

Set by calling .kill() or .disconnect(), until then it is undefined.\n\n

\n

The boolean worker.suicide lets you distinguish between voluntary and accidental\nexit, the master may choose not to respawn a worker based on this value.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// kill worker\nworker.kill();
\n" } ], "methods": [ { "textRaw": "worker.send(message[, sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker.\n\n

\n

In a worker you can also use process.send(message), it is the same function.\n\n

\n

This example will echo back all messages from the master:\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
\n" }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "String", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "default": "'SIGTERM'" } ] } ], "desc": "

This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.\n\n

\n

Causes .suicide to be set.\n\n

\n

This method is aliased as worker.destroy() for backwards compatibility.\n\n

\n

Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.\n\n

\n" }, { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "desc": "

In a worker, this function will close all servers, wait for the 'close' event on\nthose servers, and then disconnect the IPC channel.\n\n

\n

In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.\n\n

\n

Causes .suicide to be set.\n\n

\n

Note that after a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker\nwill close allowing it to die gracefully.\n\n

\n

The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.\n\n

\n

Note that in a worker, process.disconnect exists, but it is not this function,\nit is disconnect.\n\n

\n

Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe disconnect event has not been emitted after some time.\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', function(msg) {\n    if(msg === 'shutdown') {\n      // initiate graceful close of any connections to server\n    }\n  });\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.isDead()", "type": "method", "name": "isDead", "desc": "

This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.isConnected()", "type": "method", "name": "isConnected", "desc": "

This function returns true if the worker is connected to its master via its IPC\nchannel, false otherwise. A worker is connected to its master after it's been\ncreated. It is disconnected after the disconnect event is emitted.\n\n

\n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

This event is the same as the one provided by child_process.fork().\n\n

\n

In a worker you can also use process.on('message').\n\n

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\n  function messageHandler(msg) {\n    if (msg.cmd && msg.cmd == 'notifyRequest') {\n      numReqs += 1;\n    }\n  }\n\n  // Start workers and listen for messages containing notifyRequest\n  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "desc": "

Similar to the cluster.on('online') event, but specific to this worker.\n\n

\n
cluster.fork().on('online', function() {\n  // Worker is online\n});
\n

It is not emitted in the worker.\n\n

\n", "params": [] }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

Similar to the cluster.on('listening') event, but specific to this worker.\n\n

\n
cluster.fork().on('listening', function(address) {\n  // Worker is listening\n});
\n

It is not emitted in the worker.\n\n

\n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

Similar to the cluster.on('disconnect') event, but specfic to this worker.\n\n

\n
cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n});
\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

Similar to the cluster.on('exit') event, but specific to this worker.\n\n

\n
var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n});
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

This event is the same as the one provided by child_process.fork().\n\n

\n

In a worker you can also use process.on('error').\n

\n", "params": [] } ] } ], "type": "module", "displayName": "Cluster" } ] }