Categories
JavaScript Answers

How to scale socket.IO to multiple Node.js processes using cluster?

Spread the love

Sometimes, we want to scale socket.IO to multiple Node.js processes using cluster.

In this article, we’ll look at how to scale socket.IO to multiple Node.js processes using cluster.

How to scale socket.IO to multiple Node.js processes using cluster?

To scale socket.IO to multiple Node.js processes using cluster, we can use cluster to create workers processes.

For instance, we write

const cluster = require("cluster");
const os = require("os");

if (cluster.isMaster) {
  const server = require("http").createServer();
  const io = require("socket.io").listen(server);

  const RedisStore = require("socket.io/lib/stores/redis");
  const redis = require("socket.io/node_modules/redis");

  io.set(
    "store",
    new RedisStore({
      redisPub: redis.createClient(),
      redisSub: redis.createClient(),
      redisClient: redis.createClient(),
    })
  );

  setInterval(function () {
    io.sockets.emit("data", "payload");
  }, 1000);

  for (let i = 0; i < os.cpus().length; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker, code, signal) => {
    console.log("worker " + worker.process.pid + " died");
  });
}

if (cluster.isWorker) {
  const express = require("express");
  const app = express();

  const http = require("http");
  const server = http.createServer(app);
  const io = require("socket.io").listen(server);

  const RedisStore = require("socket.io/lib/stores/redis");
  const redis = require("socket.io/node_modules/redis");

  io.set(
    "store",
    new RedisStore({
      redisPub: redis.createClient(),
      redisSub: redis.createClient(),
      redisClient: redis.createClient(),
    })
  );

  io.sockets.on("connection", (socket) => {
    socket.emit("data", "connected to worker: " + cluster.worker.id);
  });

  app.listen(80);
}

to create a server on the master with

const server = require('http').createServer();

Then we call cluster.fork(); to create worker processes.

Then we create express servers on the workers with

const server = http.createServer(app);

We use Redis to do the caching with both the cluster master and worker.

Conclusion

To scale socket.IO to multiple Node.js processes using cluster, we can use cluster to create workers processes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *