Polling, Push or Callback? Choosing a Delivery Channel
Evaluate real-time communication patterns—short polling, long polling, Server-Sent Events, WebSockets, and Webhooks—to select the right delivery transport based on directionality, scale, and operational complexity.
Contentsand lesson path
On this page
- Why it matters
- The real-time delivery spectrum: mechanics and trade-offs
- Architectural decision framework
- Check your understanding
- Apply it
- Review prompt
Lessons of Real-Time APIs & Webhooks
- Polling, Push or Callback? Choosing a Delivery Channel Concept · 20 min
- Streaming Responses and Server-Sent Events Worked example · 25 min
- Lab: An Authenticated WebSocket Feed Across Workers Lab · 30 min
- Webhooks Others Can Trust: Sign, Retry, Verify Worked example · 25 min
- Long-Lived Connections in Production: Proxies, Limits and Deploys Concept · 15 min
- Check: Choose and Defend a Real-Time Design Knowledge check · 8 questions
What you will learn
- Choose short polling, long polling, server-sent events, WebSockets or webhooks for a requirement, justifying the choice by direction of data flow, latency, connection cost and proxy and client support.
Prerequisites: Async I/O in Python
01. Why it matters
Traditional web applications are built on the classic request-response model: the client requests data, the server processes the query, returns an HTTP response, and the connection closes or returns to a pool. However, users now expect updates within a second or two. When a ride-sharing driver moves on a map, a teammate comments on an issue, a payment confirms, or an AI generates tokens, waiting for a manual page refresh is unacceptable.
Engineering teams often jump prematurely to the most complex technology—such as maintaining stateful WebSocket clusters across thousands of concurrent clients—when simpler, more resilient alternatives exist. Teams that poll aggressively have the opposite problem: their primary database answers a steady stream of queries, most of which find nothing new.
Choosing the wrong transport pattern impacts server memory, battery life on mobile devices, firewall compatibility, and infrastructure bills. On mobile devices, frequent polling keeps the radio from dropping into its low-power states, which costs battery. On the server side, supporting tens of thousands of concurrent connections requires understanding the difference between thread-per-connection models and asynchronous non-blocking event loops.
This lesson compares five ways to deliver updates: short polling, long polling, Server-Sent Events (SSE), WebSockets and webhooks.
02. The real-time delivery spectrum: mechanics and trade-offs
Each channel makes a different trade between how long a connection stays open, how quickly news arrives, which side can send, and what the network in between has to allow:
- Short polling (the client asks on a timer). The client sends an ordinary HTTP
GETevery few seconds (for example every 2 to 5 seconds). It is easy to build and works with normal caching and load balancers. The cost is a trade you cannot escape: poll often and the database answers a stream of queries that find nothing new; poll rarely and users wait for news. - Long polling (the server holds the request). The client sends a request, and the server keeps it open until there is news or a timeout passes (often 30 to 60 seconds). The server then answers, and the client sends the next request at once. There are fewer empty answers, but every message still costs a full HTTP request and response with headers, and each waiting client holds one request open. Keep-alive reuses the TCP and TLS connection between polls, so the handshake is not repeated.
- Server-Sent Events (one-way push over HTTP). The server answers one request with
Content-Type: text/event-streamand keeps writing events into that response. Browsers read it with the built-inEventSourceAPI, which reconnects by itself: when the stream drops, the browser waits its reconnection time (a browser default of a few seconds, or the value the server last sent in aretry:field), may wait longer after failed attempts, and then reconnects with theLast-Event-IDheader so the server can resume. If the server answers a reconnect with any status other than200, or with another content type, the browser stops for good; a server can use204 No Contentto tell a client to stop on purpose. SSE is plain HTTP, so it passes most proxies and firewalls, but proxy buffering and response compression must be off for the stream (Cache-Control: no-cache,X-Accel-Buffering: noon nginx, no gzip), or events arrive late and in batches. Over HTTP/1.1 each stream also holds one of the roughly six connections a browser allows per origin, so a few open tabs can stall the rest of the page; serve SSE over HTTP/2, which carries many streams on one connection. - WebSockets (two-way, both sides send at any time). The connection starts as an HTTP request with an
Upgradeheader and then switches to a light binary framing protocol on the same TCP connection. Each frame adds only 2 to 14 bytes (client frames add a 4-byte mask), compared with hundreds of bytes of HTTP headers per request. WebSockets fit best when both client and server send frequent, low-latency messages. - Webhooks (server-to-server callbacks). No connection stays open. When an event happens, the sender makes an HTTP
POSTto a URL the subscriber registered earlier. Because nothing is held open between events, webhooks are the usual choice for integrations between two companies' back ends.
# Conceptual handler models in Python/FastAPI
# 1. Short Polling: Stateless, high request volume
@app.get("/api/v1/orders/{order_id}/poll")
async def poll_order(order_id: str, last_seen_status: str):
order = await get_order(order_id)
# most requests return an unchanged status
return {"status": order.status, "updated": order.status != last_seen_status}
# 2. Server-Sent Events: Unidirectional HTTP streaming
@app.get("/api/v1/orders/{order_id}/live-stream")
async def sse_order_stream(order_id: str, request: Request):
queue = await broker.subscribe(order_id) # one queue per connection
async def event_generator():
try:
while not await request.is_disconnected():
try:
event = await asyncio.wait_for(queue.get(), timeout=15)
except TimeoutError:
yield ": ping\n\n" # heartbeat; loop re-checks disconnect
continue
yield f"id: {event.id}\ndata: {event.payload}\n\n"
finally:
await broker.unsubscribe(order_id, queue) # free it on disconnect
return StreamingResponse(event_generator(), media_type="text/event-stream")
# 3. WebSockets: Bidirectional full-duplex socket
@app.websocket("/ws/collaboration/{board_id}")
async def ws_board(websocket: WebSocket, board_id: str):
await websocket.accept()
while True:
msg = await websocket.receive_text() # Client sends drawing actions
await broadcast_to_room(board_id, msg) # Server pushes to peers03. Architectural decision framework
When you choose a channel for a new feature, ask four questions:
- Which way does data flow? Does the client ever send messages on this channel? If data flows strictly from server to client (such as notification bells, crypto price tickers, or AI token streams), Server-Sent Events is usually simpler to build, debug and scale than WebSockets. If the client also sends frequent real-time messages (multiplayer games, canvas whiteboards, collaborative typing), WebSockets are the better fit.
- Who is on each end, a browser or a server? A browser page cannot run an HTTP server that the internet can reach, and most users sit behind NAT, so webhooks cannot target browser clients. For server-to-server notifications (e.g. a payment gateway notifying your billing service), webhooks avoid holding thousands of idle connections open around the clock.
- What happens with more than one server? WebSockets need sticky routing or a shared message channel between servers, often called a backplane (such as Redis Pub/Sub, NATS or RabbitMQ), because two users in the same room may be connected to different worker processes. SSE needs the same backplane for fan-out. Its reconnects are simpler, because EventSource reconnects with a plain HTTP request that any pod can answer, provided the events to replay after
Last-Event-IDlive in shared storage rather than in one pod's memory. - What sits on the network path? Company networks often run forward proxies, TLS inspection boxes and devices that close idle connections quickly. WebSockets use the standard HTTP
Upgradehandshake (RFC 6455), which some older or strict proxies still block or time out. SSE is ordinary HTTP streaming, so it passes most corporate proxies, ingress controllers and CDNs, as long as they do not buffer the response (see above).
04. Check your understanding
05. Apply it
Review the real-time requirements of your existing applications. Map each feature to this selection criteria:
- If you are currently polling an endpoint every few seconds to check for background export completion or status updates, refactor the endpoint to stream updates via Server-Sent Events.
- If you are maintaining a WebSocket connection purely to push notification counter updates to a top navbar, evaluate migrating to SSE to reduce socket connection management complexity and take advantage of HTTP/2 multiplexing.
- For asynchronous partner integrations, design an outbound Webhook system using your background job queue rather than forcing external clients to poll your REST endpoints.
In the next lesson, you will implement an end-to-end Server-Sent Events streaming endpoint with automatic reconnection and event replay.
06. Review prompt
Compare Short Polling, Server-Sent Events, WebSockets, and Webhooks across three dimensions: connection duration, message directionality, and operational complexity. Detail why Webhooks are unsuitable for browser clients, and explain how HTTP/2 multiplexing benefits SSE architectures over WebSockets.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.