WebSockets
Keep a persistent, two-way connection open for chat, multiplayer, live collaboration and dashboards.
Intermediate · about 6 hours · difficulty 3/5
Learn first: HTTP in Depth, Reverse Proxies and Load Balancers
HTTP is request/response: the client asks, the server answers. For chat, live cursors or multiplayer games the server needs to push data the instant it happens. WebSockets upgrade an HTTP connection into a persistent, full-duplex channel where both sides can send messages at any time.
How it works
The client sends an HTTP request with Upgrade: websocket; the server replies 101 Switching Protocols and the TCP connection stays open, carrying small framed messages (text or binary). Use wss:// (TLS) in production.
Building with it
- Low-level libraries:
ws(Node),websockets(Python), Gorilla ornhooyr(Go). - Higher-level frameworks add rooms, reconnection, acknowledgements and fallbacks: Socket.IO, SignalR (.NET), Phoenix Channels, Django Channels. Socket.IO uses its own protocol, so its clients and servers must match.
- Define a message protocol: a
typefield plus payload, versioned like an API.
Auth and security
Authenticate during the handshake (cookie or a short-lived token), check the Origin header to prevent cross-site WebSocket hijacking, validate every incoming message like any other input, and rate limit messages per connection.
Scaling
Each connection lives on one server, so:
- Use a pub/sub backplane (Redis pub/sub, NATS) so a message published on server A reaches users connected to server B.
- Configure load balancers and proxies for long-lived connections (timeouts, Upgrade headers); sticky sessions may be needed for some libraries.
- Send heartbeats (ping/pong) to detect dead connections, and have clients reconnect with backoff and resync missed state.
You are ready to move on when you can build a chat room that works across two server instances behind a load balancer and survives a client reconnect.
Key concepts
- Upgrade handshake and frames
- Message protocol design
- Authenticating connections
- Origin checks and input validation
- Heartbeats and reconnection
- Scaling with a pub/sub backplane
- Socket.IO and similar frameworks
Mini project
Build a multi-room chat with WebSockets that authenticates on connect, uses Redis pub/sub to work across two instances, and shows typing indicators and presence.
Check yourself
Two users are connected to different server instances. How does a message from one reach the other?
Free resources
- MDN: The WebSocket API (MDN)
- RFC 6455: The WebSocket Protocol (IETF)
- Socket.IO documentation (Socket.IO)