WebSockets — full duplex
- HTTP Upgrade request (
Connection: Upgrade,Upgrade: websocket) - 101 Switching Protocols
- Framed messages (text/binary), ping/pong keepalive
Use when both directions need low latency: chat, gaming, collaborative cursors, live trading UIs.
Not a drop-in REST replacement — stateful connections, different scaling model.
Server-Sent Events (SSE)
One-way server → client over HTTP:
Content-Type: text/event-stream
data: {"score": 3}
data: {"score": 4}
Browser EventSource auto-reconnects. Works through many HTTP proxies; simpler than WS.
Pick SSE when: feed/ticker/notifications, only server pushes, HTTP/2 multiplexing OK.
Comparison
| WebSocket | SSE | Long poll | |
|---|---|---|---|
| Direction | Bidirectional | Server→client | Client-initiated |
| Protocol | WS frames | HTTP stream | Repeated HTTP |
| Browser API | WebSocket | EventSource | fetch |
| Binary | Yes | Text only | Either |
| Proxy friendly | Sometimes tricky | Better | Best |
Auth on persistent connections
- Cookie on initial HTTP upgrade (WS) — CSRF considerations
- Token in query — leaks in logs; short-lived
- First message auth — send JWT after connect
- mTLS — service-to-service WS
Re-auth on reconnect; handle token expiry mid-session.
Scaling WebSockets
Single server holds connections in memory → horizontal scale needs:
- Sticky sessions (same client → same pod) — fragile
- Pub/sub backplane (Redis, Kafka) — all nodes subscribe; local connections receive fan-out
- Dedicated connection tier (e.g. Socket.io + Redis adapter, Ably, Pusher)
Metrics: connection count, message rate, backpressure drops, reconnect storms. Instrumentation → Observability; FD limits and pod sizing → OS + Concurrency (event loop vs thread-per-connection).
GraphQL subscriptions
Typically WebSocket with connection_init + subscribe messages. Same scaling concerns.
Operational concerns
- Idle timeouts at LB (AWS ALB default 60s) — configure ping
- Graceful deploy — drain connections or force reconnect
- Message ordering — per-connection usually ordered; not global
Networking covered TLS and HTTP upgrade framing — here: application protocol choice, fan-out topology, and when WS beats SSE.
Further Reading
Hands-On Tasks (Optional)
API design drills and whiteboard exercises — protocol selection, contract design, and bulk-transfer architecture. Assumes Networking and sibling tracks on the hub page (Distributed Systems, Databases, Concurrency, LLD).
- Pick real-time transport for three features15m
Features: live sports scores, collaborative doc editing, order status on checkout page. Choose SSE, WebSocket, or polling; address reconnect and auth.