Ask the server, and it waits to answer until it has news.
Long polling is a trick to get news from a server quickly using plain HTTP. The browser asks “Anything new?”. The server does not answer right away. It waits until it has news, then replies.
HTTP is built as request and response. The client always speaks first. The server can never start talking by itself. So how does a web page learn that a new message arrived?
We want fresh data without refreshing the page. Short polling is easy, but it has two problems:
Making the gap smaller fixes the delay but makes the waste worse. Long polling gets both: few wasted calls and fast news.
| Point | Short polling | Long polling |
|---|---|---|
| Who decides when to answer? | Server answers at once | Server answers when it has news (or times out) |
| Wasted requests | Many | Few |
| Delay for news | Up to the polling gap | Almost none |
| Server resources | Short work, many times | One held connection per user |
| Needs special protocol? | No | No |
async function poll(lastId) {
try {
const res = await fetch("/updates?since=" + lastId, { signal: AbortSignal.timeout(35000) });
if (res.status === 200) {
const data = await res.json();
show(data.events);
lastId = data.lastId;
}
} catch (e) {
await sleep(2000); // network error: wait a little, then retry
}
poll(lastId); // ask again straight away
}
poll(0);since=lastEventId so no event is missed between two requests.| Term | Meaning in easy words |
|---|---|
| Polling | Asking the server again and again if there is news |
| Short polling | Polling on a timer. The server answers at once, even with 'nothing new' |
| Long polling | The server holds the request open until it has news or times out |
| Timeout | The longest time the server will hold a request before replying empty |
| Event id / cursor | A marker that tells the server what you already have |
| Backoff | Waiting longer after each failure before trying again |
| Jitter | A small random delay so many clients do not act at the same instant |
| Wasted request | A request whose answer is 'nothing new' |
| Stateless | The server remembers nothing between requests. Long polling is mostly stateless, apart from the waiting request |
| Long polling | SSE | WebSockets | |
|---|---|---|---|
| Direction | Server to client (one reply per request) | Server to client | Both ways |
| Protocol | Plain HTTP | HTTP, kept open | Upgrades to its own protocol |
| Auto-reconnect | You write it | Built in (EventSource) | You write it |
| Firewall friendly | Best | Good | Sometimes blocked |
| Cost per message | Highest (new request) | Low | Lowest |
| Best for | Fallback, simple needs | Live feeds, notifications | Chat, games, collaboration |