Live and Streamed Data: Polling, SSE, WebSockets and Streamed Fetch
Pick between polling, Server-Sent Events, WebSockets and a streamed fetch body for changing data, and handle reconnection and cancellation for each.
Contentsand lesson path
On this page
- The problem: data that changes while you watch
- Step 1: polling — the honest baseline
- Step 2: Server-Sent Events
- Step 3: WebSockets with backoff and jitter
- Step 4: reading a response as it streams
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Platform APIs & PWAs
- Where Browser Data Lives: Cookies, Storage, IndexedDB and Caches Concept · 20 min
- Off the Main Thread with Web Workers Worked example · 20 min
- Live and Streamed Data: Polling, SSE, WebSockets and Streamed Fetch Worked example · 25 min
- Installable and Offline: Service Workers, Manifests and the Limits of PWAs Concept · 25 min
- Lab: An Offline-First Notes App with Live Updates Lab · 30 min
- Check: Pick the Platform API for the Job Knowledge check · 8 questions
What you will learn
- Deliver live and streamed data to the UI with polling, Server-Sent Events, WebSockets or a streamed fetch body (for example LLM output relayed by your own server so API keys never reach the browser), justifying the choice and handling reconnection and cancellation.
Prerequisites: Async JavaScript & Fetch
01. The problem: data that changes while you watch
Everything so far assumed a request gets one complete answer. Watched data breaks that assumption: prices move, colleagues type, a language model writes its answer word by word. There are four ways to get changing data into a page, and they differ in direction, machinery and failure modes:
- Polling: the client asks again on a timer. Crude, but one fetch call, and it reuses everything HTTP gives you.
- Server-Sent Events (SSE): the server pushes messages down one long-lived HTTP response;
EventSourcereconnects by itself. - WebSockets: one connection, both directions, after an HTTP upgrade handshake. The most power and the most machinery.
- A streamed fetch body: the client reads one big or unbounded response as it arrives, chunk by chunk — how relayed model output reaches a UI.
This worked example drives all four against a small local server, watches what actually arrives, and breaks the connection on purpose to see who does the reconnecting. The lab then wires the winning combination into the notes app.
Here is that server, so you can reproduce every output below. It needs only Node 22 and no packages: one HTTP server answers the notes, events and token routes, and the same port accepts the WebSocket upgrade. The WebSocket part is deliberately minimal (short text frames only) so the whole handshake fits on screen; a real server would use a maintained library such as ws. Start it, open http://localhost:4310/, and paste each client snippet into the DevTools Console of that page, so that paths like /api/notes resolve to this server.
// demo-server.mjs: node demo-server.mjs, then open http://localhost:4310/
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const notes = ['Buy milk', 'Call Sam', 'Book dentist', 'Water plants'];
let polled = false;
const words = ['The', ' cache', ' is', ' not', ' the', ' store.'];
const server = createServer(async (req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end('<!doctype html><title>Live data</title><p>Use the console.');
}
if (req.url === '/api/notes') {
if (!polled) setTimeout(() => notes.push('Added elsewhere'), 600);
polled = true;
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(notes));
}
if (req.url === '/events') {
const last = Number(req.headers['last-event-id'] ?? 0); // sent on reconnect
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
});
res.write('retry: 1000\n\n');
if (last) res.write(`data: resuming after Last-Event-ID ${last}\n\n`);
for (let id = last + 1; id <= 6 && !res.destroyed; id += 1) {
res.write(`id: ${id}\nevent: tick\ndata: price ${100 + id}\n\n`);
if (id === 1) res.write('data: plain default event\n\n');
await sleep(500);
if (id === 3 && !last) return res.end(); // drop once, like a restart
}
return; // the response stays open until the page closes it
}
if (req.url === '/tokens' || req.url === '/slow-tokens') {
const pause = req.url === '/tokens' ? 100 : 200;
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
for (const word of words) {
if (res.destroyed) return; // the client aborted
res.write(word);
await sleep(pause);
}
return res.end();
}
res.writeHead(404).end();
});
// A minimal WebSocket endpoint, enough for this demo only: short text frames,
// no fragmentation. Real servers use a library such as `ws`.
const frame = (opcode, data) =>
Buffer.concat([Buffer.from([0x80 | opcode, data.length]), data]);
let t0;
server.on('upgrade', (req, socket) => {
if (req.url !== '/tick') return socket.destroy();
const accept = createHash('sha1')
.update(req.headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
.digest('base64');
socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n'
+ `Connection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
const send = (text) => socket.write(frame(0x1, Buffer.from(text)));
socket.on('data', (buf) => { // client frames are masked; echo text frames
if ((buf[0] & 0x0f) !== 0x1) return;
const mask = buf.subarray(2, 6);
const body = buf.subarray(6, 6 + (buf[1] & 0x7f)).map((b, i) => b ^ mask[i % 4]);
send('echo: ' + body.toString());
});
t0 ??= Date.now() - 100; // prices advance every 500 ms, even with no client
let ticks = 0;
const timer = setInterval(() => {
send(`price ${100 + Math.floor((Date.now() - t0) / 500)}`);
ticks += 1;
if (ticks < 3) return;
clearInterval(timer);
socket.end(frame(0x8, Buffer.alloc(0))); // a close frame, then hang up
}, 500);
socket.on('close', () => clearInterval(timer));
socket.on('error', () => clearInterval(timer));
});
server.listen(4310, () => console.log('demo server on http://localhost:4310'));node demo-server.mjsdemo server on http://localhost:431002. Step 1: polling — the honest baseline
async function poll(intervalMs, times) {
for (let i = 1; i <= times; i += 1) {
const res = await fetch('/api/notes');
if (!res.ok) throw new Error(`poll ${i}: HTTP ${res.status}`);
const notes = await res.json();
console.log(`poll ${i}: ${notes.length} notes`);
await new Promise((r) => setTimeout(r, intervalMs));
}
}
poll(1200, 4);poll 1: 4 notes
poll 2: 5 notes
poll 3: 5 notes
poll 4: 5 notesPolling caught the change one interval late and spent three of its four requests learning nothing. That trade — simplicity versus waste and latency — is the whole decision. For a dashboard refreshing every 30 s, polling is often the right answer. For chat or a token-by-token answer, it is not: the server ends up answering thousands of "anything new?" requests to deliver each real message seconds late.
03. Step 2: Server-Sent Events
SSE is a normal HTTP response whose body is meant to stay open. The server writes small text blocks, and the browser parses them into events. On the wire it looks like this:
retry: 1000
id: 1
event: tick
data: price 101
data: plain default event
id: 2
event: tick
data: price 102Each block ends with a blank line. data: carries the payload, event: names it (no line means the default message event), id: sets the last-event id the browser keeps and sends back as a Last-Event-ID header on reconnect — that is your hook for resuming where you left off — and retry: suggests a reconnect delay in milliseconds. The client side is one object:
const log = (label, value) => console.log(label + ': ' + value);
const states = ['CONNECTING', 'OPEN', 'CLOSED']; // readyState 0, 1, 2
const state = () => source.readyState + ' ' + states[source.readyState];
const source = new EventSource('/events');
source.onopen = () => log('open, readyState', state());
source.addEventListener('tick', (e) => log('tick ' + e.lastEventId, e.data));
source.onmessage = (e) => log('default event ' + e.lastEventId, e.data);
source.onerror = () => log('error, readyState', state());
setTimeout(() => {
source.close();
log('after close, readyState', state());
}, 4500);open, readyState: 1 OPEN
tick 1: price 101
default event 1: plain default event
tick 2: price 102
tick 3: price 103
error, readyState: 0 CONNECTING
open, readyState: 1 OPEN
default event 3: resuming after Last-Event-ID 3
tick 4: price 104
tick 5: price 105
tick 6: price 106
after close, readyState: 2 CLOSEDNamed events arrive like DOM events, and the browser owns reconnection. The demo server ended the first response after tick 3, as a restart would. EventSource reported an error with readyState 0 (CONNECTING), waited the retry delay, dialled again and sent Last-Event-ID: 3, so the server resumed at tick 4. Client code wrote none of that. The costs are equally clear: it is one-way (server to client; client messages go by separate fetches), and everything rides on intermediaries passing the response through unbuffered, which is why the server sends Content-Type: text/event-stream and Cache-Control: no-cache.
There is one more cost when the stream travels over HTTP/1.1, as it does from this node:http demo server. A browser opens at most about six HTTP/1.1 connections to one domain, and that pool is shared by every tab. Each open EventSource holds one connection for as long as it runs, so a user with several tabs of the app open can use up the pool, and ordinary fetches to the same domain then wait for a free connection. MDN warns about this limit on its SSE pages. Two fixes: serve the stream over HTTP/2 or HTTP/3, where many requests share one connection as separate streams and the stream limit is negotiated and much higher; or let only one tab hold the EventSource and pass its events to the other tabs, through a SharedWorker (one worker shared by all same-origin tabs) or a BroadcastChannel (a message channel between same-origin tabs).
One more cost shapes how you deploy SSE. Over HTTP/1.1, a browser opens at most about six connections at a time to one host, and every tab of your site shares that pool. Each open EventSource holds one of those connections for as long as it lives. Open the notes app in six tabs and the pool is full: a seventh feed, and ordinary fetch calls from any of the tabs, wait in a queue until a connection frees up. MDN's server-sent events guide warns about this, and Chrome and Firefox have closed the bug as "won't fix".
There are two ways out. Serve the feed over HTTP/2 or HTTP/3, where many requests share one connection as separate streams; browser and server agree on how many streams may run at once, usually 100 or more. Or keep one feed per browser instead of one per tab. A SharedWorker can own the EventSource and pass each event to every tab it serves. Or one tab can act as the leader: it holds the feed and re-posts each event on a BroadcastChannel that the other tabs listen to. The Web Locks API is a simple way to choose that leader: the tab that holds the lock owns the feed, and when it closes, a waiting tab gets the lock and opens the feed in its place.
04. Step 3: WebSockets with backoff and jitter
A WebSocket starts as an HTTP request asking to upgrade, then both sides speak frames over one socket — either can send at any time. That is what you need for typing indicators, collaborative editing or games, and it is more than most feeds need. What the browser does not give you is reconnection: when a WebSocket closes, it stays closed until your code dials again. The two rules are exponential backoff (double the wait each time, so a server outage is not met by a stampede) and jitter (randomness, so a thousand clients do not all land on the same millisecond). Watch the demo server close each connection about 1.5 s in, like a restart:
const log = (label, value) => console.log(label + ': ' + value);
function connect(attempt) {
const ws = new WebSocket('ws://localhost:4310/tick');
ws.onopen = () => { log('open attempt ' + attempt, 'connected');
ws.send('hello from page'); };
ws.onmessage = (e) => log('message', e.data);
ws.onclose = () => {
if (attempt >= 2) { log('gave up after', attempt + ' attempts'); return; }
const wait = Math.round(250 * 2 ** attempt + Math.random() * 250);
log('closed, reconnecting in', wait + ' ms (backoff + jitter)');
setTimeout(() => connect(attempt + 1), wait);
};
}
connect(1);open attempt 1: connected
message: echo: hello from page
message: price 101
message: price 102
message: price 103
closed, reconnecting in: 544 ms (backoff + jitter)
open attempt 2: connected
message: echo: hello from page
message: price 105
message: price 106
message: price 107
gave up after: 2 attemptsThe sequence number is the quiet lesson: the first connection ended at price 103 and the next began at price 105. A reconnected socket says nothing about what happened while it was down — the client must fetch what it missed (a "what changed since id N" call) or accept the gap. Real clients also cap the backoff, give up after some attempts and show a reconnection state, as the lab does.
05. Step 4: reading a response as it streams
The fourth shape is not about pushing updates at all: it is about not waiting for a whole body. res.body is a ReadableStream; a reader hands you each chunk the moment it arrives. This is exactly how a chat UI shows a model's answer growing. The server in the demo writes six words with a pause between each:
const log = (label, value) => console.log(label + ': ' + value);
const res = await fetch('/tokens');
log('status', res.status + ', streamed: ' + (res.body !== null));
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let text = '';
for (;;) {
const { done, value } = await reader.read();
if (done) { log('stream', 'done'); break; }
text += value;
log('chunk', JSON.stringify(value));
}
log('assembled', text);status: 200, streamed: true
chunk: "The"
chunk: " cache"
chunk: " is"
chunk: " not"
chunk: " the"
chunk: " store."
stream: done
assembled: The cache is not the store.Each read() resolved as soon as the server wrote, not when the response finished — that is the whole feature. For a model answer, the server route would hold the provider key, call the provider, and copy each token to this stream, because the key must never reach the browser (see calling a JSON API from code for the same rule applied to ordinary requests). The page renders text as it grows and reads chunks at whatever pace it can — reads left un-answered apply backpressure, slowing a sender that respects it.
Streams also need an exit. Cancellation is what AbortController is for; pass its signal to fetch and the stream errors instead of hanging:
const log = (label, value) => console.log(label + ': ' + value);
const controller = new AbortController();
const res = await fetch('/slow-tokens', { signal: controller.signal });
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
const first = await reader.read();
log('first chunk', JSON.stringify(first.value));
setTimeout(() => controller.abort(), 300);
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
log('chunk', value);
}
} catch (err) {
log('after abort, read() rejects with', err.name);
}
log('aborted fetch', controller.signal.aborted);first chunk: "The"
chunk: cache
after abort, read() rejects with: AbortError
aborted fetch: trueThe pending read() rejected with an AbortError, which unwinds the render loop cleanly — and the server saw its response closed, so a well-behaved relay can stop paying for upstream tokens. Cancellation and cleanup on unmount is the same story in React; safely fetching data and cancellation and races cover that side.
Shape Direction Reconnects Fits
Polling in n/a rare updates, tiny code
SSE in automatic, Last-Event-ID server push over plain HTTP
WebSocket in + out you write it bidirectional, low latency
Streamed fetch in you re-request one long answer, tokens
(cancel: AbortSignal)06. Check your understanding
07. Apply it
For the notes app in this skill's practice task, decide the live-updates design:
- Which channel carries "another session changed a note"? Justify it against the table above.
- Write the reconnection story for that channel: who reconnects, after how long, and how the client learns what it missed while disconnected.
- Sketch the streamed-fetch route for an optional "summarise my notes" button: what does your server hold, what does it relay, and what does the AbortController on the page do when the user clicks Stop?
Then prove the reconnection path with the server restarted mid-session, and note what your client shows while it cannot reach the feed.
08. Review prompt
Without looking back: what does an SSE event block look like on the wire, and which three fields did the demo use? Who reconnects an EventSource, and who reconnects a WebSocket? Why can a handful of open tabs stall an SSE app served over HTTP/1.1, and what are the two ways around it? What are the two ingredients of a polite WebSocket reconnection, and why is a resumed connection not enough by itself? Finally: how does a page read a streamed response chunk by chunk, and what exactly does controller.abort() do to a pending read()?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.