Every modern product eventually needs live data: a chat window, a price ticker, a build-progress bar, a notification that arrives the second something happens. Almost all of these features are built with one of three techniques — polling, Server-Sent Events (SSE), or WebSockets. They solve the same problem with very different trade-offs in complexity, cost, and capability, and picking the wrong one is a common source of pain: teams reach for WebSockets out of habit, then spend weeks fighting connection management for a feature that only ever pushes data in one direction. This guide explains how each model actually works, compares them head to head, shows working Node.js code for the two streaming options, and ends with a practical decision guide.
1. The Three Models, Explained Plainly
Polling is the simplest model: the client asks, the server answers. In short polling, the browser sends an ordinary HTTP request every few seconds — "anything new?" — and the server responds immediately with whatever it has, even if that is "nothing yet". Long polling improves on this: the server holds the request open until new data is available (or a timeout approaches), answers, and the client immediately asks again. Polling needs no special infrastructure and is stateless on the server between requests. Its cost is waste: most requests return nothing, every request pays full HTTP overhead, and freshness is limited by the interval you can afford.
Server-Sent Events reverse the flow. The client opens one ordinary HTTP request, and the server keeps the response open indefinitely, writing small text messages into it whenever something happens. The wire format is deliberately simple — lines of data: fields separated by blank lines — and the browser’s built-in EventSource API handles parsing, plus automatic reconnection with a server-controlled retry delay. SSE is strictly one-way: server to client. Anything the client needs to say still travels through normal HTTP requests. In exchange you get a persistent, low-latency push channel that rides on plain HTTP and passes through standard load balancers far more easily than a custom protocol.
WebSockets are the heavyweight option. The connection begins as an HTTP request with an Upgrade header; if the server agrees, the socket switches protocols and becomes a persistent, full-duplex channel: either side can send a message at any moment, with framing overhead as low as two bytes per message. That makes WebSockets the only one of the three designed for genuinely two-way, high-frequency traffic — chat, collaborative editing, multiplayer games, live cursors. The price is state: the server must hold every connection open, track it, detect when it silently dies, and reach a specific client when the app runs on more than one machine.
2. Side-by-Side Comparison
The differences that actually matter in production, at a glance:
| Feature | Polling | SSE | WebSockets |
|---|---|---|---|
| Direction | Client asks, server answers | Server → client only | Both directions, any time |
| Transport | Plain HTTP requests | One long-lived HTTP response | HTTP upgrade, then framed protocol |
| Browser API | fetch + timer | EventSource (built in) | WebSocket (built in) |
| Reconnection | Manual, trivial | Automatic, server-controlled retry | Manual — you build it |
| Scaling cost | Stateless, but request-heavy | One open response per client | One stateful connection per client |
| Best for | Occasional status checks | One-way live streams | Interactive two-way features |
3. Server-Sent Events in Practice
Here is a complete SSE endpoint in Express. The server sets three headers, writes a retry hint, then pushes a JSON event every two seconds. Cleanup on disconnect is essential — without it, a timer leaks for every visitor who closes the tab.
// server.js — Server-Sent Events with Express
const express = require("express");
const app = express();
app.get("/events", (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
res.write("retry: 3000\n\n"); // how fast the client should reconnect
const timer = setInterval(() => {
const payload = JSON.stringify({ time: new Date().toISOString() });
res.write(`data: ${payload}\n\n`);
}, 2000);
req.on("close", () => clearInterval(timer)); // never leak timers
});
app.listen(3000, () => console.log("SSE server on http://localhost:3000"));The browser side needs no library at all:
const source = new EventSource("/events");
source.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Server time:", data.time);
};
source.onerror = () => {
console.log("Connection dropped — EventSource retries on its own");
};Two details matter. First, every message must end with a blank line (\n\n) or the browser will buffer it silently instead of delivering it. Second, if you run this behind nginx, disable response buffering for the route (proxy_buffering off), or events will arrive in delayed batches instead of as a stream.
4. WebSockets in Practice
A minimal broadcast server with the ws package is barely longer — the real difference is that the server now owns the entire connection lifecycle:
// server.js — WebSocket server with the ws package
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (socket) => {
console.log("Client connected");
socket.send(JSON.stringify({ type: "welcome", message: "Connected" }));
socket.on("message", (data) => {
// Broadcast every message to all other clients (chat-style)
const text = data.toString();
for (const client of wss.clients) {
if (client !== socket && client.readyState === 1) { // 1 = OPEN
client.send(text);
}
}
});
socket.on("close", () => console.log("Client disconnected"));
});
console.log("WebSocket server on ws://localhost:8080");And the matching browser client:
const socket = new WebSocket("ws://localhost:8080");
socket.addEventListener("open", () => {
socket.send("Hello from the browser");
});
socket.addEventListener("message", (event) => {
console.log("Received:", event.data);
});Notice what this code does not do: reconnect. If the socket drops, the browser fires close and stays silent until your code opens a new connection — production clients need a reconnect loop with backoff, plus a heartbeat, which the next sections cover.
5. The Decision Guide
Start from the direction of your data, not from fashion. Choose WebSockets when the client must talk as much as it listens: chat, presence indicators, collaborative documents, multiplayer state, live cursors. If messages flow both ways many times per session, nothing else fits. Choose SSE when the server talks and the client mostly listens: live news and sports feeds, notification streams, build and deployment progress, queue positions — and the pattern of the moment, streaming LLM tokens to the browser as they are generated. SSE gives you push latency with HTTP simplicity, automatic reconnection, and authentication via the cookies the browser already sends. Choose polling when updates are rare, cheap, or tolerant of delay: an order-status page checked a few times a minute, a dashboard refreshed every thirty seconds, a "is it ready yet?" job check. Polling’s statelessness is a genuine feature — it scales by simply adding servers, and it can never leak a connection.
6. Scaling and Operations
Open connections change how you operate. A polling API scales horizontally for free; a room full of WebSocket or SSE connections lives on specific machines, and that creates three problems. Routing: if a user must receive events triggered by requests landing on other servers, in-memory broadcast stops working. The standard fix is a pub/sub backplane — each server publishes events to Redis (or NATS, or Kafka), and every server forwards the events its connected clients care about. Sticky sessions can delay this need, but not remove it. Liveness: connections die silently — laptops close, networks switch, NAT mappings expire. WebSocket servers should send protocol ping frames on an interval and terminate sockets that miss pongs; SSE servers should write a comment line (: heartbeat) periodically, which also keeps proxies from closing "idle" streams. Limits: every open connection consumes a file descriptor and memory, and intermediaries impose their own rules — load-balancer idle timeouts, proxy connection caps, per-IP limits. Load-test with realistic connection counts, and set your heartbeat interval comfortably below the shortest timeout in the path.
Common Mistakes to Avoid
Using WebSockets for one-way data. If the client never sends anything but "hello", you have taken on stateful connections, custom reconnection, and harder load balancing to get what SSE gives you for free. No heartbeat. Without pings, dead connections linger in your server’s memory, your "online users" count becomes fiction, and messages sent into a dead socket vanish silently. Polling too aggressively. A one-second interval from thousands of clients is a self-inflicted denial-of-service attack on your own API — and on your users’ batteries. Match the interval to how fast the data can actually change. Forgetting proxy timeouts for SSE. Default nginx and cloud load-balancer settings close idle connections quickly; without heartbeats and buffering disabled, your "real-time" stream reconnects in a loop and events arrive in clumps.
Frequently Asked Questions (FAQ)
Q: Do WebSockets replace HTTP?
No. WebSockets handle the live, conversational part of an application; HTTP remains the right tool for everything request-shaped: page loads, REST APIs, uploads, caching, and content. Most real-time applications use both — HTTP for data and actions, WebSockets or SSE for the stream of updates about that data.
Q: Is SSE supported in all browsers — and can EventSource send POST requests?
EventSource is supported in all modern browsers, but it only makes GET requests and cannot set custom headers, which shapes how you authenticate: cookies work naturally, token-in-header designs do not. If you need POST or headers, use a fetch-based streaming client instead — you keep the same server format, but you give up the built-in reconnection and must handle retries yourself.
Q: How many concurrent WebSocket connections can one Node.js server hold?
There is no single number: the limit is memory and file descriptors, not CPU, because idle connections do almost no work. A tuned Node.js process can hold tens of thousands of mostly-idle connections; the real constraints are the per-connection memory of your own application state, operating-system descriptor limits, and whatever your load balancer permits. Measure with your actual message sizes and fan-out, and scale out with a pub/sub backplane before you reach the ceiling.
Conclusion
Real-time is a spectrum, not a single technology. Polling is simple and stateless but chatty; SSE is the underrated middle — one-way push over plain HTTP with reconnection built in; WebSockets are the full-power option for two-way interaction, paid for with state and operational care. Match the tool to the direction and frequency of your data, add heartbeats and a backplane when connections multiply, and your live features will stay boring in the best possible way.
💡 Engineering Key Takeaway
Start with the simplest model that fits your data flow — polling, then SSE — and adopt WebSockets when the client genuinely needs to talk back. Every step up in power is a step up in operational cost.