When to use WebSockets
WebSockets are appropriate when the server needs to push updates to the client without polling. Use cases: live dashboards, collaborative editing, chat, live sports scores, trading UIs.
Connection lifecycle
- Client sends HTTP Upgrade request.
- Server responds with 101 Switching Protocols.
- Full-duplex TCP connection established — both sides send frames freely.
- Either side sends a Close frame to terminate gracefully.
Heartbeats
Send a ping frame every 30 seconds. If no pong is received within 10 seconds, close and reconnect. Silent connection drops (NAT timeouts, mobile network switches) are common — heartbeats detect them.
Client reconnection
Implement exponential backoff with jitter: 1s, 2s, 4s, 8s... up to a max of 60s. Without jitter, all disconnected clients reconnect simultaneously after a server restart and create a thundering herd.
Scaling across multiple servers
WebSocket connections are stateful — a message to user A must reach the server holding A's connection. Use Redis pub/sub: servers subscribe to a channel per user. Publishing to the channel reaches the correct server regardless of which instance holds the connection.