WebSockets and SSE
Two ways to keep the server talking to the client.
The old web is request/response: browser asks, server answers, connection closes. Modern apps need the opposite — the server pushing to the client whenever there is news. There are three ways to do this, and the choice locks in your delivery semantics, your infra cost, and your resilience story forever.
How WebSocket works
Client sends an HTTP request with Upgrade: websocket. Server responds 101 Switching Protocols. The TCP connection stays open and now speaks the WebSocket frame protocol. Either side can send bytes any time.
Trade-off matrix
| Dimension | WebSocket | SSE | Long-poll |
|---|---|---|---|
| Direction | Bidirectional | Server → Client | Client-initiated |
| Wire cost per event | ~4 bytes overhead | ~10 bytes overhead | ~500 bytes (HTTP headers) |
| Auto-reconnect | Manual (write code) | Built-in (browser) | Automatic (next request) |
| Corporate proxy friendly | Sometimes blocked | Always works | Always works |
| Backend infra | Sticky connections + WS servers | Any HTTP server | Any HTTP server |
| Concurrent conn limit | ~65K per port (kernel) | Browser caps at 6/domain | Same as regular HTTP |
| Load balancer complexity | L7 with session affinity | Standard L7 | Standard L7 |
| Latency for push | <5 ms | <10 ms | 0-30s (timeout window) |
When to pick each
Bidirectional chat (Slack, Discord), collaborative editing (Figma), trading apps, multiplayer games. Any time the client needs to send data back on the same channel with the same latency guarantees.
LLM streaming (OpenAI, Anthropic), live sports scores, stock ticker, notification stream. When it's one-way and you want the SIMPLEST possible infrastructure. Falls back to HTTP naturally on proxies.
Fallback layer for browsers or corporate networks blocking WS. Simple mobile clients. Legacy integrations. NOT a primary choice for new systems — the header overhead alone makes it 100× more expensive than WS at scale.
The senior-engineer question:
You are designing a chat app. Interviewer asks: WS or SSE? Most candidates reflexively answer WS. The senior answer is: “WS for the message channel — clients need to send. SSE fallback for the notification-only channel on flaky mobile networks — 3× lower server cost per idle connection.” Show that you understand the per-channel decision, not the per-app decision.
Applied in these systems
References
- RFC 6455 — The WebSocket Protocol (2011): rfc-editor.org/rfc/rfc6455
- WHATWG — Server-Sent Events: html.spec.whatwg.org/multipage/server-sent-events.html
- Slack RTM protocol: api.slack.com/rtm — reference implementation
- Discord Gateway v10: discord.com/developers/docs/topics/gateway — real production spec
Practice what you just read
Every foundation concept has a companion quiz to close the loop.