WebSockets Basics
WebSockets = persistent, bidirectional TCP connection over an HTTP upgrade. Good for real-time UIs; overkill for simple polling.
1 credit
Lifecycle
- Client does HTTP GET with `Upgrade: websocket` + `Sec-WebSocket-Key`.
- Server responds 101 Switching Protocols — TCP socket stays open.
- Both sides send/receive framed messages (text or binary) until one closes.
- No request/response — just bytes in, bytes out.
Browser API
javascript
const ws = new WebSocket("wss://api.example.com/ws");
ws.onopen = () => ws.send(JSON.stringify({ type: "hello" }));
ws.onmessage = (e) => console.log(JSON.parse(e.data));
ws.onclose = () => reconnectWithBackoff();
ws.onerror = (e) => console.error(e);
// Close cleanly on navigation
addEventListener("beforeunload", () => ws.close());When to use
5 itemsChat / presence
Low latency, bidirectional — yesLive dashboards
Stream metrics/events — yesCollaborative editing
Operational transforms / CRDTs — yesOccasional updates (1/min)
Long-polling or SSE is simplerServer → client only stream
SSE (EventSource) — survives proxies betterProduction gotchas
- Load balancers need sticky sessions or true WS support (not all do).
- Scale horizontally via Redis pub/sub fan-out — connections can't share state across nodes otherwise.
- Heartbeat every 20-30s (ping/pong) — idle connections die silently on many networks.
- Reconnect with exponential backoff + jitter. Resume state on reconnect (sequence numbers, since-timestamp).