Back to Node.js tutorials
Advanced18 min read

WebSockets & Realtime

Build realtime features with ws or Socket.IO, manage rooms, and scale pub/sub across multiple server instances.

WebSocket Basics

WebSockets upgrade HTTP connections to persistent bidirectional channels. The ws library provides low-level server and client APIs in Node.

Use WebSockets for chat, live dashboards, and collaborative editing where polling would waste bandwidth and add latency.

Handle ping/pong heartbeats and close codes to detect dead connections and free resources.

  • Authenticate during handshake with query tokens or cookies
  • Limit message size to prevent memory abuse
  • Close connections gracefully on server shutdown
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', ws => {
  ws.on('message', data => ws.send(`echo:${data}`));
});

Socket.IO Features

Socket.IO adds namespaces, rooms, automatic reconnection, and fallback transports atop Engine.IO. It simplifies broadcasting to groups of clients.

Attach Socket.IO to an existing HTTP server so REST and realtime share a port behind the same load balancer sticky rules.

Version client and server together; protocol mismatches cause confusing connection failures.

  • Use rooms instead of manual client ID lists
  • Validate every incoming event payload
  • Expose metrics on connected clients and message rates
import { Server } from 'socket.io';
const io = new Server(httpServer);
io.on('connection', socket => {
  socket.join(`room:${socket.handshake.auth.tenantId}`);
  socket.on('chat:message', msg => io.to(`room:${msg.room}`).emit('chat:message', msg));
});

Scaling Realtime

Multiple Node instances require a Redis adapter or message broker so broadcasts reach clients on other machines. Sticky sessions help during WebSocket handshake on load balancers.

Offload heavy work from the event loop—do not block message handlers with CPU-intensive tasks.

Backpressure: drop or queue messages when clients cannot keep up, with monitoring alerts.

  • Horizontal scale with Redis pub/sub adapter for Socket.IO
  • Use separate namespaces for admin versus user traffic
  • Load test connection churn during deploy simulations

Get In Touch


Ready to discuss your next project? Drop me a message.