Skip to main content

Long Polling

What It Is

Long polling is a communication technique where the client asks the server for new data, but the server does not reply immediately.

Instead, the server keeps the request open until new data is available or a timeout happens.

Long Polling = Client asks once, server waits, then responds when data is ready

Simple Example

Think of messaging your friend and saying:

Reply when you have something.

Then you wait.

As soon as your friend has a reply, you get the answer.

That is how long polling works.


How It Works

Long polling keeps one request open instead of repeatedly asking every few seconds.

1. Client sends a request to the server
2. Server does not respond immediately
3. Server waits until new data is available or timeout happens
4. Server sends the response
5. Client immediately sends a new request
6. This cycle continues

The important idea is:

The client does not keep asking repeatedly.
The server holds the request until there is something useful to send.

Request Flow

In long polling, the client sends a request and the server keeps it pending.

Client -> Server
Server waits...
Server responds when data is ready
Client -> Server again

This reduces unnecessary empty responses compared to short polling.


Flow Diagram

Client                         Server
| |
| ---- Request: /getData ----> |
| |
| Server waits |
| |
| <---- Response: data ------- |
| |
| ---- New Request ----------> |
| |
| Server waits |
| |
| <---- Response: data ------- |
| |
| Repeat... |

When to Use

Long polling is useful when the app needs near real-time updates but WebSocket is not being used.

Common use cases:

  • chat applications before WebSockets
  • live notifications
  • messaging systems
  • collaborative tools with basic real-time sync
  • live dashboards with moderate real-time needs
Use long polling when you want fewer useless requests than short polling.

Advantages

Long polling is more efficient than short polling for update-based systems.

AdvantageMeaning
More efficient than short pollingRequests complete only when data is available or timeout happens
Closer to real-timeData is delivered as soon as the server has it
Uses normal HTTPNo advanced protocol like WebSocket is required
Good for medium-scale appsHandles real-time needs better than short polling

Disadvantages

Long polling still has scaling and connection-management problems.

DisadvantageProblem
Keeps connections openEach client may hold a connection for a long time
Harder to scaleMany open connections can become difficult to manage
Needs timeout handlingServer must handle cases where no data arrives
Slight delay between cyclesAfter response, client must send a new request again
Long polling reduces repeated requests, but open connections still cost server resources.

Short Polling vs Long Polling

FeatureShort PollingLong Polling
Client behaviorSends requests repeatedly at fixed intervalsSends request and waits
Server behaviorResponds immediately every timeWaits until data is available or timeout
Empty responsesManyFewer
Real-time feelDelayed until next intervalCloser to real-time
Server load typeToo many repeated requestsToo many open connections
Simple intuition“Did you reply?” again and again“Tell me when you reply.”

Frontend Code

This example sends a request to /getData and waits for the server response.

After receiving data, it immediately calls getData() again.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<title>Long Polling Example</title>
</head>

<body>
<h1>Long Polling Example</h1>

<div id="data-container"></div>

<script>
async function getData(lastData) {
try {
const response = await fetch(`/getData?lastData=${lastData}`);
const result = await response.json();

document.getElementById("data-container").innerHTML = result.data;

getData(result.data);
} catch (error) {
console.log(error);
}
}

getData();
</script>
</body>
</html>

Backend Code

This example uses Express.

If the server has new data, it responds immediately.

If the data has not changed, it keeps the response object inside waitingClientList.

const express = require("express");

const app = express();

let data = "Our initial data here";

const waitingClientList = [];

app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

app.get("/getData", (req, res) => {
if (data !== req.query.lastData) {
res.json({ data });
} else {
waitingClientList.push(res);
}
});

app.get("/updateData", (req, res) => {
data = req.query.data;

while (waitingClientList.length > 0) {
const client = waitingClientList.pop();
client.json({ data });
}

res.json({
success: "Data updated successfully",
});
});

app.listen(5000, () => {
console.log("App running on port 5000");
});

What Happens in the Code

The frontend starts by calling:

getData();

The request goes to the server with the last known data.

fetch(`/getData?lastData=${lastData}`);

If server data is different, the server responds immediately.

res.json({ data });

If server data is the same, the server keeps the client waiting.

waitingClientList.push(res);

When data is updated, the server responds to all waiting clients.

while (waitingClientList.length > 0) {
const client = waitingClientList.pop();
client.json({ data });
}

After receiving a response, the frontend immediately starts the next long polling request.

getData(result.data);

How to Test

Run the Express server.

node index.js

Open the browser.

http://localhost:5000

Open the Network tab.

You should see a request to:

/getData

The request may stay pending while the server waits for new data.

Then update data using:

/updateData?data=New message

The pending request will complete, the UI will update, and the client will immediately start a new long polling request.


Long Polling Table

AreaExplanation
Who starts communication?Client
Connection typeRequest is held open
Server behaviorWaits until new data or timeout
Real-time qualityClose to real-time
Implementation difficultyMedium
EfficiencyBetter than short polling
Best fitNotifications, messages, and moderate real-time updates

Basic Checklist

Send one request from the client
Keep the request open on the server
Respond when data changes
Reconnect immediately after each response
Handle timeout cases
Avoid holding connections forever
Track waiting clients carefully
Use when WebSocket is not required
Monitor server resources for many open connections

Interview Style Answer

Long polling is a communication technique where the client sends a request to the server, but the server does not respond immediately. It keeps the request open until new data becomes available or a timeout occurs. After receiving the response, the client immediately sends another request, so the cycle continues. Long polling is more efficient than short polling because it reduces repeated empty responses and gives updates closer to real time. However, it keeps connections open, which can consume server resources and become harder to scale with many users. It is useful for chat applications, live notifications, messaging systems, collaborative tools, and dashboards when WebSocket is not being used.


One-Line Summary

Long Polling = The client sends one request and the server waits to respond until new data is ready.

Final Mental Model

Client asks once
Server waits
Data changes
Server responds
Client asks again

Fewer useless requests, but more open connections.