FullStack AI Hub
Studio
System Design · 04. Communication
11 min
10 steps
Intermediate

WebSockets & Real-Time

Evolve from wasteful polling to SSE and horizontally scaled WebSocket gateways backed by Redis Pub/Sub.

System Design04. CommunicationLesson 4 of 4
11 minIntermediate10 steps

WebSockets & Real-Time

Evolve from wasteful polling to SSE and horizontally scaled WebSocket gateways backed by Redis Pub/Sub.

POLL TRAFFIC
10,000/s
EMPTY RESPONSES
95% wasted
AVG MSG DELAY
1,050 ms
API CPU LOAD
88%
GET /msgs every 2sempty polls20,000 onlineREST APIFleet88%95% emptyMessages DB82%constant SELECT95% WASTED POLL WORKEmpty 304s9,500 req/s wastedCost DriverScales with idle tabs
HTTP / WS frame
live push / pubsub
heartbeat ping
poll / reconnect storm
dropped / unreachable
In This LessonStep 1 of 10
What You Will Master
  • ✓Choose cleanly between Short Polling, Long Polling, Server-Sent Events (SSE), and WebSockets
  • ✓Scale stateful WebSocket gateways horizontally using a Redis Pub/Sub message backplane
  • ✓Detect half-open mobile connections accurately with application ping/pong heartbeats and TTL presence
  • ✓Prevent reconnect thundering herds and slow-consumer OOM crashes using jittered backoff and bounded queues

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Short / Long PollingLow-frequency status checks (e.g., async export job every 10s) where plain stateless HTTP is simplestWastes up to 95% of requests on empty responses and adds polling delay + HTTP header overhead
Server-Sent Events (SSE)Server → Client only streams: live stock tickers, notifications, news feeds, and LLM token streamingUnidirectional (client sends via normal HTTP POST) and UTF-8 text frames only
WebSockets + Redis Pub/SubTrue bidirectional sub-50ms interactivity: live chat, multiplayer games, and collaborative cursorsStateful TCP connections complicate deploys, load balancing, and require a cross-node Pub/Sub backplane
Jittered Exponential BackoffReconnecting tens of thousands of dropped sockets safely after a WebSocket gateway crashes or deploysAdds a few randomized seconds before the last clients finish re-establishing their sockets

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for WebSockets & Real-Time.

STEP 01 · SETUPJump to step →

Naïve real-time: Short Polling floods your API

You need live chat and order updates. The quickest prototype runs `setInterval(fetch, 2000)` on every open browser tab.

With **20,000 online users**, that creates **10,000 requests/sec** continuously—even when nobody is typing. **95% of responses return `304 Not Modified`**, burning huge API CPU and battery for nothing.

watch:Short polling scales linearly with idle users instead of actual events—it is a self-inflicted DDoS at scale.

Short PollingEmpty 304 WasteIdle User Scaling
STEP 02 · TECHNIQUEJump to step →

Step up to Long Polling: hold until data arrives

With **HTTP Long Polling**, the server **holds the request open** for up to 30 seconds until a new message arrives, replies immediately, and the client opens the next hanging request.

Empty requests plummet and latency drops to ~80 ms—but every single message still pays full HTTP request/response header framing and re-authentication overhead.

idea:Long polling works through strict corporate firewalls that block WebSockets, but rapid chat still incurs heavy per-message HTTP teardown overhead.

HTTP Long PollingHanging RequestsHeader Overhead
STEP 03 · SOLUTIONJump to step →

Server-Sent Events (SSE): clean one-way HTTP streams

If data flows mostly **Server → Client**—like stock tickers, live sports scores, notifications, or **streaming AI tokens**—reach for **Server-Sent Events (`text/event-stream`)** before WebSockets.

SSE runs over standard HTTP/2, auto-reconnects natively with `Last-Event-ID` resume, and sails effortlessly through proxies and corporate firewalls.

idea:Don’t pay WebSocket complexity when you only need server-to-client push—SSE gives you automatic reconnection and standard HTTP tooling for free.

Server-Sent Events (SSE)Last-Event-ID ResumeUnidirectional Push
STEP 04 · SOLUTIONJump to step →

WebSockets: full-duplex frames over one TCP socket

For interactive **live chat**, **collaborative whiteboards**, or **multiplayer games**, both client and server talk rapidly at the same time. Start with a single HTTP `Upgrade: websocket` handshake (`101 Switching Protocols`).

Once upgraded, HTTP disappears: both sides exchange ultra-lean **2-byte binary or text frames** over the persistent TCP socket with sub-15 ms latency.

idea:WebSocket frame overhead is as small as 2 bytes (vs ~800 bytes of HTTP headers), making high-frequency cursor and chat messages practically free on the wire.

HTTP 101 UpgradeFull-Duplex TCP2-Byte WS Frames
STEP 05 · PROBLEMJump to step →

The scaling trap: stateful WebSocket islands

One WebSocket server caps out around 60,000 open sockets, so you scale horizontally to **WS Gateway A, B, and C** behind a load balancer.

Now a bug breaks chat: **Alice’s TCP socket lives in RAM on Gateway A**, while **Bob’s socket lives on Gateway C**. When Alice sends Bob a message, Gateway A looks in its local socket map, finds no Bob, and **silently drops the message**.

watch:Unlike stateless REST APIs, WebSocket servers hold live TCP file descriptors in local memory—you cannot route across them without a shared backplane.

Stateful ConnectionsLocal Socket MapSplit-Fleet Isolation
STEP 06 · SOLUTIONJump to step →

Bridge the fleet with a Redis Pub/Sub Backplane

Connect every WebSocket Gateway to a shared **Redis Pub/Sub** (or NATS) backplane. When Bob connects to Gateway C and joins `room:42`, Gateway C subscribes to channel `room:42`.

Now when Alice sends a message on Gateway A, Gateway A publishes to `room:42` in Redis—which fans it out in **<1 ms** to Gateway C, which pushes it straight down Bob’s live TCP socket.

idea:Decouple connection termination (dumb WS Gateways) from message routing (Pub/Sub backplane) so your WebSocket fleet scales horizontally to millions of users.

Redis Pub/Sub BackplaneChannel SubscriptionsHorizontal WS Scaling
STEP 07 · TECHNIQUEJump to step →

Presence & Heartbeats: detecting ghost mobile sockets

When a phone enters a subway tunnel, it never sends a TCP `FIN` packet. Without health checks, your gateway keeps that **half-open ghost socket** in RAM for hours and falsely shows the user as "Online."

Send a lightweight **Ping/Pong heartbeat every 25 seconds** and refresh a **Redis TTL key** (`EXPIRE presence:alice 40`). Miss two pongs → close the socket and mark Alice Offline automatically.

idea:Never trust TCP disconnect events alone on mobile networks—application-level heartbeats + TTL expiry are the only reliable source of Online presence.

Half-Open SocketsPing/Pong HeartbeatsTTL Presence Keys
STEP 08 · TRADE-OFFJump to step →

Surviving deploys: stop the Reconnect Thundering Herd

Suppose **WS Gateway A** crashes or restarts during a deploy—instantly severing **60,000 sockets**. If every client reconnects immediately on `onclose`, 60,000 simultaneous TLS + JWT auth handshakes **knock over Gateways B and C in a domino cascade**.

Fix it on both sides: clients use **Exponential Backoff with Full Jitter** (`random(0, min(30s, 1s × 2^n))`), and deploys **drain sockets gradually** over 2 minutes before shutdown.

idea:Never reconnect WebSockets on a fixed timer—randomized jitter spreads a 60,000-socket stampede into a calm, gentle ramp.

Reconnect Thundering HerdExponential Backoff + JitterGraceful Socket Drain
STEP 09 · TECHNIQUEJump to step →

Guard RAM: slow-consumer backpressure & room sharding

In a 50,000-viewer livestream chat, one user on slow 2G cannot read frames fast enough. If the gateway buffers unread frames unbounded in RAM, **one slow socket OOM-kills the entire gateway for 50,000 healthy users**.

Cap every socket’s outbound buffer (e.g., **max 64 messages**). When a slow client overflows, **drop & close that socket** so it resyncs cleanly from the HTTP history API, and shard mega-rooms across multiple Pub/Sub channels.

idea:Never let a slow receiver dictate server memory—bound every per-socket send buffer and disconnect slow consumers cleanly.

Slow Consumer ProtectionBounded Send BufferHTTP Catch-Up Sync
STEP 10 · RECAPJump to step →

Recap: Real-Time Communication Architecture

Choose the lightest transport that fits the UX: **Polling** for rare status checks, **SSE** for server-to-client streams (tickers, AI tokens), and **WebSockets** for low-latency bidirectional interactivity.

At scale, keep WebSocket Gateways thin and bridge them with **Redis Pub/Sub**, track online users with **25s heartbeats + TTL presence**, and enforce **jittered backoff + bounded buffers**.

idea:Production real-time systems always pair live WebSockets (for instant push) with a REST catch-up endpoint (for offline & reconnect sync).

SSE vs WebSocketsPub/Sub BackplanePresence TTLJittered Backoff

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.