← Back to JavaScript, page 10

javascript-0193 · Medium mid

How do polling, long polling, Server-Sent Events, and WebSockets differ, and how do you choose between them?

Polling asks repeatedly on a timer, long polling holds each request open until data exists, Server-Sent Events keep one HTTP response open for one-way server messages with automatic reconnect, and WebSockets open a two-way channel after an HTTP upgrade. Choose the simplest one that meets the direction, latency, and scale needs: SSE for server pushes, WebSockets for two-way low latency.

Full answer

All four move updates from a server to a page. They differ in direction, cost, and complexity.

  1. Polling: setInterval plus fetch. Easy, works everywhere, and cacheable. Cost: wasted requests when nothing changed, and latency up to the interval. Use it when updates are rare or data is slow to change, with backoff and a pause when the tab is hidden.
  2. Long polling: the server holds the request until data is ready or a timeout, then the client immediately asks again. Latency is low and it works through old proxies, but each message costs a full request, and servers need to hold many open connections.
  3. Server-Sent Events (SSE): one long HTTP response with Content-Type: text/event-stream. The browser EventSource parses data: lines, reconnects automatically, and sends Last-Event-ID so the server can resume. It is one-way (server to client), text only, works over HTTP/2 multiplexing, and has a limit of six connections per host over HTTP/1.1. It cannot set custom headers with EventSource, so authentication usually uses cookies or fetch streaming instead.
  4. WebSockets: an HTTP request upgrades to a persistent two-way connection with small frames, text and binary. It gives the lowest latency for chat, games, and collaborative editing. You must handle reconnects, heartbeats (ping and pong), backpressure, authentication at connect time, and scaling (sticky routing or a pub/sub layer between servers). Some proxies and corporate networks interfere.

Choosing:

  • Server pushes only (notifications, live scores, progress): SSE is usually the simplest.
  • Two-way and frequent (chat, multiplayer, cursors): WebSockets.
  • Rare updates or simple infrastructure: polling.
  • Restricted network and low volume: long polling.

Questions to decide: who sends, how often, message size, how many connections, delivery guarantees (all four need ids and replay if messages must not be lost), and mobile battery cost. Always add a reconnect strategy with exponential backoff and jitter, and send a state snapshot after reconnecting.

javascript
const http = require('node:http');

const subscribers = new Set();
const history = [];
const waiting = [];
let connections = 0;
let longPollRequests = 0;

const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');
  if (url.pathname === '/poll') {
    const since = Number(url.searchParams.get('since') ?? 0);
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(history.filter((e) => e.id > since)));
  } else if (url.pathname === '/long-poll') {
    longPollRequests++;
    const since = Number(url.searchParams.get('since') ?? 0);
    const ready = history.filter((e) => e.id > since);
    if (ready.length) return res.end(JSON.stringify(ready));
    waiting.push({ since, res });
  } else if (url.pathname === '/events') {
    connections++;
    res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
    const lastId = Number(req.headers['last-event-id'] ?? 0);
    history.filter((e) => e.id > lastId).forEach((e) => res.write(`id: ${e.id}\ndata: ${e.text}\n\n`));
    subscribers.add(res);
    req.on('close', () => subscribers.delete(res));
  } else {
    res.statusCode = 404;
    res.end();
  }
});

function publish(text) {
  const event = { id: history.length + 1, text };
  history.push(event);
  subscribers.forEach((res) => res.write(`id: ${event.id}\ndata: ${event.text}\n\n`));
  waiting.splice(0).forEach(({ res }) => res.end(JSON.stringify([event])));
}

async function readSse(base, headers, wanted) {
  const controller = new AbortController();
  const response = await fetch(base + '/events', { headers, signal: controller.signal });
  const decoder = new TextDecoder();
  const messages = [];
  let buffer = '';
  for await (const chunk of response.body) {
    buffer += decoder.decode(chunk, { stream: true });
    let end;
    while ((end = buffer.indexOf('\n\n')) !== -1) {
      const block = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      messages.push(Object.fromEntries(block.split('\n').map((line) => line.split(/: (.*)/s).slice(0, 2))));
    }
    if (messages.length >= wanted) break;
  }
  controller.abort();
  return messages;
}

server.listen(0, '127.0.0.1', async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const getJson = async (path) => (await fetch(base + path)).json();

  console.log('poll, nothing yet:', await getJson('/poll?since=0'));
  publish('one');
  console.log('poll after an event:', await getJson('/poll?since=0'));

  const pending = getJson('/long-poll?since=1');
  await new Promise((resolve) => setTimeout(resolve, 20));
  publish('two');
  console.log('long poll answers when data exists:', await pending, '| requests used:', longPollRequests);

  const live = readSse(base, {}, 3);
  await new Promise((resolve) => setTimeout(resolve, 30));
  publish('three');
  console.log('sse, one connection, replay plus live:', await live, '| connections:', connections);

  console.log('sse resume with Last-Event-ID 2:', await readSse(base, { 'Last-Event-ID': '2' }, 1), '| connections:', connections);
  console.log('raw wire format:', JSON.stringify('id: 3\ndata: three\n\n'));

  server.closeAllConnections();
  server.close();
});

Run with Node.js v24.22.1 as js-193.js; two runs gave identical output. Output: poll, nothing yet: [] poll after an event: [ { id: 1, text: 'one' } ] long poll answers when data exists: [ { id: 2, text: 'two' } ] | requests used: 1 sse, one connection, replay plus live: [ { id: '1', data: 'one' }, { id: '2', data: 'two' }, { id: '3', data: 'three' } ] | connections: 1 sse resume with Last-Event-ID 2: [ { id: '3', data: 'three' } ] | connections: 2 raw wire format: "id: 3\ndata: three\n\n"

Key points

  • Polling is simple but wasteful; long polling cuts latency but costs a request per message.
  • SSE is a one-way text stream with automatic reconnect and Last-Event-ID resume.
  • WebSockets are two-way and low latency but need heartbeats, reconnect logic, and scaling work.
  • Choose by direction, frequency, scale, and network limits.
  • Use ids, replay, backoff with jitter, and snapshots for reliability.

Common mistakes

  • Polling at a short fixed interval from many clients.
  • Using WebSockets for one-way notifications that SSE would handle.
  • No reconnect with backoff, heartbeats, or replay of missed messages.
  • Forgetting that open connections count against server and browser limits.

Follow-ups

  • How do you scale WebSocket servers across machines?
  • How do you authenticate an EventSource connection?
  • What happens to messages sent while a client is offline?

Tips

  • Start with direction and frequency of messages.
  • Name SSE as the often forgotten simple option.
  • Mention reconnect, ids, and replay for all four.