What Is Long Polling? How It Works and When to Use It
Near real-time updates using nothing but HTTP. Here's how long polling works, how it compares with short polling and WebSockets, and when it's still the right call.
Long polling vs WebSockets
|
Long polling |
WebSockets | |
|---|---|---|
|
Connection |
A new HTTP request after every response |
One persistent connection |
|
Direction |
Server to client per request; client sends separately |
Both directions on the same connection |
|
Latency |
Low, plus a gap while the next request is sent |
Lowest; data sent the moment it exists |
|
Overhead per message |
Full HTTP headers each time |
A few bytes of framing |
|
Infrastructure |
Works anywhere HTTP works |
Needs WebSocket support in proxies and load balancers |
|
Server load |
Many held requests and reconnects |
Many open sockets, little churn |
|
Best for |
Fallbacks, low-frequency updates, restrictive networks |
Chat, presence, live collaboration, frequent updates |
What is long polling?
Long polling is a way to get near real-time updates over plain HTTP. The client asks the server for new data, and if there isn't any yet, the server doesn't answer straight away. It holds the request open until something arrives or a timeout passes, then responds. The client handles the response and immediately asks again.
The result feels like the server is pushing data, even though every exchange is still a normal request and response. That made long polling the standard trick for chat and notifications on the web before WebSockets were widely supported. It's sometimes grouped with other techniques under the name Comet.
How long polling works
1. The client opens a request
The client sends something like GET /updates?after=41, where 41 is the ID of the last message it has seen.
2. The server waits
If there's nothing newer than 41, the server keeps the request open instead of replying with "nothing new". It typically waits 20 to 30 seconds, short enough to stay under proxy and load balancer timeouts.
3. The server responds
As soon as a new message arrives, the server sends it in the response. If the timeout passes first, it sends an empty response (often 204 No Content).
4. The client asks again
The client processes any data, updates its cursor to the newest ID and sends the next request right away. There's almost always one request waiting on the server, so new data goes out within milliseconds of arriving.
Long polling vs short polling
Short polling asks on a fixed timer, say every 5 seconds, and the server answers immediately, usually with nothing. Updates arrive up to one interval late and most requests are wasted.
Long polling asks once and waits. Updates arrive almost as soon as they happen, and empty responses only happen when the timeout runs out. It's a lot more efficient than short polling, but it still opens a fresh HTTP request for every batch of updates, which is where WebSockets and server-sent events do better.
Rule of thumb: long polling is a good fallback and a fine choice for occasional updates. For chat, typing indicators or presence, use a WebSocket.
Long polling example in JavaScript
A minimal browser client. It keeps a cursor so nothing is missed between requests, and backs off after an error so a failing server isn't hammered.
async function longPoll() {
let after = 0;
while (true) {
try {
const res = await fetch(`/api/updates?after=${after}&wait=25`);
if (res.status === 204) continue; // timed out, ask again
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { messages } = await res.json();
for (const m of messages) {
console.log(m.text); // render the message
after = Math.max(after, m.id);
}
} catch (err) {
await new Promise((r) => setTimeout(r, 2000)); // back off, then retry
}
}
}
longPoll();
When long polling still makes sense
Fallback transport. Libraries like Socket.IO can use HTTP long polling when a WebSocket can't be opened, for example behind restrictive proxies.
Bots and integrations. Some APIs let a bot fetch updates by long polling instead of exposing a webhook endpoint. Telegram's Bot API
getUpdatesmethod is a well-known example.Low-traffic notifications. Job status, build progress or "your export is ready" messages where a persistent socket would be overkill.
Environments without WebSocket support. Older clients, some serverless platforms and locked-down networks.
Limits and pitfalls
Overhead on every update. Each response carries full HTTP headers and is followed by a new request. With frequent updates, that adds up fast compared with one open WebSocket.
One-way at a time. The held request only carries server-to-client data. Sending from the client needs a separate request.
Gaps between requests. A message can arrive while no request is open. Always send a cursor (last ID or timestamp) so the server can return what you missed.
Held connections cost resources. Thousands of waiting requests tie up threads or sockets on servers that weren't built for it. Use an async server.
Timeouts in the middle. Proxies and load balancers may cut connections that stay idle too long. Keep the wait below their limit.
Browser connection limits. Under HTTP/1.1, browsers allow about six connections per host, and a long poll permanently uses one of them.
How CometChat delivers real-time messages
Chat needs updates in both directions, many times a second, for every user online. That's the job WebSockets were built for.
A managed WebSocket connection, so you don't build polling
The CometChat SDKs open a WebSocket connection when a user logs in and keep it alive while the app is in the foreground, so messages, typing indicators, receipts and presence arrive the moment they happen. The SDK reconnects on its own when the network drops, and you can switch to manual mode if you want to control the connection yourself. For server-side events, use CometChat webhooks instead of polling the REST API. New to the protocol? Read what WebSockets are.
Frequently asked questions
Is long polling better than WebSockets?
Rarely. WebSockets have lower latency and far less overhead once the connection is open. Long polling wins when WebSockets are blocked or unsupported, or when updates are occasional enough that a persistent connection isn't worth it.
What is the difference between short polling and long polling?
Short polling asks on a fixed timer and gets an immediate answer, usually empty. Long polling asks once and the server waits until it has data, so updates arrive sooner and fewer requests are wasted.
How long should a long-polling request wait?
Usually 20 to 30 seconds. Stay below the idle timeout of any proxy or load balancer in between, or connections will be cut and look like errors.
Does Socket.IO use long polling?
It can. Socket.IO supports HTTP long polling as a transport and can upgrade to a WebSocket when one is available, or keep polling when it isn't.
Is long polling the same as server-sent events?
No. Server-sent events keep one HTTP response open and stream many events through it. Long polling closes the response after each batch and starts a new request.