Skip to content

WebSockets, server-sent events and polling

Four ways a server gets news to a browser: ask again on a timer, hold the request open, stream one long HTTP response, or upgrade to a two-way socket. Each trades latency, header cost and server state differently.

On this page

What it is

HTTP is a request and response protocol: the client asks, the server answers, and in the base model the server has no way to start a message toward a browser. Live features such as chat, notifications and progress bars need exactly that, and four techniques fill the gap: short polling, long polling, server-sent events (SSE) and WebSockets. They differ in who holds a connection open, which way messages flow, and how much the browser does for you when the connection drops.

Short polling is a timer: the client repeats an ordinary request, spacing the requests by the delay it can tolerate, and the server answers at once, often with nothing new. Long polling changes the server side: it holds the request and answers when an event arrives or a timeout passes, and the client typically sends the next request as soon as the answer lands, or after a short pause it can afford. RFC 6202 describes both, plus HTTP streaming, where the server keeps one response open and keeps appending to it. The known costs: each poll carries a full set of HTTP headers, a held request can be cut by a proxy that treats it as idle, and the server has to keep any event that arrives between one answer and the next request.

Server-sent events are HTTP streaming made standard. The browser's EventSource sends a GET; the server replies with Content-Type: text/event-stream and leaves the response open, writing events as text lines: data: for the payload, event: for a named type, id: to label the event, retry: to set the reconnect delay in milliseconds. Messages travel one way, server to client; anything the client wants to say goes as a separate HTTP request. When the connection drops, the browser waits the reconnect delay (about three seconds unless retry: said otherwise) and opens a new request with a Last-Event-ID header carrying the last id: it saw, so the server can replay what was missed. A reply that is not a 200 with text/event-stream stops the retries, which is how a server tells a client to go away.

http
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache

retry: 10000
id: 41
event: price
data: {"sym":"ACME","px":12.3}

id: 42
data: a message with no event name

A WebSocket begins as an HTTP request and then leaves HTTP behind. The browser sends a GET with Upgrade: websocket and a Sec-WebSocket-Key; a willing server answers 101 Switching Protocols with a Sec-WebSocket-Accept computed from that key. From then on the same TCP connection carries framed messages in both directions, text or binary, until one side sends a close frame or the network drops the connection. RFC 6455 designed it to run on ports 80 and 443 and to pass through HTTP proxies, and browsers generally insist on the secure wss:// form outside local development. The browser object gives you send(), close() and the open, message, error and close events, so reconnecting, resuming from the last message and heartbeats are code you write. The WebSocket interface also has no backpressure: when a server sends faster than the page can process, the page buffers until memory runs out, pegs the CPU, or both.

http
GET /live HTTP/1.1
Host: api.example.org
Origin: https://app.example.org
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

When to use it

Start from two questions: how often does the server have something to say, and does the client talk back often? A few updates an hour to a handful of clients: short polling with a plain GET is the right answer and the simplest to run. A one-way feed with frequent updates (notifications, live scores, a job's progress, tokens from a language model, see Streaming LLM tokens): SSE, because the browser handles reconnecting and reporting the last event id, and the servers stay ordinary HTTP. Frequent traffic in both directions with low delay (chat with typing indicators, collaborative editing, multiplayer games), or binary payloads: WebSocket, which the protocol's authors list those uses for. Long polling earns its place when you need pushed updates but an intermediary in the path times out or buffers a long response, so a stream will not stay open.

Whatever you pick beyond short polling, say what the open connection costs. It lives on one server, so a message for a user connected elsewhere has to be routed to that server, usually through a pub/sub layer behind the connection tier (see Routing messages between stateful servers). MDN's guide to writing WebSocket servers suggests a reverse proxy in front that handles cookies and authentication and hands the socket to a dedicated server, which keeps the stateful tier small and dumb. Long-lived connections often need heartbeats so an idle timeout doesn't cut them and dead peers get noticed, covered in Heartbeats and presence.

When not to

Don't reach for a WebSocket when messages flow one way. You take on reconnect and last-event-id code that EventSource already does for you (the server keeps and replays missed events either way), plus a protocol upgrade and a second protocol to operate, in exchange for client-to-server frames the feature does not use. SSE, or long polling where streaming is blocked, is the smaller tool.

Don't pick SSE when the client sends often or sends binary: the client's messages need their own HTTP requests upstream, and the event stream is UTF-8 text. Watch the connection count too. MDN warns that over HTTP/1.1 browsers cap open connections per origin at a small number, six in most browsers, counted across tabs, so a page with several EventSource objects or a user with several tabs can lock itself out; over HTTP/2 the streams share one connection and the limit is negotiated with the server, 100 by default.

Don't hold connections open when updates are rare and clients few. A status page that changes a few times an hour is served well by a GET twice a minute: it is stateless, it works behind caches, and there is no long-lived response for a proxy or platform timeout to cut. RFC 6202's authors note that long polling and streaming both stretch HTTP past what it was designed for; pay that price when the latency you gain is worth it.

Compared

MechanismDirectionLatency and costWhen the connection dropsRight choice when

Short polling

Client asks, server answers at once

Delay up to the poll interval; a full request per poll, with or without new data

The next poll runs on schedule; polling current state needs nothing more, while an event feed needs a cursor

Updates are rare, clients are few, or the hosting won't hold a request open

Long polling

Client asks, server answers when it has news

Near-immediate once connected; a full request per answer (events can be batched), and a gap between answer and next ask

The client asks again; events in the gap need a server-side buffer

You need push through a path that cuts long responses or lacks WebSocket support

Server-sent events

Server to client over one open response

Immediate; one request, then text events with tiny framing

The browser reconnects after a delay and sends Last-Event-ID so the server can replay

One-way text feeds: notifications, tickers, progress, token streams

WebSocket

Both ways over one connection

Immediate; small frames, text or binary

Your code reconnects and works out what was missed

Frequent two-way traffic or binary data: chat, games, collaborative editing

In a picture

yesnoyesnonoyesUpdates rare?Poll on a timerTwo-waytraffic?WebSocketStreamingblocked?Server-senteventsLong polling
Three questions pick the transport: how often, which direction, and whether the path will keep a response open.

How to say it in an interview

The common mistake

Quiz

A dashboard shows a deploy's progress, and the browser sends nothing back while it runs. Which transport is the smallest fit?
An EventSource connection drops because of a network error. What happens next with no extra code from you?
Why does a WebSocket tier complicate horizontal scaling more than a polled endpoint does?
What does long polling change compared with short polling?

Questions that use this

Hear it in

Related

Sources

  1. RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP
  2. RFC 6455: The WebSocket Protocol
  3. MDN: Using server-sent events
  4. MDN: EventSource
  5. HTML Living Standard: Server-sent events
  6. web.dev: Stream updates with server-sent events
  7. MDN: The WebSocket API (WebSockets)
  8. MDN: Writing WebSocket servers
  9. MDN: WebSocket
Sign in to report a mistake