Polling, SSE and WebSocket
Six messages happen on the server over ten seconds, and there are four ways to get them to the page. See how late each way delivers them and how many requests it takes.
What you'll take away
- Work out how late polling delivers a message, and why most polls come back empty
- Pick SSE, a WebSocket or plain polling by who talks and how late it may arrive
- Resume a dropped SSE stream from
Last-Event-IDby giving every event anid - Know what open connections cost, down to everyone reconnecting after a deploy
The 1-minute version
Tap a point and the picture below plays that step.
The same six messages every time; 50 ms one way: the model's numbers. Gold on the server's roof is a message still waiting; teal on the page's roof, one that has arrived
A page shows share prices the server keeps sending; the page never sends anything back. Which way fits, most simply?
The picture: the page is the low house at the near end of the street, the server the tower at the far end. A blue light is a request walking up; a teal one is an answer or a message coming down (amber when it carries nothing). Gold slabs on the server's roof are messages still waiting; teal slabs on the page's roof are the ones that arrived, six places for six messages. A request waiting at the server's door is long polling; a lit line along the street is an open stream (SSE), two lines a WebSocket. A model (50 ms one way), not a real network.
Compare them all: Live updates to the browser
Six messages happen on the server at the same moments in every tile, two of them almost together. See how late each way gets them to the page, and how many requests it takes.
Use it when Things that change rarely and can be seconds late, like a long job's status. The simplest; works through any proxy
Skip it when Anything that must be quick: up to a whole interval late, and most answers are empty, so requests are wasted
A model: 50 ms one way, polling every 2 s, no time counted for opening new connections. Press any tile to see it large above, with when it fits.
Which one?
| Polling | Long polling | SSE | WebSocket | |
|---|---|---|---|---|
| How late | Up to an interval | About a trip | A trip | A trip |
| Requests | One per interval | One per delivery | One, kept open | One, upgraded |
| Direction | Page asks | Page asks | Server to page | Both ways |
| Reconnects | Nothing to do | Ask again | By itself | Your code |
Start with the direction
If only the server talks (notifications, say), SSE is plain HTTP that reconnects by itself. If both sides talk often (chat, say), use a WebSocket. If it can be seconds late, polling is simple and passes every proxy.
Open connections aren't free
Everyone with the page open holds a connection, so the server has to handle many at once, the load balancer must allow long ones, and a deploy drops them all at the same moment. Plan for everyone reconnecting together.
In real code
// Server-Sent Events, both ends for real on 127.0.0.1: one request, one response that stays open, and the server
// writing each event as it happens (text/event-stream: "id:" and "data:" lines, a blank line after each). The client
// reads the stream as it arrives, as the browser's EventSource does. (Here the server ends it after the third event so
// the example finishes; a real feed stays open.)
// Run: node sse.ts (Node 23.6+; on Node 22: node --experimental-strip-types sse.ts)
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
const messages = ["order 1001 paid", "order 1001 packed", "order 1001 shipped"];
let requests = 0;
const server = createServer((req, res) => {
requests++;
const from = Number(req.headers["last-event-id"] ?? 0); // a reconnecting browser says where it got to
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
messages.slice(from).forEach((m, i) => setTimeout(() => {
res.write(`id: ${from + i + 1}\ndata: ${m}\n\n`);
if (from + i + 1 === messages.length) res.end();
}, 20 * (i + 1)));
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/events`;
const got: string[] = [];
const res = await fetch(url, { headers: { accept: "text/event-stream" } });
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of res.body!) {
buffer += decoder.decode(chunk, { stream: true });
let end: number;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const event = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
got.push(event.split("\n").find((l) => l.startsWith("data: "))!.slice(6));
}
}
server.close();
assert.deepEqual(got, messages);
assert.equal(requests, 1);
console.log(`1 request, ${got.length} events pushed as they happened: ${got.join(" → ")}`);
node sse.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: 1 request, 3 events pushed as they happened: order 1001 paid → order 1001 packed → order 1001 shippedA real server on 127.0.0.1 answers one request with text/event-stream and writes each event as it happens; the client reads the stream as it arrives, as EventSource does, and a reconnect would resume from Last-Event-ID. It really runs.
Common questions
SSE or WebSocket: what's the difference?
SSE is one way, server to page, over plain HTTP (text/event-stream). It reconnects by itself with Last-Event-ID, but it's text only. A WebSocket goes both ways and can carry binary, but reconnecting and the rest are up to your code.
How do I pick one, say for chat or for notifications?
Start with the direction. If only the server talks, like notifications: SSE. If both sides talk often, like chat: a WebSocket. If it can be seconds late, like the status of an export that takes minutes, polling is still fine: the simplest, and it passes every proxy.
How is long polling different from regular polling?
Polling asks every few seconds and gets an answer right away, empty or not. With long polling the server holds the request until there's something, answers, and the page asks again at once. Hardly any empty answers, but every message still costs a new request.
Can't I just poll more often?
It gets quicker, but almost every request comes back empty, and the server's load multiplies with everyone who has the page open. In the picture's ten seconds, polling every 2 s already sends 6 requests, and half come back empty.
How does a WebSocket connection start?
As a normal HTTP request with the header Upgrade: websocket. The server answers 101 Switching Protocols, and that same connection becomes a pipe both sides can send frames on at any time.
If an SSE connection drops, do I lose messages?
The browser reconnects by itself and sends Last-Event-ID to say which event it got last. If the server gives each event an id and keeps the recent ones, it can carry on from there. If it keeps nothing, whatever happened in the gap is gone.
What do lots of open connections cost?
Everyone with the page open holds one, so the server has to handle many at once, the load balancer must allow long connections, and a deploy drops everyone, who then all reconnect at the same moment. Plan for that moment.
Next lesson
TCP and UDPLevel: Intermediate
SSE and a WebSocket are each one long TCP connection; next, what TCP does when a piece goes missing, and why the rest waits for it.