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

**URL:** <https://forum.nocodework.com/t/how-i-fixed-my-two-node-nightmare-scaling-websockets-with-redis/60>\
**Category:** General\
**Tags:** communityinsights\
**Created:** [May 26, 2025, 6:03am UTC](https://forum.nocodework.com/t/how-i-fixed-my-two-node-nightmare-scaling-websockets-with-redis/60 "2025-05-26T06:03:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Firoz\_Tyagi](https://yyz2.discourse-cdn.com/flex032/user_avatar/forum.nocodework.com/firoz_tyagi/32/25_2.png) [@Firoz\_Tyagi](https://forum.nocodework.com/u/Firoz_Tyagi)\
**Post date:** [May 26, 2025, 6:03am UTC](https://forum.nocodework.com/t/how-i-fixed-my-two-node-nightmare-scaling-websockets-with-redis/60/1 "2025-05-26T06:03:08Z")

</div>

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 ☹

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](http://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. 😂
