Skip to content

Implementing sticky sessions with socket.io and cluster module #3992

Answered by darrachequesne
crupeng-1 asked this question in Q&A
Discussion options

You must be logged in to vote

You can use the cluster adapter and the @socket.io/sticky package for this:

const cluster = require("cluster");
const http = require("http");
const { Server } = require("socket.io");
const numCPUs = require("os").cpus().length;
const { setupMaster, setupWorker } = require("@socket.io/sticky");
const { createAdapter, setupPrimary } = require("@socket.io/cluster-adapter");

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  const httpServer = http.createServer();

  // setup sticky sessions
  setupMaster(httpServer, {
    loadBalancingMethod: "least-connection",
  });

  // setup connections between the workers
  setupPrimary();

  // needed for packets containing…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@crupeng-1
Comment options

Answer selected by crupeng-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants