ALL WRITINGS
May 10, 20261 min read
Backend
WebSockets
Redis
Node.js
System Design

How I Built a Real-Time Chat App with WebSockets, Redis & Node.js

A deep dive into building a production-ready real-time chat system — covering WebSocket connections, Redis pub/sub for horizontal scaling, message persistence, and the hard lessons I learned shipping it to 10,000 users.

Why I Chose WebSockets Over Polling

When I first started building the chat feature, my instinct was to use long-polling — it felt safe and familiar. But after hitting 200 concurrent users, the server was drowning in HTTP overhead. Each poll was a full request-response cycle just to say "nothing new yet." Switching to WebSockets dropped server CPU by 60% and made the UI feel instant.

The Architecture at a Glance

  • Node.js with the ws library for raw WebSocket handling
  • Redis pub/sub to fan messages out across multiple server instances
  • MongoDB for persisting chat history
  • Nginx as a reverse proxy with WebSocket upgrade headers
  • // server.js — WebSocket + Redis pub/sub
  • import { WebSocketServer } from 'ws';
  • import { createClient } from 'redis';

  • const wss = new WebSocketServer({ port: 8080 });
  • const publisher = createClient();
  • const subscriber = createClient();

  • await publisher.connect();
  • await subscriber.connect();

  • await subscriber.subscribe('chat:global', (message) => {
  •   wss.clients.forEach((client) => {
  •     if (client.readyState === WebSocket.OPEN) {
  •       client.send(message);
  •     }
  •   });
  • });

  • wss.on('connection', (ws, req) => {
  •   ws.on('message', async (data) => {
  •     const msg = JSON.parse(data);
  •     await publisher.publish('chat:global', JSON.stringify({
  •       text: msg.text,
  •       timestamp: Date.now(),
  •     }));
  •   });
  • });

    Your quote here...

    The hardest part of real-time systems isn't the real-time part — it's keeping state consistent when three different server instances are all receiving messages simultaneously.


  • https://images.unsplash.com/photo-1555066931-4365d14bab8c?w=1200&q=80



← All Writings