Modern System Design & API Architecture · Chapter 7 · ~22 min · Intermediate
Real-Time Protocols: Polling vs. SSE vs. WebSockets
Master real-time streaming architectures. Compare HTTP Short Polling, Long Polling, Server-Sent Events (SSE), and full-duplex WebSockets, evaluate wire overhead, and design distributed Pub/Sub backplanes for horizontal scaling.
- Compare Short Polling, Long Polling, SSE, and WebSockets across wire overhead and latency
- Understand HTTP/1.1 Upgrade handshakes and binary framing in WebSockets (RFC 6455)
- Choose Server-Sent Events (SSE) for LLM streaming and unidirectional real-time data
- Design horizontal WebSocket fleets using Redis Pub/Sub backplanes and connection heartbeats
Real-Time Protocols: Polling vs. SSE vs. WebSockets: learn it visually
Evaluate live communication channels: short polling overhead vs long polling vs unidirectional Server-Sent Events (SSE) vs full-duplex WebSockets.
1The Evolution of Live Data on the Web
The original World Wide Web was strictly request-and-response: the client asked for a document, the server returned it, and the TCP connection closed. But modern interactive applications—such as collaborative Google Docs, live crypto tickers, LLM token streaming, and multiplayer gaming—require the server to push updates the instant they happen.
Periodic Spam
Client sends a GET request every 1–2 seconds. Wasteful: 95% of requests return empty responses with full HTTP headers.
Hanging GET
Server holds the request open until data arrives or a timeout occurs. Better latency than short polling, but re-establishes TCP sockets repeatedly.
1-Way Stream
Server streams UTF-8 events over a single open HTTP connection. Built-in browser reconnection. Ideal for LLM token streaming.
Full-Duplex
Persistent bidirectional TCP connection with 2-byte framing. Simultaneous two-way messaging for chat, gaming, and collaborative tools.
2Protocol Comparison: Wire Overhead & Framing
To understand why short polling collapses under load, consider the byte math: Every HTTP request includes 600 to 1,000 bytes of headers (Cookies, User-Agent, Accept-Encoding, Authorization). If 50,000 active mobile users poll your API every 1 second, your servers process:
# Polling Overhead Calculation:
50,000 users * 1 request/sec = 50,000 requests/sec
50,000 req/s * 800 bytes header = 40,000,000 bytes/sec (40 MB/s or 320 Mbps)
# Over 98% of this bandwidth transmits identical HTTP headers with zero new data!By contrast, once a WebSocket handshake succeeds, the HTTP layer is abandoned. Messages travel in compact binary frames with as few as 2 to 6 bytes of framing overhead:
// WebSocket Handshake Request (Client):
GET /chat HTTP/1.1
Host: api.codershub.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
// Handshake Response (Server switches protocol):
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Wrong idea: Polling every 500ms delivers a true real-time responsive experience
Assuming that rapid HTTP GET requests provide real-time streaming without imposing devastating header bloat and connection thrashing on servers.
Real system: Persistent streams eliminate handshake latency and header overhead
WebSockets and Server-Sent Events negotiate a single connection once, shrinking per-message transfer overhead to as little as 2 to 6 bytes of binary framing.
Why does WebSockets drastically reduce bandwidth consumption compared to HTTP short polling?
3Server-Sent Events (SSE): The Secret Weapon for LLMs & Feeds
Server-Sent Events (SSE) is an official W3C standard that allows a server to push real-time text events over HTTP. Unlike WebSockets, SSE:
- Operates over standard HTTP/1.1 and multiplexed HTTP/2 without protocol upgrades.
- Provides native browser auto-reconnection via the
EventSourceAPI. - Works seamlessly with existing enterprise firewalls, API gateways, and corporate proxy filters.
- Is the universal industry standard for ChatGPT and Claude AI token streaming.
// Frontend: Subscribing to an SSE stream
const eventSource = new EventSource("/api/ai/stream-tokens");
eventSource.onmessage = (event) => {
const token = JSON.parse(event.data);
appendWordToScreen(token.word);
};
eventSource.onerror = () => {
// Browser automatically attempts reconnect with exponential backoff!
};Why did OpenAI and modern AI platforms choose Server-Sent Events (SSE) instead of WebSockets for streaming LLM tokens?
4Hands-On: Live Packet & Connection Overhead Inspector
Switch between Short Polling, Long Polling, SSE, and WebSockets. Send messages in both directions and observe the exact byte count and header bloat transmitted across the wire:
Live Packet & Connection Overhead Inspector
1.4 KB
3 packet events2–6 Bytes
Binary frame headerFull-Duplex
Simultaneous 2-way< 2 ms
Push upon event5Horizontal WebSocket Scaling: The Redis Pub/Sub Backplane
HTTP REST backends are trivially stateless: any server can handle any request. WebSockets, however, are deeply stateful: a client holds a persistent open TCP socket to one specific server machine.
If Alice is connected to Gateway Node #1 and Bob is connected to Gateway Node #2, how does Alice's chat message reach Bob? Gateway Node #1 has no socket to Bob!
The solution is a Pub/Sub message broker backplane (such as Redis Pub/Sub, NATS, or Apache Kafka):
1. Subscribe on Connection
When Bob connects to Gateway #2 and joins room #general, Gateway #2 subscribes to the Redis channel room:general.
2. Publish on Message
When Alice sends a message to Gateway #1, Gateway #1 issues REDIS.PUBLISH("room:general", message).
3. Fanout Delivery
Redis broadcasts the message to Gateway #2 in 0.5ms. Gateway #2 finds Bob's local socket and pushes the frame down to his device!
Why is a Pub/Sub backplane (like Redis or Kafka) required to horizontally scale a WebSocket chat architecture across multiple servers?
6Bug Hunt: Fix Real-Time WebSocket & Heartbeat Resiliency
A production real-time gateway was launched for live notifications, but the configuration contains three severe operational flaws: the heartbeat ping interval is set to 0 causing intermediate proxies to silently terminate idle connections, reconnects use a constant 0ms backoff that causes stampede crashes on restarts, and the system is falling back to inefficient short-polling.
Fix the configuration below and click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Keep connections alive: configure
heartbeatIntervalMsbetween10000and45000(e.g.30000). - Prevent reconnection storms: set
reconnectBackoffType: "exponential-jitter". - Enable true streaming: set
protocolMode: "websocket".
7Recap & Real-Time Protocol Decision Matrix
| Protocol | Direction | Framing Overhead | Ideal Use Case |
|---|---|---|---|
| Short Polling | Half-Duplex (Spam) | 800+ Bytes per poll | Infrequent background checks (e.g. email sync every 15 min) |
| Long Polling | Half-Duplex (Hanging) | 600+ Bytes per push | Legacy browser fallback when WebSockets/SSE blocked |
| Server-Sent Events | Unidirectional (Server → Client) | 4–10 Bytes per event | LLM token streaming, live stock prices, news feeds |
| WebSockets | Full-Duplex (Bi-directional) | 2–6 Bytes per frame | Live chat, multiplayer gaming, collaborative canvas editing |
Ready for Chapter 8 (Asynchronous Processing & Queues)? Mark this chapter as complete to proceed: