Polling, WebSocket & SSE
- Compare short polling, long polling, SSE and WebSocket on latency, server cost, proxy friendliness and failure behaviour
- Explain the WebSocket upgrade handshake, frame format, heartbeats and close codes
- Design a horizontally scalable real-time tier: connection gateways, connection registry, pub/sub backplane, reconnect and replay
- Handle slow consumers with backpressure and conflation for high-frequency data such as prices
- Choose a protocol for order-status updates, trading prices, chat and bank notifications, and justify it
TL;DR
- Short polling: client asks every N seconds. Simple, cacheable, wasteful; average delay ≈ N/2.
- Long polling: server holds the request until there is data or a timeout (≈20–30 s), then the client immediately re-asks. Near-real-time over plain HTTP; one request per message burst.
- SSE (Server-Sent Events): one long-lived HTTP response streaming
text/event-stream. Server → client only, text, built-in browser reconnect withLast-Event-ID. Works through most HTTP infrastructure; best on HTTP/2. - WebSocket: HTTP/1.1
Upgrade→ full-duplex framed messages (text or binary) over the same TCP connection. Lowest overhead for bidirectional, high-frequency traffic; you build reconnect, acknowledgement and replay yourself. - Scaling real-time is about state: connections live on specific gateway nodes, so events produced elsewhere need a pub/sub backplane (Redis, NATS, Kafka) or a connection registry to reach them. Plan for reconnect storms on deploys.
- Mobile apps cannot hold sockets in the background: use push notifications (APNs/FCM) for out-of-app alerts and a socket/SSE only while the app is open.
- Rule of thumb: order status → SSE (+ push); trading prices → WebSocket with conflation; chat → WebSocket (+ push + durable message store).
Why it matters
Real-time features are product requirements in both domains:
- E-commerce: live order tracking, flash-sale countdowns and remaining stock, seller dashboards, customer support chat.
- Banking: instant transfer confirmations, card transaction alerts, brokerage price streams and order fills, video KYC, fraud-ops dashboards.
The protocol choice drives infrastructure cost and failure modes. A million open connections need gateway nodes, load balancers with long idle timeouts, and a plan for what happens when 200,000 of them reconnect at once after a deploy. Choosing WebSocket where SSE would do adds complexity; choosing polling for prices multiplies load and still feels laggy. Interviewers ask "how would the client get updates?" in almost every system design question — notification systems, chat, stock exchange, ride hailing.
Core concepts
Short polling
The client repeats a normal request on a timer: GET /v1/orders/ORD-7781 every 10 s.
- Latency: up to the interval, ≈N/2 on average.
- Cost: requests = clients × (1/N), most returning "no change". 100,000 open order pages polling every 5 s ≈ 20,000 req/s of mostly wasted work.
- Strengths: trivially cacheable (short
max-age,ETag/304), stateless, works everywhere, easy to rate limit. - Good enough for slowly changing data where a few seconds of delay is fine, especially combined with a CDN.
Long polling
- Near-real-time over plain HTTP, through any proxy.
- Each message burst costs a full HTTP round trip and request overhead; a held request still occupies a connection and (in thread-per-request servers) a thread. In Go, a goroutine per held request is cheap.
- Use a cursor (
after=42) so events produced between responses are not lost. - Set the hold timeout below every proxy/LB idle timeout on the path.
Server-Sent Events (SSE)
The server keeps one HTTP response open and writes events as they occur:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-store
retry: 3000
id: 42
event: order-status
data: {"order_id":"ORD-7781","status":"PACKED"}
: heartbeat comment keeps proxies from timing out
id: 43
event: order-status
data: {"order_id":"ORD-7781","status":"SHIPPED"}
- Browser API:
new EventSource(url). It reconnects automatically and sends the last receivedidin theLast-Event-IDheader, so the server can replay what was missed. - One direction: server → client. Client → server actions use normal HTTP requests — which is often exactly right (e.g. "cancel order" is a
POST, updates arrive on the stream). - Text only (UTF-8). Binary must be base64-encoded.
- On HTTP/1.1, browsers limit ≈6 connections per origin, and each SSE stream uses one — a user with several tabs can exhaust it. On HTTP/2, streams are multiplexed and the limit effectively disappears.
- Proxies that buffer responses break SSE (events arrive in batches). Disable buffering for the route (e.g. NGINX
proxy_buffering offor theX-Accel-Buffering: noresponse header). EventSourcecannot set custom headers likeAuthorization; use cookies, or a fetch-based SSE client library for token auth.
WebSocket
Handshake (RFC 6455): an HTTP/1.1 request asks to switch protocols on the same TCP connection.
GET /v1/stream HTTP/1.1
Host: trade.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://trade.example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Accept is the base64 SHA-1 of the client key concatenated with a fixed GUID. It proves the server understood the WebSocket request (it is not a security mechanism). After 101, both sides exchange frames:
| Field | Size | Meaning |
|---|---|---|
| FIN | 1 bit | Last fragment of a message |
| Opcode | 4 bits | 0x1 text, 0x2 binary, 0x0 continuation, 0x8 close, 0x9 ping, 0xA pong |
| MASK | 1 bit | Client → server frames must be masked (protects intermediaries from cache-poisoning tricks) |
| Payload length | 7 bits, or 7+16, or 7+64 | Small messages have a 2-byte header (server → client) or 6 bytes (client → server, with mask key) |
| Masking key | 32 bits | Present on client frames |
Operational facts:
- Heartbeats: send ping frames (or app-level pings) more often than the shortest idle timeout on the path — e.g. every 20–30 s if a load balancer drops idle connections at 60 s. Pings also detect dead clients.
- Close codes:
1000normal,1001going away (server shutting down — tell the client to reconnect),1008policy violation,1011server error;1006is reported locally when the connection dropped without a close frame. - Security: browsers send cookies on the handshake, so a malicious page can open a socket to your API with the victim's session (Cross-Site WebSocket Hijacking). Always check
Originon the handshake, and prefer short-lived tokens sent in the first message over long-lived cookies. Avoid tokens in query strings (they end up in logs). - No built-in semantics for acknowledgements, ordering across reconnects, replay or request/response correlation — you design a small protocol on top (message IDs, sequence numbers, ack frames).
- WebSocket over HTTP/2 exists (RFC 8441, extended CONNECT) but support across proxies varies; most deployments still upgrade HTTP/1.1 connections.
- In Go, the standard library has no WebSocket server; common choices are
github.com/coder/websocket(formerlynhooyr.io/websocket) andgithub.com/gorilla/websocket.
Scaling stateful connections
The core problem: a WebSocket/SSE connection lives on one gateway node, but the event that should reach it (order shipped, price tick, new chat message) is produced by some other service.
Design elements:
- Separate the connection tier from business logic. Gateway nodes only authenticate, hold connections, subscribe and push. Business services stay stateless and publish events.
- Fan-out strategy:
- Broadcast + filter: every gateway subscribes to the stream and drops events for users it does not hold. Simple; cost grows with nodes × events. Fine for modest scale.
- Topic per key: gateways subscribe only to topics their clients need (e.g. per symbol for prices, per chat room). Efficient for many-to-many.
- Targeted routing via registry: look up which node holds user B (
user:B → node-2, TTL refreshed by heartbeats) and publish to that node's channel. Efficient for one-to-one (order updates, private chat).
- Backplane choice: Redis Pub/Sub is fast but fire-and-forget (a gateway that blips misses messages); Redis Streams, NATS JetStream or Kafka add durability and replay at higher cost.
- Replay on reconnect: clients send the last sequence number they processed; the gateway replays from a durable store or the client refetches a snapshot via REST. Without this, every reconnect silently loses events.
- Sticky sessions: not needed for the WebSocket itself — the TCP connection is pinned to its node already. They are needed when a library falls back to long polling (multiple HTTP requests per session must hit the same node) or keeps per-session state across reconnects.
- Capacity: each connection costs a file descriptor, kernel buffers, and in Go at least a goroutine or two plus read/write buffers — very roughly tens of KB per connection. Six-figure connection counts per node are achievable with tuning (file descriptor limits, buffer sizes, epoll-based servers); measure with your own message rates.
- Deploys and reconnect storms: drain gateway nodes gradually, close with
1001, and make clients reconnect with exponential backoff plus jitter. Rate-limit new connections at the load balancer so one node restart does not overload the others with TLS handshakes. - Backpressure: every connection gets a bounded send queue. When a client is slow (bad mobile network), either conflate (keep only the latest value per key), drop non-critical messages, or disconnect it — never let one slow client grow memory unbounded.
WebRTC in brief
WebRTC is for peer-to-peer media and data, not server push:
- Audio/video over SRTP and data channels over SCTP/DTLS, both on UDP, encrypted by default.
- ICE finds a working path between peers through NATs, using STUN (discover your public address) and TURN (relay when direct paths fail — you pay for its bandwidth).
- A signaling channel (often a WebSocket) exchanges session descriptions; WebRTC does not define it.
- Multi-party calls use an SFU (selective forwarding unit) server rather than full mesh.
- Banking/e-commerce uses: video KYC for remote account opening, advisor video calls, live-commerce streams (often via a media server).
Choosing a protocol
| Scenario | Recommended | Why | Key design details |
|---|---|---|---|
| E-commerce order status | SSE on the order page + push notifications for mobile; polling fallback | Low rate (a handful of events per order), server → client only, must survive reconnects | Per-order event sequence; Last-Event-ID replay; authorize that the user owns the order; status also fetchable via REST |
| Flash-sale stock counter | Short polling through the CDN (1–2 s TTL) or SSE broadcast | Same value for everyone; CDN collapses millions of polls into a few origin hits | Never let this path touch the inventory database directly |
| Trading / brokerage prices | WebSocket with binary messages | High-frequency, many symbols, client subscribes/unsubscribes dynamically | Snapshot + incremental updates with sequence numbers; conflation per symbol (e.g. at most every 100–250 ms per client); per-client bounded queues; separate channel or REST for order entry with idempotency keys |
| Chat / customer support | WebSocket + push notifications | Bidirectional, typing indicators, presence | Client-generated message IDs for idempotent sends; server acks; durable message store; per-conversation ordering; offline delivery via push |
| Bank transaction alerts | Push notifications + in-app SSE | User is usually not in the app | Push payload has no sensitive details ("You have a new transaction") — the app fetches details after auth |
| Ops / fraud dashboard | SSE or WebSocket | Internal users, continuous updates | Aggregate server-side; do not stream every raw event |
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Short polling | Simplest, stateless, CDN-cacheable, easy to rate limit | Wasted requests, latency ≈ interval/2 | Slow-changing or broadcast data, MVPs |
| Long polling | Near-real-time on plain HTTP, works through strict proxies | Request overhead per message burst, held connections, cursor logic | Fallback transport; environments that block streaming |
| SSE | Simple server push, auto-reconnect + Last-Event-ID, plain HTTP, works with HTTP/2 multiplexing | One-way, text only, buffering proxies break it, HTTP/1.1 connection limit | Notifications, order tracking, feeds, dashboards |
| WebSocket | Full-duplex, low per-message overhead, binary | Stateful scaling, custom protocol for acks/replay, some proxies/LBs need config, CSWSH risk | Chat, trading, collaborative editing, games |
| WebRTC | Peer-to-peer, UDP media, low latency | Complex (ICE/STUN/TURN), TURN cost, signaling needed | Video/voice (video KYC), P2P data |
| Push notifications | Reach users outside the app; OS-managed connection | Best-effort delivery, payload limits, privacy constraints | Alerts and re-engagement on mobile |
In practice
SSE order-status stream in Go with replay via Last-Event-ID, heartbeats and backpressure. In production, replace the in-memory broker with Redis Streams/NATS and a bounded history.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"time"
)
type OrderEvent struct {
Seq int64 `json:"seq"`
OrderID string `json:"order_id"`
Status string `json:"status"`
}
// Broker keeps per-order history for replay and fans out live events.
type Broker struct {
mu sync.Mutex
history map[string][]OrderEvent
subs map[string]map[chan OrderEvent]struct{}
}
func NewBroker() *Broker {
return &Broker{
history: make(map[string][]OrderEvent),
subs: make(map[string]map[chan OrderEvent]struct{}),
}
}
func (b *Broker) Publish(ev OrderEvent) {
b.mu.Lock()
defer b.mu.Unlock()
b.history[ev.OrderID] = append(b.history[ev.OrderID], ev)
for ch := range b.subs[ev.OrderID] {
select {
case ch <- ev:
default: // slow client: drop; it resyncs with Last-Event-ID on reconnect
}
}
}
// Subscribe returns events after seq `after` plus a channel for live events.
func (b *Broker) Subscribe(orderID string, after int64) ([]OrderEvent, chan OrderEvent, func()) {
b.mu.Lock()
defer b.mu.Unlock()
var missed []OrderEvent
for _, ev := range b.history[orderID] {
if ev.Seq > after {
missed = append(missed, ev)
}
}
ch := make(chan OrderEvent, 16)
if b.subs[orderID] == nil {
b.subs[orderID] = make(map[chan OrderEvent]struct{})
}
b.subs[orderID][ch] = struct{}{}
unsubscribe := func() {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.subs[orderID], ch)
}
return missed, ch, unsubscribe
}
func (b *Broker) ServeSSE(w http.ResponseWriter, r *http.Request) {
orderID := r.PathValue("id")
// TODO: authorize that the authenticated user owns orderID.
after, _ := strconv.ParseInt(r.Header.Get("Last-Event-ID"), 10, 64)
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-store")
h.Set("X-Accel-Buffering", "no") // ask NGINX not to buffer this response
rc := http.NewResponseController(w)
missed, live, unsubscribe := b.Subscribe(orderID, after)
defer unsubscribe()
send := func(ev OrderEvent) error {
data, err := json.Marshal(ev)
if err != nil {
return err
}
if _, err := fmt.Fprintf(w, "id: %d\nevent: order-status\ndata: %s\n\n", ev.Seq, data); err != nil {
return err
}
return rc.Flush()
}
if _, err := fmt.Fprint(w, "retry: 3000\n\n"); err != nil {
return
}
for _, ev := range missed {
if err := send(ev); err != nil {
return
}
}
heartbeat := time.NewTicker(20 * time.Second) // below proxy idle timeouts
defer heartbeat.Stop()
for {
select {
case <-r.Context().Done():
return // client went away
case ev := <-live:
if err := send(ev); err != nil {
return
}
case <-heartbeat.C:
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
return
}
if err := rc.Flush(); err != nil {
return
}
}
}
}
func main() {
b := NewBroker()
go func() { // simulate the order service emitting status changes
for i, s := range []string{"PAID", "PICKING", "PACKED", "SHIPPED", "DELIVERED"} {
time.Sleep(3 * time.Second)
b.Publish(OrderEvent{Seq: int64(i + 1), OrderID: "ORD-7781", Status: s})
}
}()
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/orders/{id}/events", b.ServeSSE)
// No WriteTimeout: it would cut long-lived streams. Bound reads instead.
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())
}
Infrastructure knobs (approximate, verify per vendor):
- Load balancer idle timeout ≥ heartbeat interval × 2 (AWS ALB defaults to 60 s; raise it for WebSocket/SSE, and keep heartbeats around 20–30 s).
- NGINX for WebSocket:
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 1h;. For SSE:proxy_buffering off;. - OS limits on gateway nodes: file descriptors (
ulimit -n), ephemeral ports if gateways connect onward, memory per connection. - Metrics per gateway node: open connections, connects/disconnects per second, send-queue depth, dropped/conflated messages, replay requests, p99 delivery latency (event created → pushed).
Common pitfalls
- No replay on reconnect. Symptom: users occasionally miss "order shipped" or a chat message; impossible to reproduce. Always use sequence numbers /
Last-Event-IDand a durable source. - Response buffering in a proxy. Symptom: SSE events arrive in bursts every few seconds or only when the connection closes.
- Idle timeouts shorter than heartbeats. Symptom: connections drop every 60 s exactly; clients reconnect constantly.
- Reconnect storm after deploy. Symptom: CPU spike from TLS handshakes and auth calls, cascading timeouts on other gateways. Use jittered backoff and gradual draining.
- Unbounded per-client buffers. Symptom: gateway memory grows during market volatility because a few mobile clients are slow; OOM kills drop everyone.
- Not checking
Originon WebSocket upgrades. Symptom: penetration test demonstrates cross-site WebSocket hijacking of an authenticated session. - Putting business logic in the gateway. Symptom: deploying a pricing change requires reconnecting every client.
- Using WebSocket for everything. Symptom: you rebuild request/response, auth, caching and retries that HTTP already gives you; simple REST calls would have been better for commands.
- Sensitive data in push notifications. Symptom: account balances visible on lock screens; compliance finding.
- Polling the primary database. Symptom: a flash-sale countdown page drives the inventory database to 100% CPU.
Interview angle
- "How do clients get updates?" appears in chat, notification, order tracking, stock exchange and ride-hailing designs. Name the options, choose one with a reason tied to direction, frequency and client type, and mention mobile push.
- Strong answers cover the stateful tier: gateway nodes, connection registry, pub/sub backplane, replay with sequence numbers, heartbeats, backpressure, reconnect storms, and the load balancer's idle timeout.
- For trading prices: snapshot + deltas, sequence numbers, conflation, binary encoding, separating market data from order entry.
- Follow-ups: "What happens when a gateway node dies?" (clients reconnect elsewhere with backoff, replay from last seq; registry entries expire by TTL), "How many connections per node?" (measure; tens of KB per connection as a rough planning number), "Why not long polling?"
- Red flags: "WebSocket because it's real-time" without discussing scaling, no plan for missed messages, ignoring mobile background behaviour, sticky sessions as the only scaling idea.
Self-check
1. Why is SSE often a better choice than WebSocket for order-status updates?
Order updates are infrequent and flow only from server to client. SSE is plain HTTP, works through standard proxies and HTTP/2 multiplexing, and the browser reconnects automatically while sending Last-Event-ID so the server can replay missed events. Client actions (cancel order) stay ordinary REST calls. WebSocket would add a custom protocol, stateful scaling and security work without benefit.
2. What does the Sec-WebSocket-Accept header prove, and what does it not prove?
It proves the server understood the WebSocket upgrade: it is the base64 SHA-1 of the client's key plus a fixed GUID, so a non-WebSocket server or a confused cache will not produce it. It provides no authentication or protection against cross-site use — you still must check Origin and authenticate the user.
3. A WebSocket chat runs on 20 gateway nodes. User A on node 3 sends a message to user B on node 17. Describe the delivery path.
Node 3 authenticates the frame, assigns or validates the client message ID, and hands the message to the chat service, which persists it (for durability and history) and publishes an event. The event reaches node 17 either via a topic for the conversation that node 17 subscribes to, or via a connection registry lookup (user:B → node-17) and a node-specific channel. Node 17 pushes it to B, B acks, and if B is offline the system sends a push notification instead.
4. How do you handle a slow mobile client on a high-frequency price stream?
Give each connection a bounded send queue. For prices, conflate: keep only the latest value per symbol and send at a capped rate, so a slow client gets fewer but current updates. If the client still cannot keep up (queue full for too long), disconnect it with a clear close code; on reconnect it receives a fresh snapshot and resumes deltas from the snapshot's sequence number.
5. Why do WebSocket connections drop every 60 seconds behind a cloud load balancer, and how do you fix it?
The load balancer's idle timeout (often 60 s by default) closes connections with no traffic in that window. Send ping frames or application heartbeats more frequently (e.g. every 20–30 s) and/or raise the load balancer's idle timeout. Also make sure the server's own read deadlines accommodate the heartbeat interval.
6. When do you need sticky sessions in a real-time system?
A pure WebSocket or SSE connection is already pinned to one node by its TCP connection, so stickiness is not needed for it. You need sticky sessions when the transport is a series of separate HTTP requests that share server-side state — for example a library falling back to long polling — or when a node keeps per-session state that a reconnect should find. Better designs keep that state in shared storage so any node can resume.
7. Why should a bank's transaction push notification not include the amount and merchant?
Push payloads transit third-party services (APNs/FCM) and appear on lock screens, where anyone nearby can read them; they also persist in notification centers. A generic message ("New card transaction") that prompts the user to open the app, authenticate, and fetch details over the bank's API keeps sensitive data inside the authenticated channel. Some banks let customers opt in to richer notifications.
Exercise
Part A — run the SSE stream.
go run . # the Go program above
curl -N http://localhost:8080/v1/orders/ORD-7781/events # -N disables curl's buffering
# Stop curl after event 2, then resume from where you left off:
curl -N -H 'Last-Event-ID: 2' http://localhost:8080/v1/orders/ORD-7781/events
Confirm that the second connection replays only events after 2. Open the stream in a browser with a three-line EventSource page and kill the server mid-stream; watch the browser reconnect after the retry interval.
Part B — scale it out. Run two instances behind NGINX, replace the in-memory broker with Redis (Pub/Sub for live events plus a Redis Stream per order for replay), publish from a separate process, and verify that a client connected to instance 1 receives events published while it was connected to instance 2.
Part C — design. Sketch a price-streaming service for a brokerage app: 200,000 concurrent users, 3,000 symbols, peaks of 50,000 ticks/s. Specify transport, message format, subscription protocol, conflation rate, gateway count (state your per-node assumption), backplane, and the reconnect/snapshot procedure.
Done when: replay works after reconnect, the two-instance setup delivers across nodes, and your design states the conflation interval, per-client queue bound, and what happens to a client that falls behind.
Further reading
- RFC 6455 — The WebSocket Protocol.
- HTML Living Standard (WHATWG) — "Server-sent events" section.
- High Performance Browser Networking — Ilya Grigorik, chapters on XHR, SSE, WebSocket and WebRTC (hpbn.co).
- System Design Interview Vol. 1 — Alex Xu, chat system chapter (polling vs long polling vs WebSocket).
- WebRTC for the Curious — free book on ICE, STUN, TURN and DTLS.
Related
- Chat System — a full design using WebSocket gateways.
- Notification System — push notifications and fan-out.
- Stock Exchange — market data distribution.
- Order Management & State Machines — the events behind order-status streams.
- Message Queues & Event Streaming — choosing a backplane.
- Proxies, Load Balancers & API Gateways — idle timeouts, draining, sticky sessions.
- I/O Models: Blocking, epoll, io_uring — how one node holds many connections.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).