Backend Development 13 min read

Server‑Sent Events (SSE) vs WebSocket vs Polling: Concepts, Use Cases, and Implementation Demo

This article explains the three common server‑to‑client push techniques—polling, WebSocket, and Server‑Sent Events—detailing their advantages, drawbacks, suitable business scenarios, and provides step‑by‑step demo code for both frontend and Node.js backend implementations.

Architect
Architect
Architect
Server‑Sent Events (SSE) vs WebSocket vs Polling: Concepts, Use Cases, and Implementation Demo

In everyday development we often encounter scenarios where the server must actively push data to the client, such as real‑time dashboards, unread‑message notifications, and chat functions.

The article introduces three typical solutions for these scenarios: long‑polling, WebSocket, and Server‑Sent Events (SSE), and compares their characteristics.

Polling

Polling is a pseudo‑push technique where the client repeatedly sends HTTP requests to the server; each request incurs the full HTTP handshake, consumes connection slots, and can be inefficient, especially when the server has little new data.

Drawbacks include unnecessary network overhead, constant client processing, limited browser concurrent connections, and delayed data delivery.

WebSocket

WebSocket provides a full‑duplex communication channel, allowing both client and server to send messages independently. It offers powerful functionality but requires a separate ws/wss protocol, which may not be supported by all browsers and adds complexity.

Compatibility varies across browsers, and the protocol is heavier than SSE.

Server‑Sent Events (SSE)

SSE is a one‑way, lightweight protocol built on top of HTTP/1.1 long‑living connections; the server can push data to the client, but the client cannot send messages back over the same channel.

Advantages include low overhead, use of standard HTTP (no extra server support needed), automatic reconnection, and lower client resource consumption. However, IE does not support SSE, and mini‑programs also lack support.

Comparison

WebSocket is full‑duplex and more feature‑rich; SSE is single‑direction and simpler.

WebSocket requires server‑side support for the ws protocol; SSE works with any HTTP server.

SSE is lighter and easier to deploy; WebSocket is heavier and more complex.

SSE includes built‑in reconnection; WebSocket needs custom handling.

SSE allows custom data types.

When to Use Which

Use SSE for scenarios that only need server‑to‑client push, such as real‑time dashboards or notification feeds.

Use WebSocket when bidirectional communication is required, e.g., chat applications.

Polling should be a last resort, only when both WebSocket and SSE are unavailable.

SSE API Overview

Creating an SSE connection:

var source = new EventSource(url);

Connection readyState values:

0 – CONNECTING (connection not yet established or disconnected)

1 – OPEN (connection established, data can be received)

2 – CLOSED (connection closed, no reconnection)

Key events:

open – triggered when the connection is opened

message – triggered when data arrives

error – triggered on communication errors

Typical response headers for SSE:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

Demo Implementation

The demo uses a plain HTML page on the frontend and a Node.js Express server on the backend.

Frontend Demo (HTML + JavaScript)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Demo</title>
</head>
<body>
    <ul id="ul"></ul>
<script>
function createLi(data) {
    let li = document.createElement("li");
    li.innerHTML = String(data.message);
    return li;
}
let source = '';
if (window.EventSource) {
    source = new EventSource('http://localhost:8088/sse/');
} else {
    throw new Error("Current browser does not support SSE");
}
source.onopen = function(event) {
    console.log('Connection opened');
};
source.onmessage = function(event) {
    let li = createLi(JSON.parse(event.data));
    document.getElementById('ul').appendChild(li);
};
source.onerror = function(event) {
    console.log('Connection error');
};
</script>
</html>

Backend Demo (Node.js + Express)

const express = require('express');
const app = express();
const port = 8088;

// Enable CORS
app.all('*', function(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 SSE connection');
    setInterval(() => {
        const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
        res.write(`data: ${JSON.stringify(data)}\n\n`);
    }, 1000);
});

app.listen(port, () => {
    console.log(`Server started at http://localhost:${port}`);
});

Conclusion

SSE is lighter than WebSocket and works over standard HTTP/HTTPS.

WebSocket offers full‑duplex communication for scenarios like chat.

Polling is the least efficient method and should be avoided when possible.

IE does not support SSE; mini‑programs also lack support.

backendfrontendNode.jsWebSocketExpresspollingSSE
Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.