{}DSA Atlas

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.

Intermediate → Advanced7 interview questions

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.

Short polling many empty answers Long polling server holds the request SSE one request, many events WebSocket upgrade, then both ways clientserver
Blue arrows carry useful data. Top line = client, bottom line = server in each row.

The options

Short pollingLong pollingSSEWebSocket
Directionclient pullserver push (emulated)server → clientbidirectional
TransportHTTPHTTPHTTP (1.1/2/3)TCP after HTTP upgrade
Latencyup to the intervallowlowlowest
Overheadhigh (empty polls)medium (re-requests)lowlowest per message
Reconnect / resumen/amanualbuilt-in (Last-Event-ID)manual
Binary datayesyesno (text)yes
Proxy/firewall friendlinessbestgoodgoodusually fine; some proxies interfere
Best forrare updates, dashboardsfallbacknotifications, feeds, LLM streamingchat, games, collaboration

Long polling

Python
# 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

HTTP
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

user A user B user C L4/L7 LBlong timeouts WS gateway 1 WS gateway 2 pub/subRedis / NATS / Kafka chat service presenceuser→gateway
A message from A (gateway 1) reaches C (gateway 2) through pub/sub; stateless services do the business logic.

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)

sensor: publish sensor: publish MQTT brokerEMQX · Mosquitto dashboard: home/+/temp alerts: home/# ingest → Kafka/TSDB topic: home/kitchen/temp · QoS 1 · retained
Publishers and subscribers never talk directly; the broker routes by topic.
QoSGuaranteeMessagesUse
0at most oncePUBLISHfrequent telemetry where loss is fine
1at least once (duplicates possible)PUBLISH → PUBACKmost commands/events (make handlers idempotent)
2exactly once (broker ↔ client)PUBLISH → PUBREC → PUBREL → PUBCOMPbilling-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

Protobuf
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/JSONgRPC
ContractOpenAPI (optional).proto (required, codegen)
PayloadJSON textProtobuf binary (smaller, faster)
TransportHTTP/1.1 or 2HTTP/2
StreamingSSE/WebSocket bolt-onsnative, 4 modes
Browser supportnativeneeds gRPC-Web/Connect proxy
HTTP cachingyesno
Best forpublic APIsinternal 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

Text
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

NeedUse
Notifications, live feed, progress, LLM tokensSSE
Chat, multiplayer, collaborative editingWebSocket
Mobile/IoT devices on unreliable linksMQTT
Internal service calls, streaming between servicesgRPC
Notify a third party's server of eventsWebhooks
Audio/video calls, P2P dataWebRTC
Updates every few minutes, simple infraPolling (with ETags)
Clients that can't hold connectionsLong polling fallback, or push notifications (APNs/FCM)

Interview questions

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.