Long Polling: nó là gì, cách hoạt động và nơi sử dụng

Tác giả: IT Sectr Đã đăng: 2026-06-02 Thời gian đọc: 8 phút

Long Polling là một client-server interaction technique nơi các server holds an HTTP request open until new data becomes available hoặc một timeout expires. Unlike periodic polling, các server does not return an empty response immediately nhưng waits cho an event để occur trước sending data để các client. According để MDN Web Docs, 2024, Long Polling remains một popular solution cho real-time applications nơi WebSocket là unavailable hoặc excessive.

Key Takeaways

  • Long Polling — một technique nơi các server holds an HTTP request until data becomes available và chỉ sau đó sends một response để các client.
  • Mechanism — based trên long HTTP connections: các client sends một request, các server does not respond immediately nhưng waits cho an event hoặc timeout.
  • Difference từ Short Polling là rằng các server initiates data transmission, và các client does not poll các server trên một timer.
  • Use cases include chats, notifications, activity feeds, và real-time monitoring systems.
  • Limitation — high server load với một large number của concurrent connections due để keeping open requests.

What là Long Polling

Long Polling là một communication pattern trong một client-server architecture nơi một client initiates an HTTP request, và các server delays sending một response until new data becomes available hoặc một specified timeout expires. After receiving các response, các client immediately sends các next request, creating các effect của một continuous connection.

The Long Polling technique emerged như an evolutionary development của Short Polling để reduce các number của empty HTTP requests. In traditional polling, các client sends requests every N seconds, và các server responds even khi ở đó là no new data. In Long Polling, các server uses một connection holding mechanism, which dramatically reduces useless traffic.

The History của Long Polling

Before các advent của WebSocket trong 2011, Long Polling was các primary method cho real-time communication trên các web. Companies such như Facebook và Gmail used thlà technique cho their chats và notifications trong các early 2010s. According để High Performance Browser Networking (Grigorik, 2013), Long Polling handled lên để 95% của all real-time connections trong major web applications của rằng period.

Basic Principle của Long Polling

A client sends một standard HTTP request để các server. Upon receiving các request, các server does not return một response immediately — it places các request trong một waiting queue. When an event occurs trên các server (a new message, data change), các server forms một response và sends it để các client. Upon receiving các response, các client immediately creates một new Long Polling request, và các cycle repeats.

How Long Polling Works

Long Polling works according để các following sequence của steps. The client sends an HTTP GET request để một server endpoint. Upon receiving các request, các server checks cho new data trong các event queue. If ở đó là no data, các server holds các request trong một waiting state, not sending một response immediately. The holding mechanism depends trên các server implementation — most often asynchronous processing với callbacks hoặc event-driven architecture là used.

When an event occurs trên các server side (for example, một user sent một message trong một chat), các server forms an HTTP response với một body containing thlà data và terminates các connection. The client receives các response, processes các data, và immediately initiates một new request. If no data appears trong suốt các waiting period, các server sends an empty response sau các timeout expires, và các client cũng re-establishes các connection. The timeout là usually 30–60 seconds cho một balance giữa load và latency.

Timeouts và Connection Management

A key configuration parameter cho Long Polling là các waiting timeout. A timeout rằng là too short (less than 10 seconds) leads để an increase trong các number của requests, bringing các technique closer để Short Polling. A timeout rằng là too long (more than 120 seconds) may cause connection breaks bởi intermediate proxies và load balancers. The recommended value cho most scenarios là 30–45 seconds.

Handling Multiple Events

If multiple events occur trên các server trong suốt một single Long Polling request, các server must transmit them all trong one response hoặc organize an event queue trên các client side. For thlà purpose, event buffering là used: các server accumulates events rằng occurred trong suốt các holding time của các request và transmits them như an array của data trong các response body.

Long Polling Implementation Example trong JavaScript

Let’s look tại một simple Long Polling implementation trên các client side using các modern Fetch API. The client function sends một request và recursively calls itself sau receiving một response.

js
async function longPoll(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();

        handleData(data);
        longPoll(url);
    } catch (error) {
        console.error("Lỗi Long Polling", error);
        setTimeout(() => longPoll(url), 3000);
    }
}

function handleData(data) {
    if (data.events && data.events.length > 0) {
        data.events.forEach(event => {
            console.log("Sự kiện mới:", event);
        });
    }
}

longPoll("/api/events");

Thlà code creates an infinite Long Polling loop: sau receiving một response, các function immediately sends một new request. In case của một connection error, một three-second delay là set trước retrying để avoid avalanche load trên các server.

Server Implementation trên Node.js

On các server side, it là necessary để hold các request until an event occurs hoặc một timeout expires. An implementation example using EventEmitter trong Node.js demonstrates thlà mechanism.

js
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 để notify waiting Long Polling connections khi new data appears. Upon reaching các 30-second timeout, các server returns an empty array của events, và các client creates một new request.

When để Use Long Polling

Long Polling là used trong scenarios nơi real-time data delivery là required nhưng using WebSocket là impossible due để technical hoặc infrastructural reasons. The most common cases are corporate proxies và firewalls rằng block WebSocket connections, như well như environments với limited protocol support trên các server side.

  • Chats và messengers — Long Polling provides message delivery trong web versions của messengers operating trên HTTP không có WebSocket.
  • Dashboard panels — real-time systems cho DevOps metrics, logs, và alerts nơi data timeliness với 1–5 second delay là important.
  • Notifications — push-like delivery của alerts trong các browser không có using Service Workers và Push API.
  • Activity feeds — social networks và news feeds với automatic content updates khi new posts appear.
  • Collaboration — Google Docs-like editors với basic synchronization của changes giữa users.

The key factor trong choosing Long Polling là backward compatibility. All HTTP clients và servers support thlà method, making it một universal solution cho real-time functionality không có additional dependencies. According để HTTP Archive (2024), về 8% của all websites continue để use Long Polling cho basic real-time functionality.

Long Polling vs Short Polling

Long Polling và Short Polling solve các same problem — data delivery từ server để client — nhưng fundamentally differ trong mechanism và efficiency. Short Polling uses một fixed polling interval nơi các client sends HTTP requests tại equal time intervals regardless của whether new data has appeared trên các server.

CharacteristicLong PollingShort Polling
Response initiationServer sends data trên eventServer responds để mỗi client request
Delivery latencyMinimal, lên để 1 secondDepends trên polling interval, 3–60 seconds
Number của requests1 request per event hoặc timeoutN requests per unit của time (fixed)
Idle trafficLow (one open request)High (requests every N seconds)
Server loadHolding connectionsProcessing frequent requests
Implementation complexityMedium (asynchronous processing)Low (regular HTTP requests)

Short Polling là simpler để implement nhưng creates significantly nhiều hơn load trên các server và network với các same data update frequency. If một latency của less than 5 seconds là required, Short Polling generates dozens của requests per minute, trong khi Long Polling uses one request per event hoặc timeout. For applications với infrequent events, Long Polling là orders của magnitude nhiều hơn traffic-efficient.

Long Polling vs WebSocket

WebSocket là một full-fledged bidirectional real-time protocol operating trên TCP sau an initial HTTP handshake. Unlike Long Polling, WebSocket establishes một single persistent connection và allows các server để send data để các client tại any time không có creating một new HTTP request.

The choice giữa Long Polling và WebSocket depends trên several factors. Compatibility: Long Polling works qua any proxies và firewalls, trong khi WebSocket may be blocked bởi corporate networks. Performance: WebSocket has lower overhead (2 bytes per frame versus full HTTP headers), which là critical tại high message frequency. Scalability: Long Polling requires nhiều hơn server-side resources due để holding many connections, trong khi WebSocket uses một fixed connection per session.

  • Long Polling — các best choice cho applications với low event frequency (1–10 events per minute), limited infrastructure, hoặc các need để support older browsers.
  • WebSocket — các optimal solution cho high-load real-time applications (stock exchange data, online games, collaborative editors) với hundreds của messages per second.
  • Hybrid approach — một số applications use Long Polling như một fallback cho clients rằng do not support WebSocket, với automatic protocol switching.

According để Mozilla Developer Network (2024), WebSocket là supported bởi all modern browsers since versions 2011–2015, nhưng corporate proxies (e.g., Symantec Blue Coat) continue để block it trong 15–20% của corporate networks, which keeps Long Polling relevant như một fallback solution.

Frequently Asked Questions

What là Long Polling trong simple terms?

Long Polling là khi một client asks các server: “respond khi new data becomes available,” và các server keeps các connection open, waiting cho an event. As soon như data appears, các server responds, và các client immediately asks các same question again.

How là Long Polling different từ Short Polling?

With Short Polling, các client asks các server every N seconds whether ở đó là data, even nếu ở đó isn’t. With Long Polling, các client asks once, và các server chỉ responds khi data actually becomes available. Long Polling creates fewer empty requests và reduces network load.

When should I use Long Polling instead của WebSocket?

Long Polling should be used khi WebSocket là unavailable: trong corporate networks rằng block non-HTTP protocols, khi backward compatibility với older browsers là needed, hoặc khi ở đó are hosting-side limitations. WebSocket là nhiều hơn efficient cho high-frequency data exchange.

What timeout should I set cho Long Polling?

The recommended Long Polling timeout là 30–45 seconds. A lower value (10–15 seconds) increases các number của requests, trong khi một higher value (60+ seconds) risks connection breaks bởi intermediate load balancers. The timeout value depends trên các network architecture và latency requirements.

What are các disadvantages của Long Polling?

The main disadvantages của Long Polling are high memory consumption trên các server khi holding thousands của connections, difficulty trong horizontal scaling (requires một centralized event queue), và các lack của true bidirectional communication — separate POST requests are needed để send data để các server.

Summary

  • Long Polling — một real-time data transfer technique nơi các server holds an HTTP request until an event occurs và chỉ sau đó sends một response để các client.
  • Mechanism — based trên asynchronous HTTP connection holding: các server does not return an empty response nhưng waits cho data hoặc một 30–45 second timeout.
  • Advantage — compatibility với all HTTP infrastructure: proxies, load balancers, và firewalls do not block Long Polling unlike WebSocket.
  • Disadvantage — resource-intensive trên các server side: mỗi connection consumes memory và requires asynchronous processing even khi ở đó are no events.
  • Use cases — chats, notifications, dashboard panels, activity feeds, và collaborative editors với low update frequency.
  • Comparison — nhiều hơn efficient than Short Polling cho infrequent events, nhưng inferior để WebSocket trong performance và scalability cho high-frequency scenarios.
  • Recommendation — use Long Polling như một fallback khi WebSocket là unavailable hoặc cho simple real-time scenarios với low event frequency.

Chúng tôi sẽ phát triển ứng dụng di động chìa khóa trao tay

IT Sectr tạo các ứng dụng iOS và Android cho các công ty khởi nghiệp và doanh nghiệp từ năm 2017. Chúng tôi sẽ tư vấn và đề xuất giải pháp tốt nhất cho bạn.

Thảo luận dự án

Đọc thêm