When to Use SSE vs WebSocket vs Polling: A Practical Guide
This article explains the three main server‑to‑client push techniques—polling, WebSocket, and Server‑Sent Events (SSE)—detailing their principles, advantages, drawbacks, compatibility, typical use cases, and provides complete Node.js/Express and plain‑HTML demos to help developers choose the right solution.
In many development scenarios the server needs to push data to the client, such as real‑time dashboards, unread message notifications, or chat functions.
Implementation Schemes
The common ways to achieve server‑to‑client push are:
Polling
WebSocket
SSE
Polling Overview
Polling is a pseudo‑push technique where the client repeatedly sends HTTP requests to the server, which always initiates the request. It consumes extra connections, occupies browser concurrency limits, and cannot guarantee timely data delivery, making it the least desirable method.
Polling drawbacks:
Each request must go through the HTTP handshake (three‑way handshake, four‑way termination), causing unnecessary overhead.
The client must keep sending requests from page load onward, which is unfriendly to the browser.
Browser concurrency is limited (e.g., Chrome allows only six concurrent connections per domain), and a long‑running poll occupies one slot.
Long polling intervals may still miss timely data.
WebSocket Overview
WebSocket provides a full‑duplex communication channel, allowing both client and server to send messages. It is powerful but requires the ws/wss protocol, which not all browsers support, and its implementation is more complex.
SSE Overview
Server‑Sent Events (SSE) is a one‑way, long‑living HTTP/1.1 connection that lets the server push data to the browser. It is lightweight, uses the existing HTTP infrastructure, and is supported by most browsers except IE.
Differences Between WebSocket and SSE
WebSocket is full‑duplex; SSE is one‑way (server‑to‑client only).
WebSocket requires server support for the ws protocol; SSE works over standard HTTP.
SSE is a lightweight protocol with lower complexity; WebSocket is heavier.
SSE automatically reconnects on disconnection; WebSocket needs additional handling.
SSE can send custom data types.
Typical Business Scenarios
SSE is ideal for scenarios that only need server‑to‑client pushes, such as live dashboards or notification centers. WebSocket is preferred when bidirectional communication is required, e.g., chat applications.
SSE API and Demo
Key API properties: source.readyState: 0 = CONNECTING, 1 = OPEN, 2 = CLOSED.
Events: open (connection established), message (data received), error (communication error).
Data format must include:
Content-Type: text/event-stream // text response format
Cache-Control: no-cache // prevent caching
Connection: keep-alive // keep‑alive long connectionEstablishing an SSE connection (client)
var source = new EventSource(url);Backend Demo (Node.js + Express)
const express = require('express');
const app = express();
const port = 8088;
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.header('Access-Control-Allow-Credentials', true);
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.get('/sse', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
console.log('Entered long‑connection');
setInterval(() => {
const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
res.write(`data: ${JSON.stringify(data)}
`);
}, 1000);
});
app.listen(port, () => console.log(`Server started at http://localhost:${port}`));Frontend Demo (plain HTML)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSE Demo</title>
</head>
<body>
<ul id="ul"></ul>
<script>
if (window.EventSource) {
const source = new EventSource('http://localhost:8088/sse/');
source.onopen = () => console.log('Connection opened');
source.onmessage = e => {
const li = document.createElement('li');
li.innerHTML = JSON.parse(e.data).message;
document.getElementById('ul').appendChild(li);
};
source.onerror = () => console.log('Connection error');
} else {
throw new Error('Browser does not support SSE');
}
</script>
</body>
</html>Summary
SSE is lighter than WebSocket.
SSE works over HTTP/HTTPS.
WebSocket uses a new ws/wss protocol.
If only server‑to‑client push is needed, SSE is recommended.
If bidirectional communication is required, choose WebSocket.
Both have good browser compatibility, except IE does not support SSE.
Polling should be avoided because it consumes client resources.
Mini‑programs do not support SSE.
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
