Damien Arrachequesne 0c431243e2 refactor: use the ClusterAdapter class from socket.io-adapter package
The ClusterAdapter class has been moved to [1], so that this adapter
only needs to implement to pub/sub mechanism.

Also, [2] should reduce the number of "timeout reached: only x
responses received out of y" errors, since the fetchSockets() requests
will now succeed even if a server leaves the cluster.

[1]: https://github.com/socketio/socket.io/tree/main/packages/socket.io-adapter
[2]: 0e23ff0cc6
2025-10-16 19:16:20 +02:00
2025-10-16 12:03:32 +02:00
2021-06-22 07:02:16 +02:00
2021-06-22 07:02:16 +02:00
2023-03-24 17:32:35 +01:00
2021-06-22 07:02:16 +02:00
2021-06-22 07:02:16 +02:00

Socket.IO cluster adapter

The @socket.io/cluster-adapter package allows broadcasting packets between multiple Socket.IO servers.

Adapter diagram

It can be used in conjunction with @socket.io/sticky to broadcast packets between the workers of the same Node.js cluster.

Supported features:

Related packages:

Table of contents

Installation

npm install @socket.io/cluster-adapter

Usage

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 buffers (you can ignore it if you only send plaintext objects)
  // Node.js < 16.0.0
  cluster.setupMaster({
    serialization: "advanced",
  });
  // Node.js > 16.0.0
  // cluster.setupPrimary({
  //   serialization: "advanced",
  // });

  httpServer.listen(3000);

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

  cluster.on("exit", (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });
} else {
  console.log(`Worker ${process.pid} started`);

  const httpServer = http.createServer();
  const io = new Server(httpServer);

  // use the cluster adapter
  io.adapter(createAdapter());

  // setup connection with the primary process
  setupWorker(io);

  io.on("connection", (socket) => {
    /* ... */
  });
}

License

MIT

Description
No description provided
Readme MIT 42 MiB
Languages
TypeScript 64.1%
JavaScript 35.8%