Multi-process in Node.js

André Werlang (@awerlang)

Node.js Architecture

Cluster Use Cases

  • Restart on Failure
  • Multi-Core
  • Inter-Process Communication

Definitions

  • Program: the source code
  • Process: a runtime instance of a program
  • Cluster: a group of processes in a single machine
  • Master: initial processes, starts the others
  • Worker: a child process

Comparison

  • child_process: create any process
  • cluster: create a copy of a single Node.js process

Usage


const cluster = require('cluster');

if (cluster.isMaster) {
    const numWorkers = require('os').cpus().length;
    for (let i = 0; i < numWorkers; i++) {
        const newWorker = cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
        cluster.fork();
    });
} else {
    require('./app');
}
                

* cluster is a native module, no need to npm install

Node.js Runtime

API

  • master
    • cluster.isMaster
    • cluster.fork(env?)
    • cluster.on('online', cb)
    • cluster.on('exit', cb)
    • cluster.workers
    • os.cpus().length
  • worker
    • cluster.isWorker
    • cluster.worker

API #2

  • Inter-Process Communication
    • cluster.on('message', cb)
    • process.send(message, sendHandle?)

Beware

  • debug
    • Start the child worker you want to debug

Alternatives

  • forever
  • pm2

References

  • https://nodejs.org/api/cluster.html

THANKS