WebSockets, SSE and long polling
How a server can push live updates to apps, and how to pick between long polling, Server-Sent Events and WebSockets.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A food delivery app adds live order tracking. When the restaurant marks an order as "cooking" or the rider moves, the phone should update at once. The team picks WebSockets and builds it in two weeks. On a laptop, it works well.
In production, two problems appear. First, many phones show "Reconnecting…" again and again. The team finds that their nginx proxy closes any connection that is quiet for 60 seconds. A cooking order can be quiet for ten minutes.
Second, some users never see "rider picked up". The team runs four WebSocket servers. The update is created on server 1, but the user's phone is connected to server 3. Server 1 has no idea that server 3 holds the user.
The fix takes another two weeks: ping frames every 30 seconds, and a Redis pub/sub channel per order. This story is made up, but both problems are real and well documented. 8 9
The idea in simple words
Normal HTTP is request and response. The client asks, and the server answers. The server cannot speak first. For live updates, like chat, scores or a rider on a map, you need the server to push.
There are four common ways to do this:
- Short polling: the client asks "anything new?" every few seconds. Simple, but most answers are empty, and updates wait until the next ask.
- Long polling: the client asks, and the server holds the request until there is news or a timeout. Then the client asks again. 3
- Server-Sent Events (SSE): the client opens one HTTP response that never ends. The server keeps writing events into it. Data flows only from server to client. 2 4
- WebSocket: the client starts with an HTTP request and asks to "upgrade". After that, one connection stays open, and each side can send at any time. 1
The key idea. Pushing data means holding a connection open for every user. The hard part is not the protocol. It is keeping millions of open connections alive, routed and fed at the right speed.
How it works
Step through one chat message, delivered three ways. Use Next and Back, or the ← and → keys.
- Before the event. A, long polling: the app asks for news and the server holds the request open. B, SSE: the app opens one response that never ends. C, WebSocket: an HTTP Upgrade request gets 101, and the connection stays open.
- Someone sends a chat message. The server has it now. It must reach the app in each of the three set-ups.
- A answers the waiting request with the message, and that request is finished. B writes one more event into the open response. C sends one WebSocket frame on the open connection.
- A must send a new request, or the server has no open request to answer with the next message. B can only receive, so the app sends with a normal POST. C can send on the same connection, for example a typing signal.
Long polling. The server answers only when an event happens or a timeout ends. The client then sends a new request, usually at once. 3 Every poll is a full HTTP message with headers. In the worst case, a message waits more than three network trips, because it can arrive just after a response left. RFC 6202 says a timeout of about 30 seconds is safer than longer ones, which proxies may cut. 3
SSE. The browser calls new EventSource("/events"). The server answers with the type text/event-stream and writes lines like data: hello, with a blank line after each event. 4 Each event can carry an id. If the connection drops, the browser reconnects by itself and sends the last id in a Last-Event-ID header. The server can then send what the client missed. 2 The client cannot send events on this connection. 4 To send data, use normal requests, such as POST.
WebSocket. The client sends an HTTP Upgrade request. The server answers 101 Switching Protocols, and from then on, either side can send frames at any time. 1 RFC 6455 leaves reconnecting to the client. It says clients should wait a random time before the first reconnect, then use backoff. 1 There is also no built-in "what did I miss", so you design that yourself.
Proxies and load balancers. Anything between the app and your server can break a long-lived connection.
Upgradeis a hop-by-hop header, so a reverse proxy does not pass it on by default. In nginx you must set theUpgradeandConnectionheaders yourself. 8- nginx closes a proxied connection if the server sends nothing for 60 seconds. You can raise
proxy_read_timeout, or send ping frames. 8 - Some old proxies drop quiet HTTP connections too. The SSE spec suggests a comment line, starting with
:, about every 15 seconds. 2 Proxies may also buffer a whole response before they send any of it, which breaks streaming. 3
Heartbeats. A WebSocket ping frame can work as a keepalive or as a check that the other side still answers. The other side must reply with a pong. 1 Heartbeats do two jobs: they keep proxies from closing quiet connections, and they find dead connections, so you can free their memory.
HTTP/2. Without HTTP/2, MDN says a browser allows only 6 SSE connections per domain, across all tabs. So a few open tabs can use them all up. Over HTTP/2, the browser and server agree on a stream limit, and the default is 100. 4 RFC 8441 lets a WebSocket run on one HTTP/2 stream instead of its own TCP connection. 7
Scaling many open connections. Each user now holds a connection to one server. Two things follow.
- Routing. A WebSocket stays on the server where it started. Long polling sends many separate requests, so they need sticky sessions to reach the server that holds the client's state. 9
- Fan-out. One event must reach every user who cares, but those users sit on many servers. You put a pub/sub layer in the middle. Each server subscribes to the topics of its own users, and passes messages down their connections. Socket.IO calls this an adapter, and Redis is one option. 9
Slack does this at large scale. Gateway servers in many regions hold the users' WebSockets. A channel server, found by consistent hashing, sends each message to every gateway with a subscriber. Each gateway then sends it to its own clients. 10 At Discord, each WebSocket gets its own session process. Anything published in a guild goes to every session connected to it. 11
Backpressure for slow clients. A phone on a weak network reads slowly. If the server keeps sending, messages pile up in memory. MDN says the plain browser WebSocket interface has no backpressure. Fast messages can fill memory or use all the CPU. 5 On the sending side, bufferedAmount shows the bytes queued by send() that are not yet on the network. 6 Watch your server's queue per connection. When it grows too large, drop old updates, merge them, or close the connection and let the client resync.
Discord learned how slow parts spread. During peak hours, some guild processes could not keep up with their message queues. In another case, session processes grew their message queues until the whole Erlang VM ran out of memory. 11
Trade-offs
| Option | Direction | Reconnect and missed events | Proxies and load balancers | Use it when |
|---|---|---|---|---|
| Short polling | Client asks | Yes Each ask is fresh. | Easy. Plain requests. | Updates are rare, and a delay of seconds is fine. |
| Long polling | Server to client, one answer per request | Yes Next request picks up. | Needs sticky sessions with many servers. 9 Header cost on every message. 3 | A fallback for networks that block other options. |
| SSE | Server to client only | Yes Built in, with Last-Event-ID. 2 | Plain HTTP. Use HTTP/2, or six tabs can use up the browser limit. 4 | Feeds, scores, notifications, streaming AI answers. |
| WebSocket | Both ways | No You build reconnect and catch-up. | Proxy must pass Upgrade. Idle timeouts need pings. 8 | Chat, games, shared editing: the client sends often too. |
Simple rule: if only the server talks, start with SSE. Choose WebSocket when the client also sends often. Keep long polling as a fallback.
At work: how a senior uses this
- Ask first: "How fast must the update arrive, and who talks?" A ten-second delay may be fine with plain polling.
- Plan "what did I miss" from day one. Give events an id, and let the client ask for everything after its last id.
- Check every hop: CDN, load balancer, proxy. Ask: "What is the idle timeout here?" Set your heartbeat below the smallest one.
- Treat connections as a resource. Count open connections per server, and alert on sudden drops.
- After a deploy or outage, every client reconnects at once. Add random jitter to reconnect delays.
- Keep connection servers thin. They hold sockets and forward messages. Business logic lives in normal services.
- Load test with real numbers of idle connections, not only with requests per second.
With AI
What to ask the agent
"Write an SSE endpoint in Node for order status. Send an id with each event, support Last-Event-ID, and send a comment line every 15 seconds."
"Review this WebSocket client. Does it reconnect with backoff and jitter? Does it fetch missed events after a reconnect?"
"We run 6 WebSocket servers behind a load balancer. Design the pub/sub layer with Redis so a message reaches users on any server."
What to check yourself
- The proxy config passes
UpgradeandConnection, and the idle timeout is longer than the heartbeat. - The server sends heartbeats, and closes connections that stop answering.
- Reconnect has a limit, backoff and jitter. A loop with a fixed one-second delay can flood your servers after an outage.
- Each connection has a send queue with a maximum size. Agents often write
socket.send()in a loop with no limit. - The client sends an auth token on connect, and the server checks that the user may see each topic.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 11 sources and related lessons
- Fette and Melnikov, RFC 6455: The WebSocket Protocol (IETF, 2011) (opens in a new tab)
The opening handshake (HTTP Upgrade and 101), frames, ping and pong, and the closing handshake. - WHATWG, HTML Living Standard, section 9.2: Server-sent events (opens in a new tab)
The EventSource API, the text/event-stream format, automatic reconnect and the Last-Event-ID header. - Loreto, Saint-Andre, Salsano and Wilkins, RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP (IETF, 2011) (opens in a new tab)
How long polling and HTTP streaming work, and their costs in latency, headers, held connections and proxies. - MDN Web Docs, “Using server-sent events” (opens in a new tab)
Code for the browser and the server, and the six-connection limit without HTTP/2. - MDN Web Docs, “The WebSocket API (WebSockets)” (opens in a new tab)
The browser API, and why the plain WebSocket interface has no backpressure. - MDN Web Docs, “WebSocket: bufferedAmount property” (opens in a new tab)
How many bytes are queued by send() but not yet sent on the network. - McManus, RFC 8441: Bootstrapping WebSockets with HTTP/2 (IETF, 2018) (opens in a new tab)
Running a WebSocket on one stream of an HTTP/2 connection with an extended CONNECT. - nginx documentation, “WebSocket proxying” (opens in a new tab)
The headers a reverse proxy must pass, and the 60-second idle timeout. - Socket.IO documentation, “Using multiple nodes” (source on GitHub) (opens in a new tab)
Why long polling needs sticky sessions, and why many servers need an adapter such as Redis to broadcast. - Sameera Thangudu, “Real-time Messaging”, Slack Engineering, 2023 (opens in a new tab)
Gateway servers that hold WebSockets, channel servers found by consistent hashing, and the path of one message. - Stanislav Vishnevskiy, “How Discord Scaled Elixir to 5,000,000 Concurrent Users”, Discord blog, 2017 (opens in a new tab)
One session process per WebSocket, pub/sub inside a guild, and what broke under load.
Case studies: Discord: Fanning out messages to millions of users with Elixir · Slack: How Slack delivers messages in real time
Related: HTTP/1.1, HTTP/2 and HTTP/3 · Load balancing · Presence and real-time fan-out · Backpressure and flow control · Webhooks and async APIs
- HTTP/1.1, HTTP/2, HTTP/3 and QUIC: why many streams on one connection matter.
- Presence and real-time fan-out: sending one event to millions of users.
- Backpressure and flow control: what to do when a reader is slower than a writer.