Node.js & Libuv•Part 4: Express, Fastify, APIs & Middleware (36 - 50)
Scaling WebSockets across multiple Node.js instances.
In Simple Words: Use the Redis Pub/Sub Adapter (or Redis Streams). When a client on Instance A sends a message to a room, Instance A publishes the event to Redis, which broadcasts it to all other Node instances holding active WebSocket clients in that room.
javascript
const { Server } = require('socket.io');
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');
const pubClient = createClient({ url: 'redis://localhost:6379' });
const subClient = pubClient.duplicate();
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(createAdapter(pubClient, subClient));
});