How I fixed my two-node nightmare - Scaling WebSockets with Redis

I was building a real time notification system using Nodejs and websockets. Everything was working great until I ran two server instances. Suddenly, some users stopped getting updates. Messages didn’t reach everyone. I was confused.

The problem? Each server had its own memory, and they were not talking to each other. Let me show you how I fixed this using Redis Pub/Sub in a simple and clean way.

Here’s what I did initially:

  • Used Socket IO to handle real-time communication.
  • Stored socket IDs in memory like this:

const socketMap = {};
io.on(“connection”, (socket) => {
socketMap[socket.userId] = socket.id;
});

This worked fine on one server. But when I added another server, it broke :frowning:

Why? Because each server had a different socketMap. So if a user connected to Server A, but a message was sent from Server B, it would not reach them.

The Fix: Redis Pub/Sub:

Redis is a super-fast memory store. Even better, Socket IO has a Redis adapter that lets multiple servers share socket data.

const { createServer } = require(“http”);
const { Server } = require(“socket.io”);
const { createAdapter } = require(“@socket.io/redis-adapter”);
const { createClient } = require(“redis”);

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

const pubClient = createClient({ url: “redis://localhost:6379” });
const subClient = pubClient.duplicate();

Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(createAdapter(pubClient, subClient));

io.on(“connection”, (socket) => {
console.log(“User connected:”, socket.id);

How It Works -

  • When Server A emits a message, Redis publishes it.
  • Server B (and others) get the message and send it to the correct client.
  • It’s like a shared memory hub that keeps all your servers in sync.

If you are using WebSockets with Node js and planning to scale beyond one server, use Redis. It saved me hours of debugging and made my app production ready.

Hope this helped you avoid the same headaches I had. :joy:

1 Like