DEV Community

Cover image for Scaling WebSocket Connections with Redis Pub/Sub for Multi-Instance Node.js Applications
HexShift
HexShift

Posted on

1 1 1

Scaling WebSocket Connections with Redis Pub/Sub for Multi-Instance Node.js Applications

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

<!DOCTYPE html>
<html>
<body>
  <textarea id="chat" rows="10" cols="50"></textarea><br/>
  <input id="input" />
  <button onclick="sendMessage()">Send</button>

  <script>
    const socket = new WebSocket('ws://localhost:8080');
    const chat = document.getElementById('chat');

    socket.onmessage = (event) => {
      chat.value += event.data + "\n";
    };

    function sendMessage() {
      const input = document.getElementById('input');
      socket.send(input.value);
      input.value = '';
    }
  </script>
</body>
</html>

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

Postmark Image

20% off for developers shipping features, not fixing email

Build your product without worrying about email infrastructure. Our reliable delivery, detailed analytics, and developer-friendly API let you focus on shipping features that matter.

Start free

Top comments (1)

Collapse
 
nevodavid profile image
Nevo David

Amazing how easy it is to connect lots of servers together with Redis like this!

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️