Notes
All notes

Real-time APIs (API Design #4)

Your dashboard shows live delivery positions. Version one polls GET /vehicles every three seconds. With 50 dispatchers it is fine. With 5,000, you are serving 1,700 requests a second, 95% of which answer “nothing moved since last time” — a machine for asking anything yet? at data-center scale.

Real-time APIs invert the question: the server speaks when something happens. But “real-time” is not one technology, it is a spectrum — short polling, long polling, server-sent events, WebSockets, and out-of-band webhooks for server-to-server work. This chapter covers how each one actually moves bytes, what it costs to operate, and how to choose the cheapest mechanism that meets the requirement.

By the end you will be able to compute the waste of a polling design, implement an SSE stream and a webhook receiver, and defend the choice to not use WebSockets.

Polling and the price of asking

Short polling sends GET every \(T\) seconds. Two numbers define it: latency and waste. An event waits \(\bar{w} \approx T/2\) on average before the next poll notices it, and if events arrive every \(\bar{e}\) seconds with \(\bar{e} \gg T\), the fraction of requests that return nothing is

\[ \text{waste} = 1 - \frac{T}{\bar{e}} \]

Events every 60 s, polling every 3 s: 95% of requests are empty. Polling is still the right answer when updates are rare, consumers are few, and simplicity wins — a status page, a build badge. It fails when freshness and scale both matter.

Long polling patches the waste: the server holds the request open until an event arrives or a timeout (say 30 s) fires, then the client immediately re-asks. Empty responses mostly disappear and latency drops to ~instant, at the cost of one held connection per waiting client and a reconnect dance. It is what people used before WebSockets, and it survives today mainly behind restrictive proxies.

import requests

def long_poll(url: str, cursor: str | None, timeout: int = 30):
    while True:
        r = requests.get(url, params={"since": cursor}, timeout=timeout + 5)
        if r.status_code == 200:
            batch = r.json()
            for event in batch["events"]:
                yield event
            cursor = batch["next_cursor"]
        # 204 = nothing happened within timeout: reconnect immediately

Server-sent events: push over plain HTTP

SSE keeps one HTTP response open forever and streams events down it as text/event-stream. It is strictly one-directional — server to client — which happens to be exactly what feeds, tickers, logs, and progress bars need.

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

id: 1042
event: vehicle
data: {"id":"v-17","lat":28.61,"lng":77.20}

: heartbeat comment keeps intermediaries from closing the idle stream

Because SSE is HTTP, it inherits everything: proxies, TLS, auth headers, and — crucially — automatic reconnection with resume. A reconnecting browser sends Last-Event-ID: 1042, and the server replays from 1043. You get exactly-once-ish delivery over an at-most-once wire, for free.

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import asyncio, json

app = FastAPI()

async def events(after: int = 0):
    last = after
    while True:
        for e in await poll_events_since(last):       # your event store
            last = e["id"]
            yield f"id: {e['id']}\nevent: vehicle\ndata: {json.dumps(e)}\n\n"
        yield ": hb\n\n"                               # heartbeat every cycle
        await asyncio.sleep(15)

@app.get("/vehicles/stream")
async def stream(last_event_id: int = 0):
    return StreamingResponse(events(last_event_id),
                             media_type="text/event-stream")

Two operational notes. Held-open streams are connections: each costs memory and a file descriptor, so 100k dashboards mean 100k open sockets — fine for an event-loop server, fatal for a thread-per-connection one. And over HTTP/1.1 browsers cap ~6 connections per origin; serve SSE over HTTP/2 and streams multiplex onto one connection.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (c) at (0,1.6) {client};
  \node[b, fill=orange!16] (s) at (0,0) {server};
  \draw[a] (c) -- node[right, font=\rmfamily\scriptsize] {GET /stream (once)} (s);
  \draw[a, dashed, green!45!black] (s) to[bend left=18] node[left, font=\rmfamily\scriptsize] {event 1, 2, \dots\ (response never ends)} (c);
\end{tikzpicture}

One request, an unbounded response. The connection is the subscription.

WebSockets: when both sides talk

A WebSocket starts as HTTP, then upgrades (Upgrade: websocket) into a persistent TCP channel where either side sends frames at any time. That full-duplex property is the whole point: collaborative editors, chat, multiplayer games, live cursors — cases where the client streams as much as the server.

import asyncio, websockets

async def echo_counter(ws):
    n = 0
    async for message in ws:                 # client pushes
        n += 1
        await ws.send(f"ack {n}: {message}") # server pushes back

async def main():
    async with websockets.serve(echo_counter, "localhost", 8765):
        await asyncio.Future()

asyncio.run(main())

The bill for full-duplex arrives as operations work. You now own: reconnection and resume (no Last-Event-ID built in — you design the protocol), heartbeats (idle TCP gets silently reaped by NATs and load balancers), backpressure (a slow client behind a fast producer grows a queue until the server falls over), and stateful scaling — a socket lives on exactly one server, so broadcasting to 100k clients requires a pub/sub backbone (Redis, NATS) to fan out across your fleet.

The most common real-time mistake is paying this bill for a one-way feed. If the client never sends, SSE does the same job with half the machinery.

Webhooks: push between servers

A webhook is a reverse API call: you register a URL with a provider, and the provider POSTs events to it. Payment processors, CI systems, and email providers all work this way — server-to-server, so no browser and no held connections, just ordinary POSTs you must handle correctly.

POST /webhooks/payments
X-Signature: sha256=8f3ac2...
{
  "id": "evt_123",
  "type": "payment.succeeded",
  "data": { "order_id": "42", "amount": 1999 }
}

Three invariants make a webhook endpoint safe:

  1. Verify the signature. Your URL is public; anyone can POST “payment succeeded” to it. Providers sign the raw body with HMAC and a shared secret — recompute and compare in constant time.
  2. Be idempotent. Delivery is at-least-once: your 5-second silence triggers a retry, so evt_123 can arrive twice. Deduplicate on the event id.
  3. Ack fast, work async. Return 2xx within a couple of seconds — enqueue the real work. Slow handlers cause retries, which cause duplicates, which cause more load: a self-inflicted outage.
import hmac, hashlib

def verify(body: bytes, signature: str, secret: bytes) -> bool:
    expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)      # constant-time compare

Webhooks fail silently when your endpoint is down — no provider retries forever. The professional pattern pairs webhooks with reconciliation polling: a periodic job fetches events since your last processed id and heals any gap.

Choosing the mechanism

Requirement Latency Direction Cheapest fit
rare updates, few clients seconds pull short polling
frequent updates, hostile proxies ~instant server→client long polling
feeds, logs, progress, tickers instant server→client SSE
chat, collab editing, games instant bidirectional WebSockets
provider → your server instant server→server webhooks (+ reconciliation)

The cost model to internalize: every held-open connection is memory and a descriptor; every retry is duplicate work; every unverified webhook is an open door.

Pitfalls

QQuestionSelf-check

Your activity feed needs instant updates and the client never sends data — which mechanism, and why not the “richer” one? A payment provider POSTs to your webhook and your handler takes 20 s — describe the failure cascade. What does Last-Event-ID buy an SSE client that a WebSocket client must build itself?

ASolution

SSE: the traffic is server→client only, it rides plain HTTP (proxies, TLS, auth just work), and the browser reconnects automatically — WebSockets would add hand-rolled resume, heartbeats, and stateful scaling for no benefit. A 20 s handler makes the provider retry, each retry is another delivery (at-least-once), duplicates multiply load, and the endpoint falls further behind — ack in under a few seconds and process asynchronously, deduplicating by event id. Last-Event-ID gives automatic resume after a disconnect: the server replays from that id, so the client gets gap-free delivery; WebSockets has no such concept, so you must design sequence numbers and replay into your own protocol.

Next: Authentication Methods (API Design #5) — proving who the caller is, from Basic auth to JWT, OAuth 2.0, and OIDC.