Polling and long polling
The simplest way to get updates is short polling: ask every few seconds.
every 5 s: GET /api/orders/1842/status -> "preparing" (no change)
GET /api/orders/1842/status -> "preparing" (no change)
GET /api/orders/1842/status -> "on the way" (finally)It’s easy and works everywhere, but it’s wasteful (most answers say “nothing new”) and slow (a change waits up to 5 seconds to be seen). Polling every second makes it faster and ten times more expensive.
Long polling fixes both. The client sends a request, and the server doesn’t answer until it has something to say, or until a timeout of about 30 seconds passes:
GET /api/messages?after=1041 ... server waits ...
<- 200 [message 1042] (sent the moment it arrived)
GET /api/messages?after=1042 ... server waits 30 s, nothing happens ...
<- 204 No Content (timeout: ask again)
GET /api/messages?after=1042 ...As soon as a response arrives, the client sends the next request. Updates arrive almost instantly, and quiet periods cost one request per 30 seconds.
The after=1042 part is a cursor: the ID of the last message the client has. If a message arrives in the short gap between two requests, the next request still gets it, because the server returns everything after the cursor. Without a cursor, messages get lost.
- Short polling is fine when updates are rare and a delay is acceptable (a report that takes minutes); use
ETagand conditional requests so “no change” costs a 304. RespectRetry-Afteron 429 and 503. - Long polling costs a held request per client: cheap with async servers (event loops, coroutines, virtual threads), expensive with a thread per request. Keep the hold below every timeout on the path (load balancers often default to 60 s, some proxies 30 s).
- Cursor semantics: return everything after the cursor, in order, with the new cursor; the server must keep recent events long enough for slow clients, or answer “cursor too old, resync”.
- Delivery: with cursors it’s at-least-once from the client’s view (a response lost on the way is re-requested), so deduplicate by event ID.
- Retry policy: exponential backoff with jitter on errors; immediate re-request only after a successful response.
- Long polling still works through every proxy and corporate firewall, which is why libraries like Socket.IO and SignalR use it as a fallback.
Predict the output
A long-polling client sends GET /api/messages?after=1041. Message 1042 arrives at the server 10 seconds later, and message 1043 arrives 0.1 seconds after that, while the response with 1042 is still on its way. What does the client end up with?
t=0s GET /api/messages?after=1041 (held)
t=10.0s message 1042 arrives -> response [1042]
t=10.1s message 1043 arrives (no request open)
t=10.2s GET /api/messages?after=1042 -> response [1043] at onceThe first response carries 1042 and the client's next request is ?after=1042. The server has 1043 stored, so it answers at once instead of waiting. That's the job of the cursor: the gap between two requests loses nothing. A design that only pushes 'new' messages to whoever is waiting at that moment would lose 1043.
// Android: coroutine loop with a cursor and backoff on errors
suspend fun pollMessages(api: ChatApi, onMessages: (List<Message>) -> Unit) {
var cursor = store.lastMessageId()
var delayMs = 1_000L
while (currentCoroutineContext().isActive) {
try {
val batch = api.messages(after = cursor, waitSeconds = 30) // held by the server
if (batch.isNotEmpty()) {
onMessages(batch)
cursor = batch.last().id
}
delayMs = 1_000L // success: ask again right away
} catch (e: IOException) {
delay(delayMs + Random.nextLong(delayMs)) // backoff with jitter
delayMs = minOf(delayMs * 2, 60_000L)
}
}
}async function pollMessages(onMessages: (m: Message[]) => void, signal: AbortSignal) {
let cursor = localStorage.getItem('cursor') ?? '0';
let delayMs = 1000;
while (!signal.aborted) {
try {
const res = await fetch(`/api/messages?after=${cursor}&wait=30`, { signal });
if (res.status === 200) {
const batch: Message[] = await res.json();
onMessages(batch);
cursor = batch.at(-1)!.id;
}
delayMs = 1000;
} catch {
await new Promise((r) => setTimeout(r, delayMs + Math.random() * delayMs));
delayMs = Math.min(delayMs * 2, 60_000);
}
}
}The loop that never rests
Tap the line with the bug.
suspend fun pollMessages(api: ChatApi) {
var cursor = store.lastMessageId()
while (true) {
try {
val batch = api.messages(after = cursor, waitSeconds = 30)
if (batch.isNotEmpty()) cursor = batch.last().id
show(batch)
} catch (e: IOException) {
log("poll failed, retrying")
}
}
}async function pollMessages() {
let cursor = loadCursor();
while (true) {
try {
const res = await fetch('/api/messages?after=' + cursor + '&wait=30');
const batch = await res.json();
if (batch.length) cursor = batch.at(-1).id;
show(batch);
} catch (e) {
console.log('poll failed, retrying');
}
}
}Hint: The server is down for a minute. How long does each failing request take, and what does the loop do next?
When the server is reachable, each request waits up to 30 seconds, so the loop is calm. When the server is down or the phone has no network, the request fails immediately, and the loop retries immediately, forever: thousands of requests per second from one client, a hot CPU, a drained battery, and a log full of “poll failed”.
Now multiply by every client: when the server comes back after a deploy, all of them hit it in the same instant, which can take it down again.
Wait before retrying, longer after each failure, with some randomness so clients spread out:
} catch (e: IOException) {
delay(delayMs + Random.nextLong(delayMs))
delayMs = minOf(delayMs * 2, 60_000L)
}} catch (e) {
await new Promise((r) => setTimeout(r, delayMs + Math.random() * delayMs));
delayMs = Math.min(delayMs * 2, 60_000);
}Reset delayMs to its starting value after a successful response.
Deep diveReconnect storms after a deployInterview favorite
“Every time we deploy the real-time service, the database falls over.” The pattern is the same for long polling, SSE and WebSockets: a server holding 200,000 open connections restarts, all 200,000 clients notice within seconds, and they all reconnect and resync at the same moment.
The damage comes from three things at once: the connection handshakes themselves (TCP, TLS, authentication on every one), the catch-up queries (“give me everything since my cursor” for every client), and retries of the failures caused by the first two.
What to say:
- Clients: exponential backoff with full jitter (a random delay between 0 and the current backoff), a random delay before the first reconnect after a clean server close, and a cap. Honour a server hint (
Retry-After, the SSEretry:field, a WebSocket close reason). - Servers: drain gracefully during deploys: stop accepting new connections, then close existing ones gradually over minutes, not all at once; roll instances one at a time.
- Cheap resync: cursors that hit an index or an in-memory log (Redis Streams, Kafka) rather than a heavy database query; a “cursor too old, fetch a snapshot” path with its own rate limit.
- Admission control: rate-limit reconnects and catch-up per instance, shed load with 503 and
Retry-Afterinstead of falling over. - Measure reconnects per second and catch-up latency; test a full restart in staging with realistic client counts.
The same thinking applies to a mobile app coming back from airplane mode or a train tunnel: one reconnect with a cursor, not a burst of retries.
- Short polling: simple, wasteful; use ETags so “no change” is a 304. Long polling: server holds the request until news or ~30 s timeout.
- Cursors make delivery gap-free and at-least-once; deduplicate by ID; keep holds below proxy and load balancer timeouts.
- Backoff with jitter on errors, immediate re-request only after success; graceful draining on deploys to avoid reconnect storms.
GET /api/messages?after=1042&wait=30 -> 200 [events] | 204 (timeout) then repeat with the new cursorCheck this part
What does the server do with a long-polling request when it has no news?
Why does a long-polling request include ?after=1042?
A deploy restarts servers holding 200,000 connections, and the database falls over. Best client-side fix?
What limits how long a server should hold a long-poll request?