How Do Websockets Work ✨

WebSockets enable persistent, full-duplex communication between clients and servers over a single TCP connection, eliminating the need for repeated HTTP polling. They are ideal for real-time applications like chat, gaming, and live updates due to low latency and efficient data transfer. The protocol begins with an HTTP-based handshake before upgrading to a WebSocket connection.
Core Technical Concepts/Technologies
- WebSocket Protocol (RFC 6455)
- HTTP Upgrade Mechanism
- Full-Duplex Communication
- TCP Connection Persistence
- Frame-Based Data Transmission
Main Points
-
Handshake Process:
- Client sends an HTTP request with
Upgrade: websocket
andConnection: Upgrade
headers. - Server responds with HTTP 101 status code to switch protocols.
- Secured via
Sec-WebSocket-Key
andSec-WebSocket-Accept
headers.
- Client sends an HTTP request with
-
Data Frames:
- Messages are split into frames (opcode, payload length, masking key, payload data).
- Supports text, binary, ping/pong (keepalive), and connection close frames.
-
Advantages Over HTTP Polling:
- Eliminates header overhead per request.
- Enables bidirectional communication without connection re-establishment.
-
Use Cases:
- Real-time notifications, collaborative apps, multiplayer gaming, live feeds.
Technical Specifications/Implementation
- Headers Example:
GET /chat HTTP/1.1 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
- Server Response:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Key Takeaways
- WebSockets reduce latency and overhead by maintaining a single TCP connection.
- The protocol relies on an HTTP-compatible handshake for compatibility.
- Frame-based messaging supports diverse data types and control signals.
- Ideal for applications requiring real-time, bidirectional communication.
Limitations/Caveats
- Requires stateful server connections (scaling challenges).
- Not all proxies/load balancers support WebSocket traffic.
- Security considerations (e.g., masking, origin validation) are critical.
#67: A Simple Introduction to Websockets (3 Minutes)
This article was originally published on The System Design Newsletter
Visit Original Source