Chapter 8: WebSockets, SSE, and Real-Time Communication

The Problem: Server → Client Push

HTTP is request-response: client asks, server answers. But what if the server needs to push data to the client (chat messages, live scores, notifications)?

Solutions Compared

MethodDirectionConnectionUse Case
PollingClient → Server (repeated)New connection each timeSimple, low-frequency updates
Long PollingClient → Server (held open)Held until data availableModerate real-time needs
SSEServer → Client (one-way)Persistent HTTPLive feeds, notifications
WebSocketBidirectionalPersistent TCPChat, gaming, collaboration
gRPC streamingBidirectionalHTTP/2 streamService-to-service real-time

WebSocket

HTTP Upgrade handshake: Client: GET /chat HTTP/1.1 Upgrade: websocket Server: HTTP/1.1 101 Switching Protocols Now: full-duplex TCP connection Client ◄──────────────────► Server messages flow freely both ways until either side closes

Use for: chat, multiplayer games, collaborative editing, live trading

Challenge at scale: each WebSocket = persistent connection. 1M users = 1M open connections. Need connection-aware load balancing.

Server-Sent Events (SSE)

// Server sends events over a long-lived HTTP connection
// Client uses EventSource API (built into browsers)
GET /events HTTP/1.1
Accept: text/event-stream

// Server responds with streaming data:
data: {"type":"notification","msg":"New message"}

data: {"type":"score","home":2,"away":1}

// Simple, auto-reconnects, works through proxies

Use for: notifications, live feeds, dashboards (server→client only)

Scaling Real-Time Systems

Challenge: User A on Server 1 sends message to User B on Server 3 Solution: Pub/Sub backbone (Redis Pub/Sub or Kafka) Server 1 ──publish──► Redis Pub/Sub ──notify──► Server 3 (User A) (User B) All servers subscribe to relevant channels. Message reaches the right server regardless of which one the user is on.
Key Takeaways