WebSockets and Server-Sent Events: Keeping a Connection Open
Compare polling, server-sent events and WebSockets, and learn what it takes to keep live connections working in production.
Key takeaways
- Server-sent events are a long-running HTTP response carrying text events, with automatic reconnection built into the browser.
- WebSockets start as an HTTP request and then switch to a separate two-way message protocol.
- Proxies, buffering and idle timeouts cause most live-connection problems in production.
- Any long-lived connection will drop eventually, so plan how clients reconnect and catch up.
Ordinary HTTP waits for the client to ask before the server can say anything. When a page needs live updates, such as chat messages, a progress bar or a changing score, you have two standard ways to keep a channel open. Server-sent events (SSE) let the server push a stream of text to the browser. WebSockets open a two-way channel where either side can send at any moment.
Choose SSE when updates flow mainly from server to client. Choose WebSockets when both sides talk often. If updates are rare and a delay is acceptable, plain polling may be all you need.
The problem with asking repeatedly
The oldest solution is polling: the page asks every few seconds whether anything changed. It is simple and works everywhere, but most answers say "nothing new", and news still waits for the next check.
Long polling improves the delay. The client asks, and the server holds the request open until it has something to say or a time limit passes. The client then immediately asks again. It works through almost any network, at the cost of repeated request overhead and some awkward timing code.
Server-sent events
With SSE, the browser makes a normal GET request and the server never quite finishes the response. It declares a special content type and writes events as they happen:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
data: Build started
event: progress
data: {"percent": 40}
id: 17
: this line is a comment used as a heartbeat
Each event is a few field: value lines followed by a blank line. data carries the content, event names a type, id labels the event and retry suggests how long to wait before reconnecting.
In the browser, the interface is EventSource:
const stream = new EventSource("/updates");
stream.onmessage = e => console.log(e.data);
stream.addEventListener("progress", e => console.log(e.data)); The best feature is recovery. If the connection drops, the browser reconnects on its own and sends a Last-Event-ID header with the last id it saw. A server that keeps recent events can replay the missed ones.
The limits: traffic goes one way, and the data is text. EventSource also cannot set custom request headers, so authentication usually relies on cookies. Applications that need more control read a streaming response with fetch and parse the same format themselves. Many AI chat interfaces stream their replies in this style.
Over HTTP/1.1, each open stream occupies one of the browser's few connections to a host, so several tabs can exhaust them. HTTP/2 and HTTP/3 multiplex streams and largely remove that problem.
WebSockets
The WebSocket protocol is specified in RFC 6455. It begins as an HTTP request asking to upgrade:
GET /chat HTTP/1.1
Host: www.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13 The server agrees with 101 Switching Protocols and a Sec-WebSocket-Accept value derived from the key. From then on, the connection no longer speaks HTTP. Both sides send frames that carry text or binary messages, plus control frames for ping, pong and close.
Addresses use ws:// for unencrypted and wss:// for TLS. Use wss in anything real. In JavaScript:
const socket = new WebSocket("wss://www.example.com/chat");
socket.onopen = () => socket.send("hello");
socket.onmessage = e => console.log(e.data); Per-message overhead is small, a few bytes of framing in place of full HTTP headers. You can estimate it with the WebSocket frame overhead calculator. Messages from client to server are masked, a requirement that protects older intermediaries from being confused; it is not encryption.
The standard also allows WebSockets to run inside a single HTTP/2 or HTTP/3 stream. Support depends on both browser and server.
Choosing between them
SSE with ordinary POST requests for the client's actions covers more cases than many developers expect, including notifications and dashboards. WebSockets earn their extra complexity when both directions are busy, as in real-time document editing.
Neither is the usual tool for live audio and video between people. That is the job of WebRTC, which often uses a WebSocket only to set up the call.
Surviving proxies and timeouts
Most production trouble comes from the machines in the middle.
Buffering. A proxy or compression layer may collect an SSE response until it has a full block, so events arrive in bursts or not at all. Turn off response buffering for that route and check compression settings.
Idle timeouts. Load balancers, firewalls and home routers close connections that look quiet. Send a heartbeat, such as an SSE comment line or a WebSocket ping, more often than the shortest timeout on the path.
Upgrade headers. A reverse proxy must pass the WebSocket upgrade through. In nginx, a typical location needs:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 300s; Server capacity. Each open connection holds memory, and in some server models it occupies a whole worker process. A few hundred idle streams can starve a pool sized for short requests. Event-driven servers handle this better.
Designing the messages
Neither technology tells you what to put inside a message, so settle that early.
Give every message a type, so the receiver can route it, and an ID or sequence number, so it can spot gaps and duplicates. JSON is a convenient default:
{"type": "chat.message", "id": 1042, "room": "support", "text": "Hello"} Binary formats make sense when volume is high or payloads are numeric, at the cost of readability.
Decide what delivery you actually need. A WebSocket delivers messages in order while it lasts, but a successful send call does not prove the other side processed anything. If a message must not be lost, have the receiver acknowledge it, keep it until acknowledged and make repeats harmless by checking the ID.
Decide, too, how a client catches up after a long absence. Replaying thousands of old events may be worse than sending a fresh snapshot of the current state followed by new changes. A good rule is to replay short gaps and reload for long ones.
Slow consumers
A server can often produce data faster than a weak mobile connection accepts it. Unsent messages then pile up in memory. Watch how much is queued for each client, and choose a policy before it matters: drop stale updates, merge them so only the latest value is sent, slow the producer or disconnect the client and let it resume.
On the browser side, socket.bufferedAmount reports how many bytes are still waiting to leave. Check it before sending large or frequent messages.
Reconnection and missed messages
Deployments, network changes and sleeping laptops will all break connections. WebSockets do not reconnect by themselves, so your code must.
The random jitter matters. If a server restarts and every client reconnects at the same instant, the rush can knock it over again. The retry and backoff simulator makes the effect visible.
With more than one server, a message arriving on one machine may need to reach a client connected to another. A shared publish-and-subscribe service usually handles that. Load balancers also need long enough timeouts and a sensible way to drain connections during releases.
A worked choice
Say you are building a page that shows the progress of a long video conversion. The user starts the job once and then watches. Messages flow almost entirely from server to browser, so an ordinary POST to start the job plus an SSE stream for progress fits well. If the stream drops, the browser reconnects, and the server sends the current percentage.
Now say the page is a shared whiteboard where several people draw at once. Every participant sends many small updates and receives everyone else's. A WebSocket suits that, together with code for reconnection, ordering and catching up.
A third case, a page showing store opening status that changes twice a day, needs neither. A cached request every few minutes is cheaper to run and has nothing to reconnect.
Security checks
- Check the
Originheader on WebSocket handshakes. CORS rules do not block cross-site WebSocket connections, and cookies may be sent along, so the server must reject origins it does not expect. - Authenticate and authorize. Verify identity at connection time, and check permission for each channel or action afterward.
- Close expired sessions. A connection can outlive the login that opened it.
- Limit size and rate. Cap message length, connections per user and messages per second.
- Validate everything. Treat incoming messages like any other untrusted input.
Testing and watching
Browser developer tools show live connections in the Network tab. Select a WebSocket entry to see frames as they pass, or an event stream to see each event. From a terminal, curl -N disables curl's output buffering so you can watch an SSE endpoint:
curl -N https://www.example.com/updates If events appear promptly when you connect to the application directly but arrive late through the public address, look at the proxy layers one at a time. And if a connection dies after a suspiciously round number of seconds, you have almost certainly found a timeout setting.