Back to docs
Recipe

WebSockets primer

Persistent bidirectional channels between client and server — no polling, no hacks.

What it is

WebSocket upgrades a standard HTTP connection to a full-duplex TCP tunnel. Once established, either side can push frames at any time. The handshake uses HTTP/1.1 with Upgrade: websocket and a Sec-WebSocket-Key challenge.

Why you want it

  • Zero-overhead push — no HTTP headers per message after handshake.
  • Sub-millisecond latency for live dashboards, chat, game state.
  • Single connection multiplexes thousands of messages.
  • Traverses most proxies and CDNs when using TLS (wss://).

The handshake

Client sends an HTTP upgrade request. Server responds with101 Switching Protocols. From that point the TCP socket is raw WebSocket frames — masked from client, unmasked from server.

Frame anatomy

Every frame carries an opcode (text, binary, ping, pong, close), a payload length encoded in 1–9 bytes, and an optional mask key. Control frames (ping/pong/close) interleave with data and keep the connection alive.

Gotchas

  • Some load balancers drop idle connections — send application-level pings every 30s.
  • Browser WebSocket API has no built-in reconnection; wrap it.
  • Backpressure: if the send buffer fills, throttle or drop.
  • Authentication belongs in the handshake (cookie or token header), not in the first data frame.

Next steps

Read the implementation recipe for a production-ready wrapper with exponential backoff, heartbeat, and message framing.