Foundations · L1WebSockets, SSE and long polling

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.

L1 Must-knowFoundations17 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 22 Oct 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

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

Section 2 of 8

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.

Section 3 of 8

How it works

Step through one chat message, delivered three ways. Use Next and Back, or the ← and → keys.

One new message, three ways to deliver it: long polling, SSE and WebSocketA · Long polling App Server B · Server-Sent Events App Server C · WebSocket App Server GET /pollserver holds the requestGET /eventsresponse stays openUpgrade → 101one open connection new messagenew messagenew message 200 + messagerequest is finisheddata: messagesame response, still openframe: messagesame connection GET /poll againto send: a normal POSTframe: "typing…" SeniorPath
  1. 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.
  2. Someone sends a chat message. The server has it now. It must reach the app in each of the three set-ups.
  3. 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.
  4. 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.
Step 1 of 4

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.

  • Upgrade is a hop-by-hop header, so a reverse proxy does not pass it on by default. In nginx you must set the Upgrade and Connection headers 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

Section 4 of 8

Trade-offs

OptionDirectionReconnect and missed eventsProxies and load balancersUse it when
Short pollingClient asksYes Each ask is fresh.Easy. Plain requests.Updates are rare, and a delay of seconds is fine.
Long pollingServer to client, one answer per requestYes Next request picks up.Needs sticky sessions with many servers. 9 Header cost on every message. 3A fallback for networks that block other options.
SSEServer to client onlyYes Built in, with Last-Event-ID. 2Plain HTTP. Use HTTP/2, or six tabs can use up the browser limit. 4Feeds, scores, notifications, streaming AI answers.
WebSocketBoth waysNo You build reconnect and catch-up.Proxy must pass Upgrade. Idle timeouts need pings. 8Chat, 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.

Section 5 of 8

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.
Section 6 of 8

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 Upgrade and Connection, 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.
Section 7 of 8

Check yourself

1. Your app shows live sports scores. The browser only needs to receive updates. What is the simplest good fit?

Show answer

Server-Sent Events, because data flows one way and the browser reconnects by itself. SSE is one-way from server to client, and the EventSource API reconnects on its own with the Last-Event-ID header.

2. Your WebSocket connections behind nginx close after one quiet minute. What is a likely cause?

Show answer

The proxy closes a connection when the server sends nothing for 60 seconds, which is the nginx default. By default, nginx closes the connection if the proxied server sends no data for 60 seconds. Raise proxy_read_timeout, or have the server send ping frames.

3. You run 4 WebSocket servers. A user on server 3 does not get a message created on server 1. What is missing?

Show answer

A pub/sub layer, so every server that holds a subscriber gets a copy of the message. Each server only knows its own connections. Socket.IO calls this part an adapter, and Slack's channel servers do this job.

4. Why does long polling across many servers often need sticky sessions?

Show answer

Each client sends many separate requests, and they must reach the server that holds its session. The Socket.IO docs say long polling sends many HTTP requests, so the load balancer must route each client to the same server.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 11 sources and related lessons
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. MDN Web Docs, “The WebSocket API (WebSockets)” (opens in a new tab)
    The browser API, and why the plain WebSocket interface has no backpressure.
  6. 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.
  7. 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.
  8. nginx documentation, “WebSocket proxying” (opens in a new tab)
    The headers a reverse proxy must pass, and the 60-second idle timeout.
  9. 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.
  10. 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.
  11. 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

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper