WebSockets
A TCP-backed, full-duplex channel started with an HTTP upgrade.
Level: intermediate
What is it?
WebSocket is a protocol for bidirectional messages over a single persistent connection. The classic browser flow begins with an HTTP upgrade handshake; WebSocket frames then carry messages until either endpoint closes the connection.
Why does it matter?
Polling repeatedly requests updates even when nothing changes. WebSockets let servers push messages to connected clients and let either side send data with lower request overhead, at the cost of persistent connection management.
Mental model
After the handshake, the connection is no longer a series of ordinary HTTP request-response exchanges. The application must define message types, authentication, backpressure, reconnect behavior, and lifecycle handling.
How it works
- The initial handshake uses HTTP semantics, including Upgrade and appropriate response headers; browser security also considers origin and cookies.
- Frames may be split into fragments; message framing is different from TCP's byte-stream boundaries.
- The protocol defines ping/pong control frames and close-handshake behavior.
- Authentication and authorization still belong to the application/session design; an open socket can outlive a token or permission change unless handled.
- Persistent connections require limits, heartbeats/timeouts, bounded send queues, and cleanup during deploys or network changes.
Steps
- The client establishes HTTP(S) and requests a WebSocket upgrade.
- The server validates the handshake, policy, and required authentication/origin information.
- Both sides exchange application messages over the persistent connection.
- On network loss or shutdown, the app handles reconnect/backoff and restores state safely.
Real-world usage
- Live dashboards, chat, collaborative editing, and game state updates.
- Replacing frequent polling when both sides benefit from server push.
Common mistakes
- Assuming WebSocket messages align with individual TCP packets or reads.
- Failing to revalidate authorization when a long-lived socket remains open.
- Allowing unbounded outbound queues when clients consume messages slowly.
Interview questions
How does WebSocket differ from ordinary HTTP polling?
WebSocket keeps a persistent bidirectional channel after an upgrade handshake, avoiding repeated request setup for each update.
What must an application add beyond the WebSocket protocol?
Message schema, authorization, resource limits/backpressure, reconnect semantics, validation, and operational monitoring.