Demystifying Long Polling: Real-Time Web Updates Without WebSockets

2026-11-29来源 dev.toEnglish
Demystifying Long Polling: Real-Time Web Updates Without WebSockets

What is Long Polling?

Long polling is a web communication technique where a client requests data from a server, but the server deliberately holds the request open until new information becomes available. Instead of instantly returning an empty response when no new data exists, the server waits patiently until an event occurs or a timeout is reached. Once the client receives the response, it immediately sends a brand-new request to restart the waiting process.

A Real-Life Analogy: The Coffee Shop Pager

Imagine walking into a busy coffee shop and ordering an espresso.

Under traditional short polling, you would stand at the counter and ask the barista every three seconds, "Is my espresso ready? Is my espresso ready? Is my espresso ready?" This creates unnecessary noise, annoys the staff, and wastes energy.

With long polling, you place your order, and the barista simply hands you a quiet buzzer pager. You step aside and wait. The barista does not talk back to you until your exact beverage is finished brewing. The moment the pager buzzes, you collect your coffee. If you want another drink, you immediately place a new order and receive a new pager to wait again. You get your coffee the instant it is ready without asking constantly.

Why Long Polling Matters in the Tech Industry

Engineers use long polling to build near-real-time features—such as live chat widgets, order status tracking, and notification feeds—on infrastructure where full WebSockets might be overkill or blocked by legacy network firewalls.

Standard HTTP requests are stateless and short-lived. If a frontend application needs to display live server updates, naive polling bombards the backend with thousands of useless HTTP requests per minute. This spikes database load, burns bandwidth, and consumes server CPU cycles for empty responses.

By adopting long polling, backend developers drastically reduce redundant network traffic while still achieving sub-second latency for end users. It serves as a reliable intermediate pattern between traditional REST APIs and full-duplex WebSockets.

A Simple Code Example in Express.js

Here is how you can implement a basic long polling endpoint in Node.js using Express.js. The server holds incoming requests in an array until a new message arrives:

const express = require('express'); const app = express(); app.use(express.json()); // Store pending client responses let waitingClients = []; // Long polling endpoint app.get('/api/messages/subscribe', (req, res) => { // Keep the HTTP connection open by saving res object waitingClients.push(res); // Set a safety timeout (30 seconds) to prevent infinite hanging req.setTimeout(30000, () => { waitingClients = waitingClients.filter(client => client !== res); res.status(204).end(); // No Content }); }); // Publisher endpoint to trigger updates app.post('/api/messages/send', (req, res) => { const { message } = req.body; // Resolve all pending long polling requests with the new data waitingClients.forEach(client => { client.json({ message, timestamp: new Date() }); }); // Clear the waiting list waitingClients = []; res.status(200).json({ success: true }); }); app.listen(3000, () => console.log('Long polling server running on port 3000')); 

On the client side, a simple recursive JavaScript function can maintain the connection loop continuously.

Key Takeaway

Long polling transforms the rigid request-response model of traditional HTTP into a responsive, event-driven listening system. While newer technologies like WebSockets and Server-Sent Events (SSE) offer true bi-directional streaming, long polling remains an essential, fallback-friendly architectural strategy for delivering immediate data updates across constrained enterprise environments.

Buy Me A Coffee

Enjoyed this breakdown? Support my open-source work on Buy Me a Coffee or explore react-hook-lab!

Originally published on my blog. You can read the alternative breakdown here.

原文:https://www.a8q9.cn/en/article/demystifying-long-polling-real-time-web-updates-without-websockets-81e4e2.html

相关文章