WebSocket Patterns
Production-grade patterns for persistent connections — reconnection, heartbeats, multiplexing, and backpressure.
Reconnection with exponential backoff
Never retry instantly. Use jittered exponential backoff capped at 30s. Track consecutive failures and reset on successful open. Store pending messages in a ring buffer and flush on reconnect.
Heartbeat / ping-pong
Send application-level pings every 15s. If no pong within 5s, consider the connection dead and trigger reconnect. Server-side, terminate sockets silent for >30s to free resources.
Multiplexing over one socket
Wrap every message with a type field and optional id for request-response correlation. Route inbound messages through a registry of handlers keyed by type. This avoids the overhead of multiple TCP+TLS handshakes.
Backpressure awareness
Check socket.bufferedAmount before sending. If it exceeds a threshold, pause the producer and resume on drain. Never blindly firehose data into a saturated socket — it balloons memory and delays the next heartbeat.