WebSocket Protocol
WebSocket upgrades an HTTP connection into a persistent, bidirectional message channel with minimal framing overhead, suited to chat, collaboration, live dashboards, and game state.
Definition
WebSocket is a protocol that starts as an HTTP upgrade handshake, then switches the same TCP connection to a full-duplex message channel with its own small frame format. It supports text and binary messages, ping-pong keepalives, and close semantics, and it survives proxies only when they support the Upgrade flow.
Context and scope
Used for server-initiated pushes, high-frequency client updates, and low-overhead bidirectional flows. Often paired with reconnect and heartbeat logic, or replaced by SSE for one-way streams.
Common misconceptions
- WebSockets are faster because they are binary — the win is removing per-message HTTP semantics and headers, not the wire format
- WebSocket messages preserve ordering globally — ordering holds per connection; across reconnects it is your job
- Firewalls and proxies pass them through like HTTP — many break or idle-timeout upgraded connections
Anti-patterns
- Using WebSockets for occasional server notifications where polling or SSE would be simpler and cache-friendlier
- Assuming message delivery without application-level acks and sequence numbers across reconnects
- Authenticating only the upgrade request and treating a long-lived socket as permanently trusted
Related concepts
Related examples
Authoritative source
What it is
HTTP is request-driven: the client asks, the server answers. WebSocket renegotiates the contract once, then both sides send framed messages whenever they want. Frames carry a few bytes of header instead of full HTTP semantics, which is the efficiency source.
How it works
The client sends an Upgrade request with a Sec-WebSocket-Key; the server answers 101 with a proof digest, and the connection changes protocol. Messages are masked from client to server. Control frames for ping, pong, and close ride the same channel. Subprotocols negotiate an application schema.
When to use it
Bidirectional and high-frequency flows: chat, collaborative editing, multiplayer state, telemetry ingestion. For server-to-client only, SSE is simpler, works over plain HTTP caching, and auto-reconnects. Hybrid designs often use HTTP for writes and SSE for pushes.
Pitfalls
Proxies and load balancers idle-timeout upgraded connections unless heartbeats keep them alive. Reconnect storms after an outage need jittered backoff. Authorization should be reassertable mid-connection for long-lived sockets, and message-level acks are application responsibility.