Module P-9·23 min read

WebSocket protocol vs HTTP, Socket.IO rooms and namespaces, Server-Sent Events, long polling, and scaling real-time across processes with the Redis adapter.

Module P-9 — WebSockets and Real-Time Communication

What this module covers: HTTP's request-response model requires the client to ask for data. Real-time features — live chat, collaborative editing, presence indicators, live dashboards — require the server to push data the moment it changes. This module covers the WebSocket protocol upgrade, building with Socket.IO including rooms and namespaces, Server-Sent Events for one-directional streaming, long polling as a fallback, and the Redis adapter that scales real-time connections across multiple server instances.


HTTP vs WebSocket

HTTP is a half-duplex, stateless protocol. Every interaction is client-initiated: request → response → connection closes. The server cannot send data unless the client asks.

WebSocket is a full-duplex, stateful protocol over a single TCP connection. After the initial HTTP upgrade handshake, both sides can send frames at any time with minimal overhead (2–14 byte header per frame vs 200–800 bytes for an HTTP request).

text

The WebSocket handshake is a standard HTTP request with Connection: Upgrade and Upgrade: websocket headers. After the 101 response, the protocol switches and HTTP is no longer involved.


Raw WebSocket with the ws Library

bash
typescript
typescript

Socket.IO: Rooms, Namespaces, and Events

Socket.IO builds on WebSocket and adds rooms (group channels), namespaces (logical separation), automatic reconnection, event-based messaging, and a fallback to long polling when WebSocket is unavailable.

bash
typescript

Emitting to specific targets

typescript

Namespaces

Namespaces are like separate sub-applications on the same server — separate event handling, separate middleware:

typescript

Server-Sent Events (SSE)

SSE is simpler than WebSocket for one-directional streams — server pushing to client, never the other way. It uses standard HTTP, works through proxies without configuration, and browsers reconnect automatically.

Good use cases: live dashboards, notification feeds, progress updates.

typescript

Triggering SSE events from elsewhere in your app:

typescript

Client-side (browser):

javascript

Scaling WebSockets with the Redis Adapter

A single-instance app has one in-memory set of connected sockets. With two app servers, a user connected to server A cannot receive an event emitted on server B.

The Socket.IO Redis adapter solves this by routing events through Redis Pub/Sub:

bash
typescript

With the Redis adapter:

  • Server A receives a message from a user
  • Server A emits to room:xyz via Socket.IO
  • Socket.IO publishes the event to Redis
  • Redis fans it out to all subscribers (every app server)
  • Each server delivers it to its locally connected clients in room:xyz

Choosing the Right Transport

ScenarioBest choice
Live chat, multiplayer, collaborative editingWebSocket / Socket.IO
Live dashboard, notifications, progress barServer-Sent Events
Simple polling, infrequent updatesLong polling or short-interval fetch
Mobile app, unreliable networksSocket.IO (handles reconnection)
Need to work through all proxies and firewallsSSE (plain HTTP)

WebSocket and SSE can coexist in the same app — use WebSocket for bidirectional real-time features, SSE for one-directional pushes.


Summary

  • WebSocket upgrades HTTP to a persistent full-duplex TCP connection. Minimal frame overhead makes it ideal for high-frequency bidirectional messaging.
  • ws library is the low-level WebSocket server. Authenticate via handshake.auth or query params (not headers — browsers don't allow custom WS headers). Heartbeat pings detect dead connections.
  • Socket.IO adds rooms, namespaces, event names, automatic reconnection, and long-polling fallback. Authenticate in the io.use() middleware. Rooms enable targeted broadcasting without managing client sets manually.
  • Server-Sent Events are plain HTTP — one-directional, proxy-friendly, auto-reconnecting. Perfect for notification feeds and live dashboards where the client never sends data over the stream.
  • Redis adapter makes Socket.IO multi-server — events emitted on any instance reach clients on all instances. Two Redis connections required (pub + sub).

Next: REST API design principles, URL structure, versioning strategies, cursor-based pagination, and generating interactive OpenAPI documentation from your Express routes.


Knowledge Check

What is the primary difference between the WebSocket protocol and standard HTTP polling for real-time communication?


When using Socket.IO across multiple server instances (e.g., behind a load balancer), what must be implemented to ensure messages reach clients connected to different servers?


In which scenario is Server-Sent Events (SSE) generally considered a better choice than WebSockets?

Test your knowledge with more question sets

Sign in to access a wider variety of questions and get notified when new practice sets are added to this module.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.