Mrs. Rini's board from the last lesson still asks the server every 30 seconds, so its news is 15 seconds late on average. There are four ways to keep the board up to date. They differ in who speaks, how many connections they use, and what happens when the network drops. In this story, Mrs. Rini is the browser and Eko is the server:
- Short polling: Mrs. Rini walks to the back every 30 seconds and asks.
- Long polling: Mrs. Rini asks, and Eko holds his answer until something changes (or until 30 seconds pass). As soon as she gets the answer, Mrs. Rini asks again.
- SSE (Server-Sent Events): Eko has a loudspeaker to the front counter. Eko can talk, Mrs. Rini can only listen.
- WebSocket: like a phone line that stays connected. Both can talk at any time.
Short polling
This is the polling from the last lesson, with a request every 30 seconds:
setInterval(async () => {
const res = await fetch('/board') // ask every 30 seconds
document.querySelector('#board').innerHTML = await res.text()
}, 30000)
Its main weakness: wasted requests. The browser keeps asking even when there is no new data. One tab sends 120 requests per hour. If the hour holds only 6 changes, 114 requests come back with the same board. Every request also carries full headers: in the last lesson one question measured 1,023 bytes, while the news was a single word. The wait can be anything from almost 0 to one whole interval, half of it on average (15 seconds).
Long polling
With long polling, the browser asks /board/wait again and again: for (;;) is a loop with no end.
async function waitForNews() {
for (;;) {
try {
const res = await fetch('/board/wait') // the server holds the answer up to 30 seconds
if (!res.ok) throw new Error(`HTTP ${res.status}`) // 500, 502, 503, 429: pause in catch too
if (res.status === 200) show(await res.text())
// 204: 30 seconds passed with no news, ask again right away
} catch {
await new Promise((r) => setTimeout(r, 3000)) // the network dropped or the server failed: pause first
}
}
}
waitForNews()
- The server does not answer right away. It holds the request until something changes, and at that moment it answers with status
200and the board. If 30 seconds pass with no news, the server answers204 No Content(it worked, with no content). Then the loop asks again right away. - The wait is down to one network trip, because the answer goes out as soon as the change happens.
- But every piece of news is still one full HTTP request. Even when nothing happens, there is still one request every 30 seconds.
- The 3-second pause in
catchmatters. Without that pause, when the server is down, the loop sends requests without end. Butfetchonly goes tocatchwhen no answer comes at all (the network dropped or the server is down). A failed answer like502,503,500or429still counts as a normal finish. So the lineif (!res.ok) throwsends those answers tocatchtoo. Tested in Node 24 against a server that always answers502: without that line, 11,850 requests in 1 second. With it, 4 requests in 10 seconds.
Server-Sent Events (SSE)
With SSE, the browser opens the connection with EventSource, the browser's built-in tool for SSE. The function in addEventListener('status', ...) runs for each piece of news named status:
const source = new EventSource('http://localhost:3000/board/stream')
source.addEventListener('status', (event) => {
const { id, status } = JSON.parse(event.data)
document.querySelector(`#status-${id}`).textContent = status
})
SSE is one HTTP response that never finishes: the server keeps writing news into it. It goes only from the server to the browser. When it drops, the browser reconnects by itself (measured: Chromium 147 and Safari wait 3 seconds, Firefox 146 waits 5 seconds). The content is text. The details are in the Server-Sent Events lesson.
WebSocket
With WebSocket, new WebSocket(...) opens the connection. The function in ws.onmessage runs each time a message arrives. ws.send sends a message, here when ironButton (the Ironing button on Eko's tablet) is pressed:
const ws = new WebSocket('ws://localhost:3000/board')
ws.onmessage = (event) => {
const { id, status } = JSON.parse(event.data)
document.querySelector(`#status-${id}`).textContent = status
}
ironButton.onclick = () => ws.send(JSON.stringify({ type: 'status', id: 12, status: 'Ironing' }))
One connection, both ways: Eko's tablet can send over the same connection it receives on. Each message is wrapped in a frame (a small wrapper) with a header of only 2 to 14 bytes, not HTTP headers. When it drops, the browser does not reconnect by itself: you write that code. The server also has to understand the WebSocket protocol (its rules for sending messages). The details are in the WebSocket Fundamentals lesson.
Compared in numbers
This table counts one tab for one hour, with 6 status changes. All sizes were measured in Chromium 147 against a local server with no cookies (the board on port 8000, the realtime server on port 3000). The Lab on this page calculates this table again for the number of changes and tabs you pick.
| Short polling 30 s | Long polling, held 30 s | SSE | WebSocket | |
|---|---|---|---|---|
| Direction | the browser asks | the browser asks, the server holds | server to browser | both ways |
| Requests per hour | 120 | 120 | 1 | 1 |
| Bytes per hour | 122,760 | 90,042 | 1,209 | 904 |
| Average wait | 15 s | 1 network trip | 1 network trip | 1 network trip |
| When it drops | the next request just runs | your loop retries | automatic | write it yourself |
| HTTP/1.1 connection slot | used briefly | 1 slot all the time | 1 slot all the time | uses no slot |
- Long polling: 120 requests of 625 bytes each, 114 empty
204answers (only a 111-byte header), and 6 answers with the board. - SSE: a 578-byte request and a 241-byte response header, paid only once. After that, 65 bytes per update.
- WebSocket: a 487-byte handshake (the opening request that asks for a WebSocket connection) and its 129-byte reply, paid only once. After that, 48 bytes per update.
The limit of 6 connections per domain
Guess first: Mrs. Rini opens the board in 7 Chrome tabs, and each tab uses SSE to a server that still uses HTTP/1.1. Does the seventh tab keep getting news, show an error, or hang waiting?
HTTP/1.1 and HTTP/2 are two versions of HTTP. HTTP/2 is the newer one. Over HTTP/1.1 a browser opens only 6 connections at a time to one domain (the server's name in the address, for example localhost), and all tabs share that limit. Think of 6 slots (places): each connection takes one slot, as in the last row of the table. SSE and long polling each hold one slot all the time. Tested in Chromium 147, Firefox 146 and WebKit 26.4 (Safari's engine): with 6 SSE connections open, a seventh request to the same domain was still waiting after 2 seconds. So the seventh tab hangs waiting, with no error, and ordinary requests to that domain wait in the queue too.
Over HTTP/2, all requests to one domain share one connection. Inside that connection, each request travels as a separate stream (a lane). The server sets the limit on streams, usually 100 (the minimum that RFC 9113, the HTTP/2 standard, recommends). So SSE over HTTP/2 is safe for many tabs. WebSocket does not use those 6 slots: in all three browsers, 10 WebSockets opened at the same time and ordinary requests still went through.
Proxies need care too. nginx is a widely used proxy. With its default settings, it does two things that get in the way of SSE:
- nginx closes a connection that stays quiet for 60 seconds (the
proxy_read_timeoutsetting). So the server needs to send small messages at regular times. - nginx collects a response before it passes it on to the browser (buffering). So SSE needs an
X-Accel-Buffering: noheader, which makes nginx pass on each update right away.
WebSocket needs a proxy that passes on the Upgrade and Connection headers, two headers the WebSocket handshake uses.
One more: WebTransport
WebTransport runs on HTTP/3 (the newest version of HTTP, which uses QUIC). WebTransport opens many streams at the same time, and it can send datagrams: small packets that may get lost on the way, which suits games. According to MDN browser-compat-data 8.1.5, support is: Chrome and Edge since version 97, Firefox since 114, Safari since 26.4. Servers and libraries are still few, so this track stays with WebSocket.
How to choose
- Data only flows from the server to the browser (a board, notifications, live prices): SSE. The simplest for one-way push, and reconnecting is built in.
- Both ways and often (chat, shared cursors, games): WebSocket.
- Rarely changes, may be half an interval late: short polling.
- Push is needed but you cannot run a realtime server (hosting that only serves ordinary requests): long polling. Its hold time must be under the proxy's timeout (60 seconds in nginx).
⚠️ What makes push fail quietly
- SSE in many tabs over HTTP/1.1. The seventh tab hangs with no error. Use HTTP/2, or one connection shared between tabs.
- Long polling with no pause on errors. When the server is down or answers
502, the loop fires requests thousands of times a second. - Thinking WebSocket reconnects by itself. Only SSE does it automatically. You reconnect a WebSocket yourself, on the
closeevent (when the connection closes). - A proxy that buffers or cuts. SSE updates that nginx collects arrive in bunches, and a connection quiet for 60 seconds gets cut. Turn buffering off and send small messages at regular times.
TL;DR: Short polling asks the server every N seconds, for example every 30 seconds. Its main weakness is wasted requests: 120 per hour per tab (122,760 bytes), while with 6 changes an hour, only 6 carry news. Its news is also half an interval late on average. Long polling makes the server hold the request until there is news: the delay is small, but each update is still a full HTTP request (90,042 bytes per hour). SSE (Server-Sent Events) is one response that keeps flowing from the server to the browser (1,209 bytes per hour), and the browser reconnects by itself when it drops. Pick SSE when data only flows in that direction. WebSocket is one two-way connection with small frames (the wrapper around each message): 904 bytes per hour, with no automatic reconnecting. Over HTTP/1.1 (the older version of HTTP) a browser opens only 6 connections to one domain (the server's name) for all its tabs, so the seventh SSE hangs. The newer HTTP/2 removes that limit. WebTransport, another option that runs on HTTP/3, is in Chrome 97, Firefox 114 and Safari 26.4, but it is still new.
⚡ Short polling vs long polling
Meaning: Short polling asks the server every 30 seconds. Its weakness is wasted requests: 120 requests per hour per tab, while, for example, the hour holds only 6 changes. On average its news is also half an interval late (half the time between two questions). Long polling asks too, but the server holds the request until something changes. So the wait is down to one network trip, but every piece of news is still one full HTTP request.
⚡ SSE: one way, reconnects by itself
Write:
const source = new EventSource('http://localhost:3000/board/stream')
source.addEventListener('status', (event) => {
const { id, status } = JSON.parse(event.data)
document.querySelector(`#status-${id}`).textContent = status
})
Meaning: SSE (Server-Sent Events) is one HTTP response that never finishes. EventSource opens the connection. The function in addEventListener('status', ...) runs each time the server sends a piece of news named status, and writes that status on the board. It flows only from the server to the browser, and when it drops the browser reconnects by itself. When data only flows in that direction, pick SSE.
⚡ WebSocket: both ways, small frames
Meaning: WebSocket is one connection that the browser and the server both use to send and receive. Each message is wrapped in a frame (a small wrapper) with a header of only 2 to 14 bytes. When it drops, the browser does not reconnect by itself: you write that code.
⚡ The limit of 6 connections per domain
Guess first: Mrs. Rini, who runs a laundry, opens its order board in 7 Chrome tabs. Each tab uses SSE to a server that still uses HTTP/1.1 (the older version of HTTP). Does the seventh tab keep getting news, show an error, or hang waiting?
It hangs waiting, with no error. Over HTTP/1.1 a browser opens only 6 connections at a time to one domain (the server's name in the address), shared by all tabs. Each SSE holds one connection all the time.
Meaning: Over HTTP/2 (the newer version), all requests to one domain share one connection, so that limit is gone. WebSocket does not use any of those 6 connections.