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).
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
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.
Emitting to specific targets
Namespaces
Namespaces are like separate sub-applications on the same server — separate event handling, separate middleware:
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.
Triggering SSE events from elsewhere in your app:
Client-side (browser):
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:
With the Redis adapter:
- Server A receives a message from a user
- Server A emits to
room:xyzvia 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
| Scenario | Best choice |
|---|---|
| Live chat, multiplayer, collaborative editing | WebSocket / Socket.IO |
| Live dashboard, notifications, progress bar | Server-Sent Events |
| Simple polling, infrequent updates | Long polling or short-interval fetch |
| Mobile app, unreliable networks | Socket.IO (handles reconnection) |
| Need to work through all proxies and firewalls | SSE (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.
wslibrary is the low-level WebSocket server. Authenticate viahandshake.author 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.
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 & RegisterDiscussion
0Join the discussion