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
| Method | Direction | Connection | Use Case |
|---|---|---|---|
| Polling | Client → Server (repeated) | New connection each time | Simple, low-frequency updates |
| Long Polling | Client → Server (held open) | Held until data available | Moderate real-time needs |
| SSE | Server → Client (one-way) | Persistent HTTP | Live feeds, notifications |
| WebSocket | Bidirectional | Persistent TCP | Chat, gaming, collaboration |
| gRPC streaming | Bidirectional | HTTP/2 stream | Service-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
- Polling: simple but wasteful. Long polling: better but still hacky.
- SSE: server→client streaming over HTTP. Simple, auto-reconnect.
- WebSocket: full bidirectional. Best for chat/gaming. Complex at scale.
- Scaling real-time: pub/sub backbone (Redis/Kafka) connects servers
- gRPC streaming: best for service-to-service real-time