Module 6 / Live updates / Long polling and server-sent events

Lesson8 minModule 6 · lesson 2 of 9

Long polling and server-sent events

Waiting on the server instead of asking again.

Plain polling wastes requests on empty answers. The idea behind long polling is to let the server hold the request open instead of answering immediately. The client asks 'anything new since version 41?'. If there is nothing, the server waits, up to say 30 seconds, and answers the moment something appears. The client then asks again right away. Updates arrive nearly instantly, and quiet periods cost one request per 30 seconds instead of one per 5.

Server-sent events (SSE) go further: the client makes one request, and the server keeps the response open and writes a stream of small messages into it over time. The browser provides an EventSource API that reconnects automatically and sends the id of the last event it saw, so the server can resume where it left off. SSE is one-directional, server to client, over ordinary HTTP.

PollingLong pollingServer-sent eventsServerask, answer,repeatask, wait,answerask once,stream forever
Three ways to get updates over HTTP.
// Browser side of SSE
const stream = new EventSource("/orders/812/events");
stream.addEventListener("status", (e) => {
  render(JSON.parse(e.data));
});
// On reconnect the browser sends Last-Event-ID automatically,
// so the server can replay anything missed.
SSE client: reconnect and resume are built in.

Which should you choose? Long polling works almost everywhere, even with awkward proxies, but each update costs a full request-response cycle, and the server must hold many waiting requests. SSE is simpler and lighter for one-way feeds such as order status, notifications or live scores. If the browser also needs to send frequent messages upward (typing indicators, game input), a bidirectional channel like WebSockets is a better fit, covered next.

Question 1

A feed only pushes order status updates to the browser, and the browser never sends anything back after the first request. Which fits best?

Question 2

Why send periodic heartbeat lines on an idle SSE stream?

Your turn

Compare long polling and SSE for a live match score page with 200,000 viewers. Name one advantage of each and pick one.

Stuck? Think about requests per update and about reconnection.

What to remember

  1. Long polling holds a request open until there is news.

  2. SSE keeps one response open and streams events one way, with automatic resume.

  3. Both rely on held connections, so heartbeats and timeouts matter.

  4. Use SSE for one-way feeds, WebSockets when the client also talks a lot.