Polling vs SSE vs WebSocket — Realtime

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…

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

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()

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

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:

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

⚠️ What makes push fail quietly

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.

What you will learn