HTTP Long Polling
The "hanging GET" — the server holds a request open until there's news, then the client asks again. Near-real-time over plain HTTP, and still the universal fallback.
On this page
Long polling is the clever hack that made real-time web apps possible before browsers had a proper way to do it. The client makes a request; if the server has nothing new, instead of replying empty it holds the request open until there’s data (or a timeout). As soon as the client gets a response, it immediately asks again — so there’s almost always a waiting request the server can answer the moment something happens.
The loop
async function subscribe(cursor = "") {
while (true) {
const res = await fetch(`/events?since=${cursor}`); // server waits up to ~30s
if (res.status === 200) {
const { events, next } = await res.json();
handle(events);
cursor = next;
} else if (res.status !== 204) {
await sleep(backoff()); // error: back off before retrying
}
}
}
The details that bite
- Timeouts. Proxies and load balancers often kill idle connections at around a minute. Hold for less than that, and
return an empty
204on timeout so the client simply loops. - Gaps between polls. Events that arrive between one response and the next request can be lost. Always send a
cursor (
?since=…) so the server can replay anything missed. This is the same idea asLast-Event-IDin Server-Sent Events (SSEs). - Server resources. Every waiting client holds a connection. That’s cheap with async I/O and painful with thread-per-request servers.
Where it fits now
SSE standardised the server-to-client half of this, and WebSockets cover two-way traffic. Long polling remains the fallback when long-lived connections are blocked by corporate proxies, and it’s still a sensible choice for “poll for jobs” APIs. Compare all four techniques in AJAX Polling.
- #long-polling
- #real-time
- #http
↩ Linked from (3)
- AJAX PollingGrowing
…polling | client asks | up to the interval | many empty requests | rare updates, simplest infrastructure | | HTTP Long Polling | server answers when ready | low | held connections | fallback, legacy, job queues | | Serv…
- Server-Sent Events (SSEs)Growing
…also sends frequently on the same channel. SSE is essentially the standardised, browser-supported version of HTTP Long Polling. The full comparison with polling and WebSockets, including the offline case, is in WebSocke…
- WebSocketsEvergreen
…tes are fine | AJAX Polling — simplest, cache-friendly | | The infrastructure won't carry SSE or WebSockets | HTTP Long Polling | | Connectivity is patchy | Offline-first: a local store and outbound queue, sync on reconn…
↪ Links to (3)
Related by topic
- Seed
requestAnimationFrame and High Refresh Rates
Frontend craft - Growingcase study
Smart TV Apps on Low-End Devices
Frontend craft - Growing
Snapshot and Delta Sync over WebSockets
Real-time UIs - Growingcase study
Building a Graph Component Library
Frontend craft