How to Choose Between SSE and WebSockets
Compare transport semantics, reconnection behavior, proxy compatibility, and HTTP/2 limits to pick server-sent events or WebSockets with confidence.
On this page
Introduction
When a page needs live updates from the server, two transports dominate the decision: server-sent events over plain HTTP, and the WebSocket protocol with its dedicated handshake. Teams often choose by familiarity rather than by constraints, and the wrong choice surfaces late as scaling limits, proxy fights, or an unnecessary protocol layer that must be debugged separately. The two mechanisms overlap in the narrow case of server-to-client notifications, where SSE is usually the simpler tool, and diverge sharply once the client needs to send a continuous stream back. This tutorial compares them on the axes that actually decide production deployments: direction of flow, framing and data types, reconnection behavior, compatibility with proxies and HTTP versions, and operational cost. It ends with a decision procedure and the migration signals that indicate the choice needs revisiting, so the decision is recorded rather than re-argued every quarter.
Transport and framing differences
SSE is a long-lived HTTP response with the content type text/event-stream. The body is a sequence of UTF-8 lines: fields such as event, id, and data, separated by blank lines. There is no new protocol, which is the source of most of its advantages: it passes through HTTP infrastructure, honors compression and authentication headers, and fails visibly when something buffers it. WebSockets upgrades an HTTP connection into a bidirectional frame protocol defined by RFC 6455. After the upgrade, both sides send frames independently: text or binary, with control frames interleaved. That symmetry is its power and its cost. The application must define its own message semantics, heartbeat behavior, and resubscription protocol, none of which the browser or the server provides. In exchange it offers binary framing, lower per-message overhead, and true peer-to-peer messaging. A useful shorthand: SSE gives you a stream of server events for free; WebSockets gives you a raw bidirectional channel and leaves the protocol design to you.
When SSE wins
The canonical SSE shape is one-directional notification: dashboards, activity feeds, stock or build status, progress reporting, and token streaming from language models. The client subscribes, the server pushes events, and any client-to-server interaction happens through ordinary fetch requests alongside the stream. In this shape SSE delivers three concrete wins. First, automatic reconnection: the browser EventSource reconnects on its own and sends the Last-Event-ID header, so the server can resume the stream exactly where it broke, with no client-side reconnect code. Second, infrastructure friendliness: SSE is an ordinary HTTP response, so existing auth middleware, compression, and monitoring apply without modification. Third, trivial server implementation.
export function sseHandler(req, res) {
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
connection: 'keep-alive',
});
res.flushHeaders();
const lastId = Number(req.headers['last-event-id'] ?? 0);
for (const ev of replayFrom(lastId)) send(res, ev);
const timer = setInterval(() => res.write(': ping\n\n'), 25_000);
req.on('close', () => clearInterval(timer));
}
function send(res, ev) {
res.write('id: ' + ev.seq + '\n');
res.write('event: ' + ev.kind + '\n');
res.write('data: ' + JSON.stringify(ev.data) + '\n\n');
}
The comment line starting with a colon is a heartbeat that keeps intermediaries from closing an idle stream. The id field is what the browser echoes back in Last-Event-ID after a reconnect.
When WebSockets wins
WebSockets becomes the correct choice when the client sends a continuous or high-rate stream of its own, or when per-message overhead matters. Collaborative editing sends local edits at human interaction frequency; multiplayer games send input state every frame; telephony and live transcription send binary audio. These flows are awkward over SSE because every client message would require a separate HTTP request with full header overhead, and impossible for binary without base64 inflation. WebSockets also enables symmetric protocols where either side initiates, such as remote procedure call patterns where the server invokes client-side handlers. The price is owning more of the stack: the application defines message framing, implements its own heartbeat with control frames, writes the reconnect state machine that the browser provides for free with EventSource, and designs resubscription semantics. A practical rule: if the product is a chat where the server relays client messages to other clients, the client-to-server side is low-rate and WebSockets is warranted. If the server is the only writer, that same product ships faster on SSE.
A minimal browser client makes the asymmetry concrete. The EventSource side is three lines, and the reconnect behavior arrives with the platform:
const es = new EventSource('/api/stream?topics=orders');
es.addEventListener('order', (e) => render(JSON.parse(e.data as string)));
es.onerror = () => console.warn('stream dropped; the browser reconnects automatically');
The WebSockets side starts a protocol instead: the application defines message kinds, heartbeats with control frames, and a reconnect state machine with backoff, because the platform provides none of them. That cost is the entry ticket for bidirectionality and binary framing, and it is only worth paying when the product actually needs what it buys.
Infrastructure and HTTP version constraints
SSE has two operational constraints worth verifying before committing. The first is buffering: any proxy or middleware in the chain that buffers the response body defeats streaming entirely, and the failure is silent because the client simply waits forever for the first event. Send an explicit flush of headers immediately, include the heartbeat comment line, and test through the real production chain, not a local dev server. The second is the connection limit: on HTTP/1.1 browsers cap connections per origin at six, so a page with several SSE streams plus regular requests can exhaust the pool and stall ordinary fetches. On HTTP/2 the streams multiplex over one connection and the limit disappears, which makes SSE at scale an HTTP/2 deployment question. WebSockets sidesteps both issues after its upgrade, but introduces its own: some corporate proxies strip the Upgrade header, and load balancers need explicit idle timeout configuration or long-lived sockets are reaped mid-session. Both transports need the same timeout audit, just at different layers.
A decision procedure
Write the decision as a short ordered checklist so it is auditable. First: does the client send a continuous stream or invoke server-push of binary payloads? If yes, choose WebSockets. Second: is the flow strictly or almost strictly server-to-client text events? If yes, choose SSE and verify proxy transparency and HTTP/2 availability at the expected scale. Third: is the expected client count per server high enough that per-connection memory matters? Both scale similarly, but SSE connections hold open response objects with less per-connection state than a typical WebSocket session with protocol buffers, so measure rather than assume. Fourth: does the team already operate one transport in production with hardened middleware? Operational maturity often outweighs a marginal technical fit. Record the answers in the design document. The recorded decision is revisitable when requirements shift; an unrecorded one is re-litigated forever.
Migration signals
Choose SSE first when the criteria are borderline, because the migration path from SSE to WebSockets is well understood: the server already maintains per-client event state and sequence numbering, and moving to WebSockets means adding a frame protocol over the same state. The reverse migration is harder because a WebSocket application has typically grown bidirectional message semantics that must be split apart. Signals that the initial choice is failing: client-to-server traffic over side-channel fetches grows past roughly one request per stream per few seconds; binary payloads force base64 encoding; per-message latency requirements make HTTP request overhead visible; or HTTP/1.1-only infrastructure caps the number of concurrent streams per page. When two or more of these appear, write the migration as a protocol design task, not a transport swap, because resubscription, replay, and ordering semantics are where the actual work lives.
Common pitfalls
- A silent buffering proxy. SSE streams hang forever with no error; test through the full production chain and flush early.
- Six-connection exhaustion on HTTP/1.1. Multiple SSE streams starve ordinary requests; confirm HTTP/2 end to end or consolidate streams.
- WebSockets for pure notifications. The team pays protocol design, heartbeats, and reconnect code for capability it never uses.
- No heartbeat on SSE. Idle streams are reaped by proxies and the client waits indefinitely for events that will never arrive.
- Ignoring Last-Event-ID. Free resumption is the main SSE advantage; not implementing replay server-side discards it.
- Assuming EventSource reconnect solves liveness. Reconnection restores the connection after a visible close; a half-open connection still needs heartbeats to detect.
Conclusion
SSE and WebSockets answer different questions. SSE is HTTP doing what HTTP already does well: one response, streamed incrementally, with browser-managed reconnection and Last-Event-ID resumption. WebSockets is a separate protocol bought for bidirectionality and binary framing, paid for in protocol design, heartbeat code, and reconnect state machines. Decide by data direction first, then by infrastructure reality: proxy buffering, connection limits, and HTTP version availability for SSE; upgrade compatibility and idle timeouts for WebSockets. Write the decision down with its criteria, and watch for the migration signals rather than treating the choice as permanent. Most notification-shaped products ship faster on SSE, and the ones that outgrow it graduate to WebSockets with their state model already in place.
Sources: MDN: Server-sent events, RFC 6455: WebSocket protocol, WHATWG: Server-sent events spec.
FAQ
- Can SSE carry binary data?
- Not natively. SSE payloads are UTF-8 text lines. Binary requires base64 encoding, which adds about 33 percent overhead, so image or binary-heavy flows belong on WebSockets or plain fetch.
- Does HTTP/2 fix the six-connection limit for SSE?
- Yes. On HTTP/2 each SSE stream is one multiplexed stream rather than one TCP connection, so the browser limit of six connections per origin no longer applies. Verify the delivery chain actually negotiates HTTP/2 end to end.
- Is EventSource reconnection really free?
- The browser reconnects automatically and replays the Last-Event-ID header, which is a real advantage. You still need server-side replay support and heartbeats to detect silent failures, so free means cheaper, not zero work.
Report a problem with this articleOpens a pre-filled issue on GitHub.