Skip to content

Lesson 1 of 9 · 22m

The WebSocket Lifecycle: Upgrade, Frames, Heartbeats, Close

What the handshake really buys you, how frames and heartbeats behave, and why most connection bugs are lifecycle bugs.

A WebSocket is not a magic pipe. It is an HTTP request that got promoted into a long-lived TCP session, with a small framing protocol on top. Most production incidents come from treating it like a permanent connection instead of a lease that must be renewed, monitored, and cleanly ended.

The upgrade is ordinary HTTP first

GET /realtime HTTP/1.1
Host: app.internal
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: json.v1

The server answers 101 Switching Protocols and the connection stops being request/response. That first request is your last easy chance to authenticate, choose a subprotocol, reject unsupported versions, and attach metadata such as tenant or device class. Cookies still work because this is HTTP. Beware the reverse proxy: if nginx, Envoy, or your ingress does not pass Upgrade and Connection correctly, clients hang or fall back before your application runs.

Frames are messages, not streams

After upgrade, data moves in frames: text, binary, ping, pong, and close. TCP gives you ordered bytes, but WebSocket gives you messages. Browser JavaScript exposes whole messages only:

const ws = new WebSocket("wss://app.example/realtime", "json.v1");
ws.onopen = () => ws.send(JSON.stringify({ type: "subscribe", topic: "room:42" }));
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data); if (msg.type === "room:event") render(msg);
};
ws.onclose = (event) => console.log("closed", event.code, event.reason);

Text frames are UTF-8 JSON in most applications. Binary frames are for protobuf, compact game state, audio, or high-frequency telemetry. Pick one wire contract and version it; ad-hoc mixed payloads become impossible to debug.

Heartbeats are leases

TCP has no reliable application-level death notification. A client can disappear when a laptop sleeps, Wi-Fi roams, or a mobile OS suspends the process, and the server may keep a dead socket for minutes. Ping/pong frames exist because silence is ambiguous.

// Node ws server sketch
setInterval(() => {
  for (const ws of server.clients) {
    if (!ws.isAlive) ws.terminate();
    ws.isAlive = false;
    ws.ping();
  }
}, 30000);
server.on("connection", (ws) => {
  ws.isAlive = true;
  ws.on("pong", () => { ws.isAlive = true; });
});

Thirty seconds is a common starting point. Shorter intervals cost traffic; longer intervals leave dead presence visible. The right number is the one aligned with your proxy idle timeout and user experience tolerance.

Close is part of the protocol

Close frames carry a status code and short reason. Use normal codes deliberately: 1000 normal, 1001 going away, 1008 policy violation, 1011 server error. Application-specific codes live in the 4000-4999 range. If clients reconnect after every close code, including 1008, you have built a retry storm machine.

Field notes

  • Always log close codes, not just disconnect counts. A spike in 1006 abnormal closures usually means network or proxy trouble.
  • Sec-WebSocket-Protocol is a negotiation, not a label; reject clients you cannot understand.
  • Browser clients cannot send custom headers on WebSocket construction. Use cookies, query tokens, or a first authenticated message.
  • A socket can be open and useless. Only heartbeats and successful application messages prove liveness.

Was this lesson helpful?

Sign in to rate