flashman
← All guides

WebSocket handshakes, proxies, and connection lifecycle

Operate reliable WebSockets through browsers, proxies, and load balancers with correct handshakes, origin policy, timeouts, heartbeats, close codes, and tests.

2026-09-07 · 8 min read

  • websocket
  • networking
  • reliability

A WebSocket connection starts with an HTTP request containing upgrade headers. After the server returns status 101, the same transport carries framed messages until one peer closes it or an intermediary drops the connection.

Production reliability therefore depends on both handshake routing and long-lived connection behavior across browsers, reverse proxies, load balancers, application instances, deploys, and network changes.

Specify the handshake boundary

Define the ws or wss URL, path routing, authentication mechanism, accepted origins, subprotocols, extensions, and maximum header size. HTTPS pages should use secure WebSockets so browsers and networks do not reject mixed or exposed transport.

  • Forward upgrade semantics with proxy-specific configuration.
  • Validate Origin independently from bearer or session authentication.
  • Negotiate only implemented subprotocols.
  • Return clear ordinary HTTP errors before the protocol switches.

Design connection ownership and state

A transport connection is temporary. Keep durable application state, acknowledgements, replay cursors, and authorization decisions outside assumptions that one socket will survive indefinitely.

When horizontal scaling requires affinity, document why and bound its lifetime. Prefer shared state or brokered messaging when clients must reconnect to any healthy instance without losing correctness.

Coordinate heartbeats, timeouts, and shutdown

Set proxy and load balancer idle timeouts beyond the expected heartbeat interval, with enough tolerance for event-loop and network delay. Avoid synchronizing every client heartbeat or reconnect attempt at the same instant.

  • Record open, authenticated, idle, closing, and closed transitions.
  • Use meaningful close codes without leaking sensitive detail.
  • Reconnect with exponential backoff, jitter, and a maximum rate.
  • Drain connections during deploys and publish a retry signal.

Test the complete route

Use Flashman's URL tool to verify endpoints, timestamp converter to align handshakes and closes, JSON formatter for synthetic messages, diff for proxy settings, and Base64 for public binary-frame fixtures. Protocol-specific clients remain necessary for actual connection tests.

Exercise direct and proxied routes, TLS termination, origin denial, subprotocol negotiation, idle and active timeouts, network loss, rolling deploys, reconnect storms, authentication expiry, backpressure, and oversized frames.

Try these tools