Polling vs Server‑Sent Events vs WebSockets: Choosing the Right Real‑Time Communication Method
This article compares three real‑time data delivery techniques—long/short polling, Server‑Sent Events, and WebSockets—explaining their mechanisms, advantages, drawbacks, and providing sample client‑server implementations to help developers select the most suitable approach for a dashboard that streams GitHub/Twitter activity.
Building real‑time web applications requires a way to push data from the server to the client. Historically there are two generic approaches: client‑initiated requests (polling) and server‑initiated pushes.
The three main techniques are:
Long/short polling (client pull)
WebSockets (server push)
Server‑Sent Events (SSE, server push)
1. Polling
Polling lets the client periodically request new data. Short polling uses a fixed‑interval AJAX timer, while long polling (Comet) keeps the request open until the server has data. A simple long‑polling client example:
/* Client - subscribing to the github events */
subscribe: (callback) => {
const pollUserEvents = () => {
$.ajax({
method: 'GET',
url: 'http://localhost:8080/githubEvents',
success: (data) => { callback(data) },
complete: () => { pollUserEvents() },
timeout: 30000
})
}
pollUserEvents()
}Drawbacks include multiple TCP round‑trips, lack of multiplexing, and timeout issues when connections stay idle.
2. WebSockets
WebSocket provides a persistent, full‑duplex TCP connection, upgraded from HTTP via the Upgrade header. It works on ports 80/443 and is compatible with HTTP proxies.
Simple WebSocket client:
$(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
const connection = new WebSocket('ws://localhost:8080/githubEvents');
connection.onopen = function () { /* ready */ };
connection.onerror = function (error) { /* handle error */ };
connection.onmessage = function (message) {
try {
const githubEvent = JSON.parse(message.data);
// display event
} catch (e) {
console.log('Invalid JSON: ' + message.data);
return;
}
};
});Server‑side Node.js example using express-ws:
const express = require('express');
const events = require('./events');
const path = require('path');
const app = express();
const port = process.env.PORT || 5001;
const expressWs = require('express-ws')(app);
app.get('/', (req, res) => res.sendFile(path.join(__dirname + '/static/index.html')));
app.ws('/', (ws, req) => {
const githubEvent = {};
ws.send('message', githubEvent);
});
app.listen(port, () => console.log('Listening on', port));WebSockets require custom handling of HTTP‑level concerns and do not benefit from HTTP/2 multiplexing; they also operate on frames rather than streams.
3. Server‑Sent Events (SSE)
SSE establishes a single HTTP connection over which the server pushes events to the client using the EventSource API, following a one‑way publish‑subscribe model. It works natively in most modern browsers and can be polyfilled.
Client example:
const evtSource = new EventSource('/events');
evtSource.addEventListener('event', function(evt) {
const data = JSON.parse(evt.data);
// use data
}, false);Node.js server implementation:
// events.js
const EventEmitter = require('eventemitter3');
const emitter = new EventEmitter();
function subscribe(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
const heartbeat = setInterval(() => res.write('
'), 15000);
const onEvent = data => {
res.write('retry: 500
');
res.write(`event: event
`);
res.write(`data: ${JSON.stringify(data)}
`);
};
emitter.on('event', onEvent);
req.on('close', () => { clearInterval(heartbeat); emitter.removeListener('event', onEvent); });
}
function publish(eventData) { emitter.emit('event', eventData); }
module.exports = { subscribe, publish };
// App.js
const express = require('express');
const events = require('./events');
const app = express();
app.get('/events', events.subscribe);
app.listen(process.env.PORT || 5001, () => console.log('Listening'));SSE advantages: simpler implementation, higher data efficiency, automatic HTTP/2 multiplexing, and a single persistent connection per client. It is well‑suited for real‑time dashboards, live news feeds, and monitoring dashboards.
Choosing between the three depends on use‑case requirements: SSE is ideal for one‑way streams with HTTP/2 support, WebSockets excel in bidirectional, high‑frequency communication (e.g., multiplayer games), and polling may be sufficient for low‑frequency updates.
Typical applications for SSE include live stock tickers, real‑time news, GitHub/Twitter activity walls, and server‑status monitors.
Resources: caniuse.com, HTML5 Rocks article on SSE, O’Reilly’s “HTML5 SSE Data Push Apps”.
Thank you for reading; feel free to share if you found this article useful.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architects Research Society
A daily treasure trove for architects, expanding your view and depth. We share enterprise, business, application, data, technology, and security architecture, discuss frameworks, planning, governance, standards, and implementation, and explore emerging styles such as microservices, event‑driven, micro‑frontend, big data, data warehousing, IoT, and AI architecture.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
