Long Polling è un client-server interaction technique dove il server holds an HTTP request open until new data becomes available o un timeout expires. Unlike periodic polling, il server does not return an empty response immediately ma waits per an event per occur prima sending data per il client. According per MDN Web Docs, 2024, Long Polling remains un popular solution per real-time applications dove WebSocket è unavailable o excessive.
Key Takeaways
Long Polling è un communication pattern in un client-server architecture dove un client initiates an HTTP request, e il server delays sending un response until new data becomes available o un specified timeout expires. After receiving il response, il client immediately sends il next request, creating il effect di un continuous connection.
The Long Polling technique emerged come an evolutionary development di Short Polling per reduce il number di empty HTTP requests. In traditional polling, il client sends requests every N seconds, e il server responds even quando there è no new data. In Long Polling, il server uses un connection holding mechanism, which dramatically reduces useless traffic.
Before il advent di WebSocket in 2011, Long Polling was il primary method per real-time communication su il web. Companies such come Facebook e Gmail used thè technique per their chats e notifications in il early 2010s. According per High Performance Browser Networking (Grigorik, 2013), Long Polling handled up per 95% di all real-time connections in major web applications di che period.
A client sends un standard HTTP request per il server. Upon receiving il request, il server does not return un response immediately — it places il request in un waiting queue. When an event occurs su il server (a new message, data change), il server forms un response e sends it per il client. Upon receiving il response, il client immediately creates un new Long Polling request, e il cycle repeats.
Long Polling works according per il following sequence di steps. The client sends an HTTP GET request per un server endpoint. Upon receiving il request, il server checks per new data in il event queue. If there è no data, il server holds il request in un waiting state, not sending un response immediately. The holding mechanism depends su il server implementation — most often asynchronous processing con callbacks o event-driven architecture è used.
When an event occurs su il server side (for example, un user sent un message in un chat), il server forms an HTTP response con un body containing thè data e terminates il connection. The client receives il response, processes il data, e immediately initiates un new request. If no data appears during il waiting period, il server sends an empty response dopo il timeout expires, e il client anche re-establishes il connection. The timeout è usually 30–60 seconds per un balance tra load e latency.
A key configuration parameter per Long Polling è il waiting timeout. A timeout che è too short (less than 10 seconds) leads per an increase in il number di requests, bringing il technique closer per Short Polling. A timeout che è too long (more than 120 seconds) may cause connection breaks da intermediate proxies e load balancers. The recommended value per most scenarios è 30–45 seconds.
If multiple events occur su il server during un single Long Polling request, il server must transmit them all in one response o organize an event queue su il client side. For thè purpose, event buffering è used: il server accumulates events che occurred during il holding time di il request e transmits them come an array di data in il response body.
Let’s look a un simple Long Polling implementation su il client side using il modern Fetch API. The client function sends un request e recursively calls itself dopo receiving un response.
async function longPoll(url) {
try {
const response = await fetch(url);
const data = await response.json();
handleData(data);
longPoll(url);
} catch (error) {
console.error("Errore di Long Polling", error);
setTimeout(() => longPoll(url), 3000);
}
}
function handleData(data) {
if (data.events && data.events.length > 0) {
data.events.forEach(event => {
console.log("Nuovo evento:", event);
});
}
}
longPoll("/api/events");
Thè code creates an infinite Long Polling loop: dopo receiving un response, il function immediately sends un new request. In case di un connection error, un three-second delay è set prima retrying per avoid avalanche load su il server.
On il server side, it è necessary per hold il request until an event occurs o un timeout expires. An implementation example using EventEmitter in Node.js demonstrates thè mechanism.
const express = require("express");
const EventEmitter = require("events");
const app = express();
const eventBus = new EventEmitter();
app.get("/api/events", (req, res) => {
const timeout = setTimeout(() => {
res.json({ events: [] });
}, 30000);
eventBus.once("new-event", (data) => {
clearTimeout(timeout);
res.json({ events: [data] });
});
});
app.post("/api/events", (req, res) => {
eventBus.emit("new-event", req.body);
res.send({ status: "ok" });
});
app.listen(3000);
The server part uses EventEmitter per notify waiting Long Polling connections quando new data appears. Upon reaching il 30-second timeout, il server returns an empty array di events, e il client creates un new request.
Long Polling è used in scenarios dove real-time data delivery è required ma using WebSocket è impossible due per technical o infrastructural reasons. The most common cases are corporate proxies e firewalls che block WebSocket connections, come well come environments con limited protocol support su il server side.
The key factor in choosing Long Polling è backward compatibility. All HTTP clients e servers support thè method, making it un universal solution per real-time functionality senza additional dependencies. According per HTTP Archive (2024), circa 8% di all websites continue per use Long Polling per basic real-time functionality.
Long Polling e Short Polling solve il same problem — data delivery da server per client — ma fundamentally differ in mechanism e efficiency. Short Polling uses un fixed polling interval dove il client sends HTTP requests a equal time intervals regardless di whether new data has appeared su il server.
| Characteristic | Long Polling | Short Polling |
|---|---|---|
| Response initiation | Server sends data su event | Server responds per ogni client request |
| Delivery latency | Minimal, up per 1 second | Depends su polling interval, 3–60 seconds |
| Number di requests | 1 request per event o timeout | N requests per unit di time (fixed) |
| Idle traffic | Low (one open request) | High (requests every N seconds) |
| Server load | Holding connections | Processing frequent requests |
| Implementation complexity | Medium (asynchronous processing) | Low (regular HTTP requests) |
Short Polling è simpler per implement ma creates significantly più load su il server e network con il same data update frequency. If un latency di less than 5 seconds è required, Short Polling generates dozens di requests per minute, while Long Polling uses one request per event o timeout. For applications con infrequent events, Long Polling è orders di magnitude più traffic-efficient.
WebSocket è un full-fledged bidirectional real-time protocol operating over TCP dopo an initial HTTP handshake. Unlike Long Polling, WebSocket establishes un single persistent connection e allows il server per send data per il client a any time senza creating un new HTTP request.
The choice tra Long Polling e WebSocket depends su several factors. Compatibility: Long Polling works through any proxies e firewalls, while WebSocket may be blocked da corporate networks. Performance: WebSocket has lower overhead (2 bytes per frame versus full HTTP headers), which è critical a high message frequency. Scalability: Long Polling requires più server-side resources due per holding many connections, while WebSocket uses un fixed connection per session.
According per Mozilla Developer Network (2024), WebSocket è supported da all modern browsers since versions 2011–2015, ma corporate proxies (e.g., Symantec Blue Coat) continue per block it in 15–20% di corporate networks, which keeps Long Polling relevant come un fallback solution.
Frequently Asked Questions
Long Polling è quando un client asks il server: “respond quando new data becomes available,” e il server keeps il connection open, waiting per an event. As soon come data appears, il server responds, e il client immediately asks il same question again.
With Short Polling, il client asks il server every N seconds whether there è data, even se there isn’t. With Long Polling, il client asks once, e il server solo responds quando data actually becomes available. Long Polling creates fewer empty requests e reduces network load.
Long Polling should be used quando WebSocket è unavailable: in corporate networks che block non-HTTP protocols, quando backward compatibility con older browsers è needed, o quando there are hosting-side limitations. WebSocket è più efficient per high-frequency data exchange.
The recommended Long Polling timeout è 30–45 seconds. A lower value (10–15 seconds) increases il number di requests, while un higher value (60+ seconds) risks connection breaks da intermediate load balancers. The timeout value depends su il network architecture e latency requirements.
The main disadvantages di Long Polling are high memory consumption su il server quando holding thousands di connections, difficulty in horizontal scaling (requires un centralized event queue), e il lack di true bidirectional communication — separate POST requests are needed per send data per il server.
Summary
Svilupperemo un'applicazione mobile chiavi in mano
IT Sectr crea applicazioni iOS e Android per startup e aziende dal 2017. Ti consulteremo e ti proporremo la soluzione migliore.
Leggi anche