An order page should change the moment the warehouse ships. A CI dashboard streams build logs line by line. A shared whiteboard sends every cursor move to everyone else. HTTP was designed for the client to ask and the server to answer, so each of these needs a way for the server to speak first.
Browsers offer three common ways to do that: long polling, server-sent events (SSE) and WebSockets. This post compares how each works on the wire, how it reconnects and catches up, what it needs from proxies and how it scales, with a sequence diagram of all three side by side.
At a glance
| Long polling | Server-sent events | WebSockets | |
|---|---|---|---|
| Direction | Server to client | Server to client | Both ways on one connection |
| On the wire | Repeated HTTP requests, each held open | One HTTP response that never ends | An HTTP handshake, then WebSocket frames |
| Data | Anything HTTP can carry | UTF-8 text events | UTF-8 text or binary frames |
| Browser API | fetch in a loop |
EventSource |
WebSocket |
| Reconnect and catch up | Your loop and a cursor | Built in, with Last-Event-ID |
Your code and your sequence numbers |
| Defined in | RFC 6202 (practices) | WHATWG HTML Standard | RFC 6455 |
Long polling: a request the server holds
Plain polling asks every few seconds and mostly hears "nothing new". Long polling changes one thing: the server does not answer until it has an event or a timeout expires. The client sends the next request as soon as a response arrives, so one request is almost always waiting at the server.
let after = 41; // last event ID the client has seen
for (;;) {
const res = await fetch(`/updates?after=${after}`, { cache: 'no-store' });
if (res.status === 200) {
const events = await res.json(); // everything after the cursor
events.forEach(handle);
after = events.at(-1).id;
} // 204: the hold timed out, ask again
}
A real client also backs off after errors. The cursor matters more than the hold: the server returns every event after it, so a slow client gets a batch instead of missing events.
RFC 6202 lists the costs. Every message pays for a full request and response. Latency is uneven: an event that arrives between a response and the next request waits for it, so the worst case is more than three network transits. And hold times fight timeouts: the RFC reports holds of up to 120 seconds working but calls 30 seconds a safer value.
Long polling survives because almost any proxy passes ordinary requests. Socket.IO, for example, starts with HTTP long polling by default and upgrades to WebSocket when it can.
Server-sent events: one response that keeps going
With SSE, the browser sends one request and the server never finishes the response. The body is a text/event-stream: UTF-8 lines of field: value, with a blank line ending each event.
HTTP/1.1 200 OK
Content-Type: text/event-stream
retry: 5000
: keep-alive
id: 42
event: order-shipped
data: {"orderId":"A-1001","carrier":"UPS"}
id: 43
data: {"orderId":"A-1002","status":"packed"}
| Field | Meaning |
|---|---|
data |
The payload; several data lines join with newlines |
id |
The last event ID, sent back as Last-Event-ID on reconnect |
event |
The event type; message if missing |
retry |
The reconnection delay in milliseconds |
: at line start |
A comment, useful as a keep-alive |
EventSource does the client work. After a network error it waits the reconnection delay, reconnects and sends Last-Event-ID, and the server replays what the client missed. A 204 response stops reconnection; any other non-200 status, or a different content type, fails the connection for good.
The limits:
- Server to client only. The client sends with ordinary requests, such as a
fetchPOST. - Text only. Binary data needs an encoding such as base64.
- No custom headers.
EventSourcetakes a URL and one option,withCredentials: cookies work, anAuthorizationheader does not. - Few connections over HTTP/1.1. MDN notes a limit of six per browser and domain, shared by every tab. Over HTTP/2, streams share one connection, and RFC 9113 recommends allowing at least 100 concurrent streams.
WebSockets: an upgrade to a different protocol
A WebSocket starts as an HTTP/1.1 request that asks to switch protocols. The handshake from RFC 6455, shortened:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The accept value is a base64 SHA-1 hash of the key plus a fixed GUID, which proves the server speaks WebSocket. After the 101 the connection is no longer HTTP, and both sides send frames:
- Data frames, text or binary, so Protocol Buffers or MessagePack need no encoding. Frames from the client are masked; frames from the server are not.
- Ping and Pong check that the other side is alive; a Ping must be answered with a Pong.
- Close can carry a status code: 1000 for a normal closure, 1001 when an endpoint goes away, such as a server shutting down. Code 1006 is never sent; it reports a connection that dropped without a Close frame.
What the protocol leaves out matters as much: no reconnection, message IDs, replay or acknowledgments. RFC 6455 only asks clients to back off after an abnormal closure, starting with a random delay such as 0 to 5 seconds. The rest is your application protocol, named in Sec-WebSocket-Protocol. The browser API has no backpressure either; MDN points to WebTransport for that.
The classic upgrade needs HTTP/1.1. RFC 8441 and RFC 9220 run a WebSocket on one HTTP/2 or HTTP/3 stream, opened with an extended CONNECT request, where every hop supports it.
Reconnection and missed messages
Every long-lived connection drops: phones switch networks, laptops sleep, servers deploy. What did the client miss?
| Long polling | SSE | WebSockets | |
|---|---|---|---|
| Who reconnects | Your request loop | The browser, after retry |
Your code, with backoff and jitter |
| Where to resume | The cursor in each request | The Last-Event-ID header |
A sequence number the client sends |
| Server needs | Recent events by ID | Recent events by ID | Recent events by ID |
The last row is the point: all three need recent events with ordered IDs, in a Redis Stream, a Kafka topic or a table with a sequence column. A broker without history is not enough. Redis Pub/Sub delivers at most once, so a disconnected subscriber loses the message for good; use it for live fan-out and keep a log for catching up.
When a server restarts, all its clients reconnect at once, so add random jitter to every reconnect delay (for SSE, send each connection a randomized retry value).
Proxies, load balancers and timeouts
Most production problems with push happen between the client and the server:
- Idle timeouts. Nginx and an AWS Application Load Balancer both close idle connections after 60 seconds by default. Keep long-poll holds below the shortest timeout, send an SSE comment "every 15 seconds or so", as the HTML Standard suggests, and send WebSocket Pings from the server.
- Buffering. A buffering proxy holds SSE events until its buffer fills. In nginx, turn off
proxy_bufferingfor the stream or sendX-Accel-Buffering: nofrom the application. - Upgrade headers.
UpgradeandConnectionare hop-by-hop, so a reverse proxy drops them unless it forwards them, as in the nginx WebSocket guide:
location /ws/ {
proxy_pass http://app;
proxy_http_version 1.1; # the default only since nginx 1.29.7
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s; # longer than the ping interval
}
location /events {
proxy_pass http://app;
proxy_buffering off; # pass each SSE event on at once
}
SSE and WebSocket connections stay on one server, so they need no sticky sessions; long-poll requests may reach any server that can read the shared event log. The load balancer diagram covers layer 4 and layer 7 balancing.
Scaling: open connections and a pub/sub backplane
Push turns a stateless web tier into one that holds state: every open connection belongs to one process.
- Fan-out needs a backplane. Events start elsewhere, such as in an order service, so each server subscribes to a channel in Redis, NATS or Kafka and forwards matching events to its own connections: the purple arrows in the diagram. Every subscribed server needs its own copy of each event, so this is pub/sub, not a work queue. The chat app architecture shows this with WebSocket gateways.
- Capacity is open connections, not requests per second. Idle connections cost memory and file descriptors on every server and proxy in the path.
- Deploys drop connections. Drain each server: stop accepting connections, close WebSockets with 1001 or end SSE responses, and let clients reconnect elsewhere with jitter.
Offline users need another channel; the notification system design covers push and email.
Choosing by use case
| Use case | Pick | Why |
|---|---|---|
| Notifications, order status, live dashboards | SSE | Server to client only, built-in resume, plain HTTP |
| Streaming text: build logs, LLM output | SSE or a streamed fetch response |
One request, one stream |
| Chat, presence, collaborative editing | WebSockets | Frequent small messages in both directions |
| Games and binary protocols | WebSockets, or WebTransport | Binary frames; WebTransport adds backpressure and datagrams |
| Networks that block upgrades or buffer responses | Long polling | Ordinary short HTTP requests |
| Updates every few minutes | Plain polling | Simpler than any open connection |
The WebSockets vs SSE vs long polling diagram
Diagram contents
- until the page closes
- many events, one response
- frames in both directions
- Browser
- Server
- GET /updates?after=41
- event 42
- 200: events [42]
- event 43
- GET /updates?after=42
- 200 at once: events [43]
- GET /updates?after=43
- 204 after 30 s: no events
- GET /events (EventSource)
- 200: text/event-stream
- id: 42, data: {...}
- : keep-alive comment
- GET /events, Last-Event-ID: 42
- id: 43, replayed from the log
- GET /ws, Upgrade: websocket
- 101 Switching Protocols
- frame: subscribe orders
- frame: event 42
- frame: ack 42
- Ping
- Pong
- Close 1000, echoed back
How to read it:
- Three panels, one event stream. Each has a Browser and a Server lifeline. Purple arrows from the right are events reaching the server from the pub/sub backplane.
- Long polling (left): the first GET waits until event 42 arrives. Event 43 arrives while no request is open, so it waits for the next GET, which returns at once. The third GET times out after 30 seconds with a 204.
- SSE (middle): one GET and one 200 response that does not end. Events carry IDs, and a comment keeps the quiet connection open. After a drop, the browser sends
Last-Event-ID: 42and event 43 is replayed. - WebSocket (right): an Upgrade request and a 101, then frames in both directions, Ping and Pong as a heartbeat and a Close with code 1000.
- Line styles: solid arrows are requests, events and frames, dashed arrows HTTP responses, dotted arrows keep-alives. Notes under each panel list proxy and resume rules.
Drawing real-time connection diagrams clearly
- Use a sequence diagram for the protocol and an architecture diagram for the topology, which shows which server holds which connection.
- Draw the same event stream for every option, so the differences sit in the arrows.
- Show the gap: the moment with no open request, or the dropped connection.
- Label the resume state and timeouts: the cursor,
Last-Event-IDor sequence number, the hold time, the ping interval and the proxy's idle timeout.
Common mistakes are a WebSocket drawn as one double-headed arrow with no handshake, a missing proxy, and fan-out with no log to catch up from. See the sequence diagram example for the notation and the event-driven architecture diagram for the backplane.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- Add a Core Text heading and subtitle for each panel: Long polling, Server-sent events (SSE) and WebSocket.
- From the Sequence pack, add two Lifeline nodes per panel, Browser and Server, six in all, in one row with the same height. Give each panel one accent: amber, teal and blue.
- Draw each message as a straight edge between the lifelines, top to bottom. Make HTTP responses dashed and keep-alives (the SSE comment, Ping and Pong) dotted.
- Draw the incoming events in purple, each from a free point to the right of the Server lifeline: event 42 and event 43 in the long-polling panel, event 42 in the other two.
- Add a Fragment from the Sequence pack with the operator
loopover the repeating part of each panel. Add a red Core Text note where the SSE connection drops. - Under each panel, add a Markdown block from the Core pack with its proxy and resume rules, and a Core Text legend at the bottom.
For the topology view, the Mermaid converter turns a flowchart into a first draft. The example uses 12 diagram nodes (six lifelines, three fragments and three Markdown blocks), within the Free plan's limit of 15 per diagram.
FAQ
Is SSE better than WebSockets?
For server-to-client updates, often yes: it is plain HTTP, the browser reconnects on its own and sends Last-Event-ID so the server can resume, and it shares connections over HTTP/2. WebSockets win when the client also sends often or the data is binary.
Can SSE send data from the client to the server?
No. The client sends with ordinary HTTP requests, such as a fetch POST, next to the stream.
Is long polling obsolete? Not entirely. It is the fallback for networks that block upgrades or buffer streams.
Do WebSockets work over HTTP/2 and HTTP/3? Yes, where the client, proxies and server support RFC 8441 or RFC 9220. Otherwise clients use the HTTP/1.1 upgrade.
How many SSE connections can a browser open? Over HTTP/1.1, about six per browser and domain, shared by all tabs. Over HTTP/2, many streams share one connection.