advanced
WebSocket APIs
Design bidirectional sessions with connection lifecycle, authentication, heartbeats, backpressure, ordering, and reconnect behavior.
WebSockets provide full-duplex, long-lived connections — chat, live dashboards, collaborative editing, game state. Design the **session lifecycle**, not only the happy path.
Connection flow:
- HTTP upgrade handshake (`Upgrade: websocket`).
- Authenticate at connect (token query param is weak; prefer short-lived ticket or first-frame auth).
- Heartbeats (ping/pong) to detect dead peers.
- Reconnect with resume token or snapshot + delta sync.
// Server message envelope
{ "type": "order.updated", "seq": 42, "payload": { "id": "1", "status": "SHIPPED" } }
Operational concerns:
- **Backpressure**: slow clients need bounded outbound buffers or drop policy.
- **Ordering**: per-channel sequence numbers; idempotent handlers.
- **Scale**: sticky sessions or pub/sub bridge (Redis, NATS) across instances.
- **AuthZ**: subscribe only to channels the user may access.
On interviews: WebSocket vs SSE trade-offs, how to secure connections, and horizontal scaling patterns.
Common pitfalls: no heartbeat, unbounded in-memory fan-out, treating WS as free long polling, and missing reconnect state recovery.
The trade-off is realtime UX versus connection and infra cost — measure concurrent connections and egress.
Checklist:
- Auth at connect; re-auth on privilege change.
- Heartbeats and idle timeouts.
- Message schema versioning.
- Horizontal scale via shared pub/sub.