How WebSockets Work: Long-Lived Connections
On this page
Polling vs long polling vs WebSockets
A chat app needs to show new messages the moment they arrive. With plain HTTP, the client must ask: poll every few seconds (wasteful and slow), or hold a request open until something happens (long polling, workable but clumsy). WebSockets give both sides a persistent channel where either can send whenever it wants.
The WebSocket upgrade handshake
A WebSocket starts as an ordinary HTTP/1.1 request asking to switch protocols (RFC 6455):
GET /chat HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://app.example.comThe server agrees with a 101 response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The accept value proves the server understood WebSockets, rather than being a confused HTTP server. It's the SHA-1 of the client's key plus a fixed GUID, base64-encoded:
import base64, hashlib
key = "dGhlIHNhbXBsZSBub25jZQ=="
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
print(base64.b64encode(hashlib.sha1((key + guid).encode()).digest()).decode())
# s3pPLMBiTxaQ9kYGzzhZRbK+xOo=After the 101, the same TCP connection (wrapped in TLS for wss://) carries WebSocket frames, not HTTP.
WebSocket frames, ping and close
- Messages travel as frames: text, binary, or control frames (ping, pong, close). Frames from browser clients are masked, a defense against cache poisoning in proxies, not encryption.
- Ping and pong keep the connection alive and detect dead peers. Proxies, load balancers and NATs close idle connections, often after 60 seconds, so send a heartbeat more often than the shortest idle timeout on the path.
- A close frame with a status code ends the connection cleanly.
WebSocket security: Origin checks and auth
- Check the Origin header. Browsers send cookies with WebSocket handshakes, and the same-origin policy doesn't block cross-site WebSocket connections. Without an Origin check, a malicious page can open a socket as the logged-in user (cross-site WebSocket hijacking).
- Authenticate the handshake (a cookie or a short-lived token) and authorize every message, not just the connection.
- Use
wss://only.
Running WebSockets in production
- Proxies must pass the upgrade. nginx needs
proxy_http_version 1.1plus theUpgradeandConnectionheaders forwarded, and a longproxy_read_timeout. - Connections are stateful and long-lived. A server holds each one open, so load balancing is per connection. Deploys and scale-down events disconnect clients, so clients must reconnect with backoff and jitter and resume (for example, "send me messages after id 1234").
- Fan-out across servers: user A is connected to server 1, user B to server 2. A message for B needs a shared channel, such as Redis pub/sub or a message broker, to reach the right server.
- Simpler alternatives: if only the server pushes (notifications, live scores), Server-Sent Events over plain HTTP is simpler and works through HTTP/2. For real-time media, use WebRTC.
Check yourself
It reuses HTTP's ports, proxies, TLS and load balancers. The client sends a normal request with Upgrade: websocket, the server answers 101 Switching Protocols, and the same TCP connection then carries WebSocket frames.
Browsers attach cookies to the handshake and allow cross-site connections, so without the check a malicious site can act as the logged-in user.
A proxy or load balancer's idle timeout closing quiet connections, often 60 seconds by default. Send ping frames more often than the timeout, say every 30 seconds, or raise the timeout on the proxy.
Each connection is long-lived and tied to one server, so you need enough capacity for idle connections, sticky routing, and a way to send messages to users connected to other servers, such as a pub/sub layer.
When the server only needs to push updates to the browser, like notifications. They run over plain HTTP, reconnect automatically and pass through proxies easily.