When to Use SSE vs WebSocket vs Polling: A Practical Guide with Code

This article explains the three main server‑to‑client push techniques—polling, WebSocket, and Server‑Sent Events—detailing their principles, advantages, drawbacks, browser compatibility, and appropriate use cases, and provides complete Node.js and HTML demos for implementing SSE.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
When to Use SSE vs WebSocket vs Polling: A Practical Guide with Code

Server Push Techniques Overview

In many web applications the server needs to push data to the client, such as real‑time dashboards, unread messages, or chat.

Common Solutions

Polling

WebSocket

Server‑Sent Events (SSE)

Polling

Polling is a pseudo‑push method where the client repeatedly sends HTTP requests to the server. It consumes resources because each request establishes a new HTTP connection, occupies browser concurrency slots, and cannot deliver data instantly.

Drawbacks of polling:

Continuous requests cause unnecessary handshake overhead.

Client must keep a request loop open, which is unfriendly to resources.

Browser limits concurrent connections per host (e.g., Chrome limits to 6).

Long‑polling intervals may lead to delayed data.

WebSocket

WebSocket provides a full‑duplex communication channel over a single TCP connection, allowing both client‑to‑server and server‑to‑client messages.

Its disadvantages are that it is a new protocol (ws/wss) and not all browsers support it out of the box. Compared with SSE it is heavier and more complex.

Browser compatibility:

WebSocket compatibility chart
WebSocket compatibility chart

Server‑Sent Events (SSE)

SSE is a one‑way, long‑living HTTP/HTTPS connection where the server can push data to the client. It cannot send data from client to server.

Advantages:

Lightweight protocol, lower client overhead than WebSocket.

Uses standard HTTP, so existing servers support it without extra configuration.

Built‑in reconnection and custom data types.

Note: Internet Explorer does not support SSE.

Browser compatibility:

SSE compatibility chart
SSE compatibility chart

Differences Between WebSocket and SSE

WebSocket is full‑duplex and more powerful but heavier; SSE is single‑direction, simpler, and easier to deploy. Choose SSE for one‑way push scenarios (dashboards, notifications). Choose WebSocket when bidirectional communication is required (chat).

SSE API Overview

var source = new EventSource(url);

Connection States

0 – CONNECTING

1 – OPEN

2 – CLOSED

Events

open – fired when the connection is established.

message – fired when a message is received.

error – fired on communication errors.

Response Headers

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

Demo: Implementing an SSE Link

Backend (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 SSE endpoint");
  setInterval(() => {
    const data = { message: `Current time is ${new Date().toLocaleTimeString()}` };
    res.write(`data: ${JSON.stringify(data)}

`);
  }, 1000);
});

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

Frontend (HTML)

<!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) {
      const li = document.createElement("li");
      li.innerHTML = data.message;
      return li;
    }
    let source = '';
    if (window.EventSource) {
      source = new EventSource('http://localhost:8088/sse');
    } else {
      throw new Error("Browser does not support SSE");
    }
    source.onopen = () => console.log("SSE connection opened");
    source.onmessage = (event) => {
      const li = createLi(JSON.parse(event.data));
      document.getElementById("ul").appendChild(li);
    };
    source.onerror = () => console.log("SSE connection error");
  </script>
</body>
</html>

Summary

SSE is lighter than WebSocket.

SSE works over HTTP/HTTPS, while WebSocket uses a separate ws/wss protocol.

Use SSE for one‑way server‑to‑client pushes such as dashboards or notifications.

Use WebSocket when bidirectional communication is needed, e.g., chat.

Both have good browser support except IE, which lacks SSE.

Polling should be avoided except as a fallback when neither SSE nor WebSocket is available.

backendfrontendNode.jsWebSocketExpressserver-sent-eventsPollingSSE
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

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.