Scaling WebSocket Connections with Redis Pub/Sub for Multi-Instance Node.js Applications
WebSocket servers usually work great in single-instance deployments. But when you scale your application across multiple servers or containers, you run into a problem: clients connected to one instance can't communicate with clients connected to another. This is where Redis Pub/Sub comes to the rescue.
Why Redis Pub/Sub?
Redis Pub/Sub allows different processes (in our case, different WebSocket server instances) to subscribe to the same message channel. When a message is published, all subscribers receive it — enabling real-time messaging across your entire infrastructure.
Step 1: Install Dependencies
npm install ws redis
Step 2: WebSocket Server with Redis Integration
// server.js
const WebSocket = require('ws');
const { createClient } = require('redis');
const wss = new WebSocket.Server({ port: 8080 });
const redisPub = createClient();
const redisSub = createClient();
redisPub.connect();
redisSub.connect();
const CHANNEL = 'global_messages';
let clients = new Set();
wss.on('connection', (ws) => {
clients.add(ws);
ws.on('message', async (message) => {
// Publish to Redis
await redisPub.publish(CHANNEL, message.toString());
});
ws.on('close', () => {
clients.delete(ws);
});
});
// Listen for Redis messages and broadcast to local clients
redisSub.subscribe(CHANNEL, (message) => {
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
Step 3: Test with Multiple Server Instances
You can now spin up multiple Node.js server instances, possibly on different ports or machines, and they'll all stay in sync via Redis. Just make sure each instance subscribes to the same Redis channel.
Step 4: A Simple Client
Conclusion
By integrating Redis Pub/Sub, you’ve unlocked horizontal scalability for your WebSocket infrastructure. This approach is production-ready, fast, and used by many real-time apps at scale. You can expand it further with namespaces, authentication layers, and message types for complex workflows.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift