Real-Time Communication — Polling, SSE, WebSockets, MQTT, gRPC
Short polling, long polling, Server-Sent Events, WebSockets (handshake, framing, scaling), MQTT (QoS levels, retained messages, last will), gRPC and its four streaming modes, webhooks, and WebRTC — with a decision table and scaling patterns for millions of connections.
The problem
HTTP is request/response: the server can only answer when asked. Many features need the server to push data as soon as it exists — chat messages, notifications, live scores, stock tickers, collaborative cursors, IoT telemetry, streamed AI responses.
The options
| Short polling | Long polling | SSE | WebSocket | |
|---|---|---|---|---|
| Direction | client pull | server push (emulated) | server → client | bidirectional |
| Transport | HTTP | HTTP | HTTP (1.1/2/3) | TCP after HTTP upgrade |
| Latency | up to the interval | low | low | lowest |
| Overhead | high (empty polls) | medium (re-requests) | low | lowest per message |
| Reconnect / resume | n/a | manual | built-in (Last-Event-ID) | manual |
| Binary data | yes | yes | no (text) | yes |
| Proxy/firewall friendliness | best | good | good | usually fine; some proxies interfere |
| Best for | rare updates, dashboards | fallback | notifications, feeds, LLM streaming | chat, games, collaboration |
Long polling
# server (FastAPI): wait up to 25 s for new messages
@app.get("/messages")
async def poll(after: int):
try:
msgs = await asyncio.wait_for(wait_for_messages(after), timeout=25)
except asyncio.TimeoutError:
msgs = []
return {"messages": msgs} # client immediately polls again with the new cursor
Server-Sent Events
GET /events HTTP/1.1
Accept: text/event-stream
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 41
event: order_shipped
data: {"order_id":"ord_981"}
id: 42
data: {"order_id":"ord_982","status":"delivered"}
const es = new EventSource("/events"); // reconnects automatically, sends Last-Event-ID
es.addEventListener("order_shipped", (e) => console.log(JSON.parse(e.data)));
WebSockets
Handshake
GET /chat HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://app.example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Client and server
const ws = new WebSocket("wss://chat.example.com/chat?token=SHORT_LIVED_TOKEN");
ws.onopen = () => ws.send(JSON.stringify({ type: "join", room: "general" }));
ws.onmessage = (e) => render(JSON.parse(e.data));
ws.onclose = () => setTimeout(reconnect, backoffWithJitter()); // always reconnect with backoff
# server with the `websockets` library
import asyncio, json, websockets
rooms: dict[str, set] = {}
async def handler(ws):
room = None
async for raw in ws:
msg = json.loads(raw)
if msg["type"] == "join":
room = msg["room"]; rooms.setdefault(room, set()).add(ws)
elif msg["type"] == "say" and room:
websockets.broadcast(rooms[room], json.dumps({"from": id(ws), "text": msg["text"]}))
if room:
rooms[room].discard(ws)
async def main():
async with websockets.serve(handler, "0.0.0.0", 8765, ping_interval=20):
await asyncio.Future()
asyncio.run(main())
Scaling WebSockets
Checklist: heartbeats (ping/pong every 20–30 s), idle timeouts aligned across LB/proxy/app, reconnect with exponential backoff + jitter, resume from the last acknowledged sequence number, per-connection send-buffer limits, graceful drain on deploys, and authorization on every message (not just at connect).
MQTT (IoT messaging)
| QoS | Guarantee | Messages | Use |
|---|---|---|---|
| 0 | at most once | PUBLISH | frequent telemetry where loss is fine |
| 1 | at least once (duplicates possible) | PUBLISH → PUBACK | most commands/events (make handlers idempotent) |
| 2 | exactly once (broker ↔ client) | PUBLISH → PUBREC → PUBREL → PUBCOMP | billing-critical, rarely needed |
Why MQTT for IoT: tiny overhead (2-byte header), works on flaky low-bandwidth networks, persistent sessions for intermittently connected devices, Last Will to detect offline devices, retained "last known state".
gRPC
syntax = "proto3";
package orders.v1;
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order); // unary
rpc WatchOrder(WatchOrderRequest) returns (stream OrderEvent); // server streaming
rpc UploadItems(stream Item) returns (UploadSummary); // client streaming
rpc Chat(stream ChatMessage) returns (stream ChatMessage); // bidirectional
}
message GetOrderRequest { string id = 1; }
message Order { string id = 1; string status = 2; int64 total_cents = 3; }
| REST/JSON | gRPC | |
|---|---|---|
| Contract | OpenAPI (optional) | .proto (required, codegen) |
| Payload | JSON text | Protobuf binary (smaller, faster) |
| Transport | HTTP/1.1 or 2 | HTTP/2 |
| Streaming | SSE/WebSocket bolt-ons | native, 4 modes |
| Browser support | native | needs gRPC-Web/Connect proxy |
| HTTP caching | yes | no |
| Best for | public APIs | internal microservices, mobile ↔ backend |
Remember deadlines (propagate them down the call chain) and load balancing: HTTP/2 keeps one long-lived connection, so L4 balancers pin all requests to one backend → use L7 (Envoy) or client-side balancing.
Webhooks
POST https://customer.example/hooks/payments
Content-Type: application/json
Webhook-Id: evt_7Hk2...
Webhook-Timestamp: 1791391200
Webhook-Signature: v1,9c1f... (HMAC-SHA256 of id.timestamp.body)
{"type":"payment.succeeded","data":{"payment_id":"pay_123","amount":4999}}
Retries with backoff, idempotent receivers (dedupe by event id), signature verification, timestamp tolerance (e.g. 5 minutes), and SSRF-safe delivery. The open Standard Webhooks spec captures these conventions.
WebRTC
Peer-to-peer media and data with built-in encryption. Needs signalling (your server), STUN (discover public address), TURN (relay fallback), and SFUs for group calls.
Decision table
| Need | Use |
|---|---|
| Notifications, live feed, progress, LLM tokens | SSE |
| Chat, multiplayer, collaborative editing | WebSocket |
| Mobile/IoT devices on unreliable links | MQTT |
| Internal service calls, streaming between services | gRPC |
| Notify a third party's server of events | Webhooks |
| Audio/video calls, P2P data | WebRTC |
| Updates every few minutes, simple infra | Polling (with ETags) |
| Clients that can't hold connections | Long polling fallback, or push notifications (APNs/FCM) |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.