WebSockets, Server-Sent Events or polling: choosing a real-time transport
"Real-time" covers very different needs: a dashboard that refreshes every few seconds, a notification that should appear promptly, a chat where both sides type, a model's answer streaming in word by word. WebSockets are often chosen by reflex for all of them. They are the most capable option and the most expensive to operate, and for many of these jobs something simpler does better.
Four ways to get fresh data to a browser
Polling
The client asks on a timer: "anything new?". It is plain HTTP, works through every proxy, is trivially cacheable and needs no special server. The costs are delay, on average half the interval, and waste, since most responses say "no". Polling is the right answer more often than its reputation suggests: for data that changes every few minutes, or when a few seconds of delay is acceptable, nothing else is as easy to run.
Long polling
The client asks, and the server holds the request open until it has something to say or a timeout passes. The client then immediately asks again. Updates arrive promptly without a constant stream of empty responses. It is still ordinary HTTP, at the price of one held connection per client and a little reconnection logic.
Server-Sent Events
The client opens one HTTP request and the server keeps the response open, writing events to it as they happen. The browser's EventSource API handles the rest:
const source = new EventSource("/events");
source.onmessage = (e) => render(JSON.parse(e.data));
On the wire it is a text format with a content type of text/event-stream:
id: 42
event: price
data: {"symbol":"ABC","value":101.5}
A blank line ends each event. SSE flows in one direction only, from server to client.
WebSockets
A WebSocket begins as an HTTP request that asks to upgrade the connection. After that it is no longer HTTP: it is a persistent, two-way channel carrying text or binary messages in either direction with very little overhead per message.
What SSE gives you for free
SSE is often overlooked, which is a pity because it solves the commonest case, a server pushing updates to a page, with almost no code.
- Automatic reconnection. If the connection drops, the browser reconnects by itself after a short delay, which the server can adjust with a
retry:field. - Resuming where it left off. If events carry an
id, the browser sends the last one it saw in aLast-Event-IDheader when it reconnects, so the server can replay what was missed. - It is just HTTP. Existing authentication, cookies, logging, load balancers and compression all work.
Its limits are real, though:
- One direction. The client sends data with ordinary requests alongside the stream.
- Text only. Binary data must be encoded.
- No custom headers.
EventSourcecannot set anAuthorizationheader. Use cookies, or read the stream withfetchinstead, which is how most streaming AI interfaces do it. - A connection limit on HTTP/1.1. Browsers allow about six connections per site, shared across all tabs, so a few open tabs can use them up. HTTP/2 multiplexes many streams over one connection and removes the problem; make sure it is enabled.
- Buffering proxies. A proxy that buffers responses will hold your events back. Disable buffering for the stream's route.
What WebSockets cost
A WebSocket gives you a raw message pipe and leaves the rest to you:
- Reconnection is your job. You must detect a dead connection, reconnect with backoff, and work out what was missed while you were away.
- Heartbeats. Idle connections are closed silently by load balancers, mobile networks and home routers, often after 30 to 120 seconds. Both ends need periodic ping messages to keep the connection alive and to notice when it has died.
- Authentication is awkward. Browsers cannot attach custom headers to the opening request. Authenticate with a cookie, or with a short-lived ticket obtained over HTTPS first, and remember that a connection stays open after the token that authorised it expires.
- Scaling needs a plan. Each client is attached to one particular server. To deliver a message to a user connected elsewhere, servers need a shared message bus between them, and deployments have to drain long-lived connections gracefully.
- Backpressure. A client on a slow network cannot keep up with a fast producer. Without a limit on what you queue for each connection, memory use grows until the server fails.
- Less help from the platform. HTTP caching, standard status codes and much request-based tooling do not apply once the connection is upgraded.
A decision guide
| You are building | Reasonable choice |
|---|---|
| A dashboard where data changes every minute | Polling |
| Notifications, activity feeds, progress of a background job | SSE |
| Streaming a generated response to the page | SSE or a streamed fetch |
| Live prices or scores, one way, many updates | SSE |
| Chat with typing indicators and presence | WebSocket |
| Collaborative editing, multiplayer games | WebSocket |
| High-frequency or binary data in both directions | WebSocket |
The deciding question is whether the client needs to send frequent, low-latency messages on the same channel. If the client mostly listens and occasionally acts, SSE plus ordinary requests is simpler and more robust. If both sides talk continuously, use a WebSocket.
Whichever you choose
- Design for disconnection. Phones change networks and laptops sleep. Give every event an ID or sequence number so that a returning client can ask for what it missed, and make the handlers safe to run twice.
- Send small events, not whole state. But offer a way to fetch a full snapshot, so that a client that has fallen too far behind can start again cleanly.
- Back off when reconnecting. If a server restarts and ten thousand clients reconnect in the same second, they will take it down again. Add a random delay that grows with each failed attempt.
- Always use TLS.
wss://and HTTPS streams pass through intermediaries far more reliably than unencrypted ones, apart from the obvious security benefit. - Test on a bad connection. Throttle the network, switch it off mid-stream, and leave a tab idle for ten minutes.
You can watch both protocols at work with the WebSocket Tester and the SSE Client: connect to an endpoint, see each message as it arrives, and observe what happens when the connection drops.