Chapter 7 of 12
Course Progress0 of 12 completed (0%)

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.

Real-Time Protocols: Polling vs. SSE vs. WebSocketsEvaluate live communication channels: short polling overhead vs long polling vs unidirectional Server-Sent Events (SSE) vs full-duplex WebSockets.UNDERSTANDReal-Time ProtocolsFOLLOW THE FLOWPollingAPPLY ITSSEReal-Time Protocols: Polling vs. SSE vs. WebSocketsEvaluate live communication channels: short polling overhead vs long polling vs unidirectional Server-Sent Events (SSE) vs full-duplex WebSockets.UNDERSTANDReal-Time ProtocolsFOLLOW THE FLOWPollingAPPLY ITSSE

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.

1. Short Polling

Periodic Spam

Client sends a GET request every 1–2 seconds. Wasteful: 95% of requests return empty responses with full HTTP headers.

2. Long Polling

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.

3. SSE

1-Way Stream

Server streams UTF-8 events over a single open HTTP connection. Built-in browser reconnection. Ideal for LLM token streaming.

4. WebSockets

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

120 HTTP GETs/min × 850 B Headers → 99% Empty 304 ResponsesFlaw: Over 100 KB/min wasted per client just transmitting repetitive HTTP headers

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

1 HTTP Upgrade → Persistent Bi-directional 2-Byte Binary FramesSub-millisecond latency; updates pushed immediately upon server-side event

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.

Concept Check

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 EventSource API.
  • 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!
};
Concept Check

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

Protocol: websocket
Cumulative Transferred

1.4 KB

3 packet events
Per-Update Overhead

2–6 Bytes

Binary frame header
Duplex Capability

Full-Duplex

Simultaneous 2-way
Delivery Latency

< 2 ms

Push upon event
Real-Time Packet Wire InspectorInspecting active protocol frames
CLIENT &rarr; SRV
GET /chat/stream HTTP/1.1 (Upgrade: websocket)
480 B
SRV &rarr; CLIENT
HTTP/1.1 101 Switching Protocols
260 B
SRV &rarr; CLIENT
WebSocket Frame [Opcode 0x1 TEXT]: {"event":"joined"}
42 B

5Horizontal 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!

Concept Check

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:

Real-Time Gateway & Heartbeat Hunt
TypeScript

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Keep connections alive: configure heartbeatIntervalMs between 10000 and 45000 (e.g. 30000).
  • Prevent reconnection storms: set reconnectBackoffType: "exponential-jitter".
  • Enable true streaming: set protocolMode: "websocket".

7Recap & Real-Time Protocol Decision Matrix

ProtocolDirectionFraming OverheadIdeal Use Case
Short PollingHalf-Duplex (Spam)800+ Bytes per pollInfrequent background checks (e.g. email sync every 15 min)
Long PollingHalf-Duplex (Hanging)600+ Bytes per pushLegacy browser fallback when WebSockets/SSE blocked
Server-Sent EventsUnidirectional (Server → Client)4–10 Bytes per eventLLM token streaming, live stock prices, news feeds
WebSocketsFull-Duplex (Bi-directional)2–6 Bytes per frameLive chat, multiplayer gaming, collaborative canvas editing

Ready for Chapter 8 (Asynchronous Processing & Queues)? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us