WebSocket
A persistent protocol over a single TCP connection enabling low-latency, full-duplex messaging between client and server
Table of Contents
Structure Diagram
Repeated Request-Response · Client-driven
- ConnectionNew request every interval
- DirectionClient must pull updates
- OverheadFull HTTP headers on every poll
- LatencyBounded by poll interval
Persistent TCP · Full-duplex push
- ConnectionSingle persistent socket via Upgrade
- DirectionSimultaneous bidirectional push
- OverheadMinimal frame header (2–14 bytes)
- LatencyInstant sub-second event push
What is WebSocket?
A persistent protocol over a single TCP connection enabling low-latency, full-duplex messaging between client and server. It is a core concept in APIs & Networking within Web Dev.
Core Principles
WebSocket starts with a standard HTTP handshake carrying an Upgrade: websocket header, then transitions into a long-lived, full-duplex TCP connection where both client and server can push messages at any moment without waiting for a request.
Whereas HTTP polling repeatedly transmits hundreds of bytes of headers even when nothing has changed, an open WebSocket exchanges text or binary frames with only 2–14 bytes of framing overhead, drastically lowering latency and bandwidth for live applications.
Practical Takeaways
- Implement heartbeats and exponential backoff reconnects: Idle proxies and mobile network switches frequently leave sockets silently half-open. Send periodic Ping/Pong frames to detect dead links, and reconnect with exponential backoff plus jitter so thousands of clients don't hammer the server simultaneously.
- Back multi-instance servers with Pub/Sub: Because WebSockets are stateful per server process, scaling horizontally requires a shared message bus (such as Redis Pub/Sub or NATS) so an event received on Server A reaches clients connected to Server B.
- Prefer SSE when traffic is strictly server-to-client: For LLM token streaming, live notifications, or dashboards where clients rarely push frames, Server-Sent Events (SSE) ride over standard HTTP/2 and are simpler to proxy and auto-reconnect.
Notable Examples
- Live chat and multiplayer collaboration: Slack, Discord, and Figma synchronizing messages, presence, and live cursor positions in milliseconds.
- Financial order books: Crypto and stock exchanges streaming hundreds of tick updates per second over compressed binary WebSocket feeds.
- Browser multiplayer games: Real-time state synchronization and lobby events between web clients and authoritative game servers.
Practical Code Snippet
Copy and drop straight into your projectconst socket = new WebSocket("wss://api.example.com/live"); socket.addEventListener("open", () => { socket.send(JSON.stringify({ type: "subscribe", room: "lobby" }));}); socket.addEventListener("message", (event) => { const payload = JSON.parse(event.data); console.log("Realtime event:", payload);}); socket.addEventListener("close", () => { setTimeout(() => reconnect(), 2000);});