Long Polling
Table of Contents
1. Introduction
Long polling is a technique used in web applications to provide real-time updates to the client without the need for constant polling. It is an improvement over traditional polling methods, allowing the server to hold a request open until new data is available, significantly reducing latency and unnecessary requests.
2. How It Works
In long polling, the client sends a request to the server, and the server keeps the request open until it has information to send back. Once the data is sent, the client immediately sends a new request, establishing a continuous connection.
Basic Flow
graph TD;
A[Client Sends Request] --> B[Server Holds Request];
B --> C{Data Available?};
C -->|Yes| D[Send Data to Client];
C -->|No| B;
D --> A;
3. Code Example
Server-side (Node.js Example)
const express = require('express');
const app = express();
let clients = [];
app.get('/poll', (req, res) => {
clients.push(res);
});
function notifyClients(data) {
clients.forEach(res => res.json(data));
clients = [];
}
// Simulate data update after 5 seconds
setTimeout(() => {
notifyClients({ message: 'New data available!' });
}, 5000);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Client-side (JavaScript Example)
function poll() {
fetch('/poll')
.then(response => response.json())
.then(data => {
console.log(data);
// Immediately call poll again
poll();
});
}
// Start polling
poll();
4. Best Practices
- Implement timeouts to prevent hanging requests.
- Use a maximum number of clients to avoid server overload.
- Optimize server response times to enhance user experience.
- Consider using WebSockets for bi-directional communication when necessary.
5. FAQ
What is the difference between long polling and regular polling?
Regular polling sends requests at fixed intervals regardless of whether new data is available, while long polling holds the request until new data is available, reducing unnecessary network traffic.
When should I use long polling?
Use long polling when you need real-time updates but cannot use WebSockets due to infrastructure limitations or compatibility issues.
Is long polling efficient?
Long polling is more efficient than regular polling as it reduces the number of requests sent to the server, but it may still not be as efficient as WebSockets for real-time applications.