back to index

Multi-Process Node with cluster

Using Node's cluster module to spread work across cores.

published Dec 07, 2017 tags #node #concurrency

~/posts/multi-process-node $ cat post.md

/ LANG EN / 中文
/ THEME / /

On a multi-core box, Node can boost throughput by going multi-process. The built-in cluster module does exactly that, with an API that feels close to C.

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

if (cluster.isMaster) {
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on("exit", function (worker, code, signal) {
        console.log(`worker ${worker.process.pid} died`);
    });
} else {
    http.createServer(function (req, res) {
        res.writeHead(200);
        res.end("hello world\n");
    }).listen(8000);
}

Structurally, it translates back to something like:

int numCPUs = /* num CPUs */;
for (int i = 0; i < numCPUs; i++) {
    if (fork() == 0) {
        // createServer
    }
}

This setup is in GHOTI-CLI now.

back to index