WebSockets & Real-Time Protocols
WebSocket upgrade handshake, full-duplex frames, ping/pong heartbeat, and comparison with SSE and long-polling.
Overview
Overview Real-time communication between clients and servers is a fundamental requirement for chat applications, live dashboards, collaborative editing, trading platforms, and online games. HTTP was designed as a request/response protocol — the client always initiates. WebSockets, Server-Sent Events (SSE), and long-polling are three approaches that work around or extend HTTP to enable server-initiated data delivery.
WebSockets (RFC 6455) provide a full-duplex, persistent, bidirectional communication channel over a single TCP connection. The protocol begins with an HTTP upgrade handshake: the client sends an HTTP/1.1 Upgrade request with specific WebSocket headers (Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key), and the server responds with 101 Switching Protocols. After the upgrade, the connection is no longer HTTP — data flows as WebSocket frames, which have a compact binary header (2 to 14 bytes: 2 to 10 for the header and length, plus a 4-byte masking key on client frames) followed by payload. Either side can send frames at any time, and either side can initiate close.
Server-Sent Events (SSE) is a simpler alternative for one-way server-to-client streaming. The server sends text/event-stream content over a persistent HTTP connection. SSE has built-in reconnection (the browser automatically reconnects with Last-Event-ID), works over HTTP/2 like any other response (a WebSocket needs RFC 8441 support on both ends to run over HTTP/2), and is trivially proxied by any HTTP infrastructure. Its limitation is that it is unidirectional — clients can only receive, not send over the SSE stream.
Long-polling is the oldest technique and works on any HTTP infrastructure. The client sends a request; the server holds it open until data is available (or a timeout), then responds. The client immediately re-sends. Long-polling has high overhead (HTTP headers on every message) and is largely replaced by WebSockets and SSE for new development.
For production systems, WebSocket scaling requires sticky sessions or a shared pub/sub backend (Redis, Kafka) since WebSocket connections are stateful. Understanding ping/pong heartbeats, frame types, masking (required for client-to-server frames by the RFC), and graceful closure is essential for building reliable real-time infrastructure.
Key concepts
- WebSocket Upgrade Handshake
- WebSocket Frames
- Ping/Pong Heartbeat
- Server-Sent Events (SSE)
- Sticky Sessions for WebSockets
Interview questions
- How does the WebSocket upgrade handshake work, and how would you debug a WebSocket connection that fails to establish?
- Compare WebSockets, Server-Sent Events, and long-polling. When would you use each?
Sign up free to read the full topic
More Networking topics
Start free on Cariara · Coding problems · System design studio