Networking

WebSockets, SSE and long polling

Four ways to push data from server to client, what each costs to run, and how to keep millions of long-lived connections working through load balancers, deploys and reconnects.

Lesson14 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

HTTP has one shape: the client asks, the server answers. The server cannot start a conversation. That is fine for loading a page and useless for a chat app, where Bob’s browser needs to learn that Alice sent a message at a moment Bob’s browser knows nothing about.

The first thing everyone tries is polling: ask every few seconds. Run the numbers for one million users polling every 5 seconds. That is 200,000 requests per second, nearly all of which return “nothing new”, and a message still waits 2.5 seconds on average. Poll every second and the delay is tolerable, but the load is a million requests per second to deliver almost nothing.

In the mid-2000s web developers found a trick: have the server hold a request open and answer only when it has something. This family of hacks was nicknamed Comet. It worked, but it fought servers and proxies built for short requests. Two standards followed: Server-Sent Events, as part of HTML5, and the WebSocket protocol, published as RFC 6455 in 2011.

Four ways to get an event from server to browser3 components: Browser, New message, Server. Connections: Browser and Server (HTTP or WebSocket); New message to Server (arrives at any time).Browserpolls every 5 sNew messagean event on the server sideServerHTTP or WebSocketarrives at any time

Step 1 of 9

Short polling. The browser asks whether there is anything new every five seconds. Most of the time the honest answer is no, and the whole request was wasted.

Read the steps as text
  1. Short polling. The browser asks whether there is anything new every five seconds. Most of the time the honest answer is no, and the whole request was wasted.
  2. A message arrives just after a poll. It sits on the server until the next one, so the user waits up to five seconds. Polling faster cuts the delay and multiplies the wasted requests.
  3. Long polling. The browser asks, and the server does not answer. It holds the request open until it has something to say, or until a timeout of perhaps thirty seconds.
  4. The message arrives and the held request is answered at once. The browser immediately sends the next request. Delivery is nearly instant, at the price of one full HTTP request for every message.
  5. Server-Sent Events. The browser makes one request and the server never finishes the response. It writes each event down the open response as it happens, each with an id.
  6. The connection drops on a train. The browser reconnects by itself and sends the last id it saw in a header. The server replays what was missed. This resume step is built into Server-Sent Events.
  7. WebSockets. The browser sends an HTTP request asking to upgrade, and the server answers with status 101. From then on the connection is no longer HTTP. It is a two-way channel for small frames.
  8. Either side can now send at any moment, with a few bytes of overhead per frame. But heartbeats, reconnection and catching up after a drop are yours to build. The protocol gives you none of them.
  9. Pick the simplest one that meets the need. Poll when seconds of delay are fine. Use Server-Sent Events when only the server pushes. Use WebSockets when both sides talk often. All but short polling hold a connection open per client.
Four ways to get an event from server to browser

The four techniques

Short polling

The client requests on a timer. The server stays stateless and every piece of HTTP infrastructure works unchanged. The costs are the ones above: delay of up to one interval, and load that grows with the number of clients, not the number of events.

Long polling

The client sends a request and the server holds it until an event arrives or a timeout passes, typically 20 to 60 seconds. The client then asks again at once. Delivery is close to instant and it passes through anything that passes HTTP. Each message costs a full request with headers and authentication, and events can arrive in the gap between one response and the next request, so the client must say “everything after id 41”.

Server-Sent Events

The client makes one HTTP request and the server replies with Content-Type: text/event-stream and never ends the response. It writes events as lines of text, each optionally carrying an id. The browser’s EventSource API reconnects automatically after a drop and sends the last id it saw in a Last-Event-ID header.

SSE is one-way (the client sends by making ordinary requests) and carries text only. Over HTTP/1.1 each stream uses one of the browser’s six connections per host, which hurts with several tabs open. Over HTTP/2 a stream is one of many on a shared connection. Streaming responses from large language model APIs are a common current use.

WebSockets

The client sends an HTTP/1.1 request with Upgrade: websocket. The server answers 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames in both directions. A frame has only a few bytes of header, and can hold text or binary data.

After the upgrade it is no longer HTTP. That is the strength (either side sends at any time, cheaply) and the cost. There are no status codes, no automatic reconnection and no resume. Authentication happens once, at the upgrade. You add heartbeats, reconnection and catch-up yourself, or take a library that does.

WebTransport is a newer browser API over HTTP/3. It offers several independent streams and unreliable datagrams, so it avoids TCP head-of-line blocking. Browser and server support is still uneven, so treat it as an option to mention, with WebSockets as the fallback.

What it costs on the server

All but short polling keep a connection open per client, and that changes the server.

  • Memory, not CPU, is the limit. An idle connection costs a file descriptor, kernel socket buffers and whatever state your application keeps: commonly a few kilobytes to tens of kilobytes. With event-driven I/O, one server can hold hundreds of thousands of connections. WhatsApp reported more than two million on a single machine in 2012. A thread per connection does not get close.
  • Ports are not the limit. A server is not capped at 65,535 connections. A connection is identified by client address, client port, server address and server port, so the port range limits how many connections one client address can open to one server address. It can bite a proxy that opens very many connections to a single backend.
  • The servers are stateful. A connection lives on one machine. You cannot move it, and when the machine goes, every client on it must reconnect.

Proxies and load balancers

  • Idle timeouts. Balancers and proxies close connections that are quiet for too long, often about 60 seconds by default. Send heartbeats (WebSocket ping and pong frames, or an SSE comment line) every 20 to 30 seconds and raise the timeout.
  • Buffering. A proxy that buffers responses will sit on SSE events until its buffer fills. Turn buffering off for streaming routes.
  • Balancing. Round robin counts new connections, not open ones. Use least connections. After a scale-out the new servers stay nearly empty, because existing connections do not move.
  • Deploys. Connection draining cannot wait for connections that never end. Have the server ask clients to reconnect, a slice at a time.
  • Reconnect storms. When a server holding 300,000 connections dies, 300,000 clients reconnect, each needing a TLS handshake and authentication. Clients must use exponential backoff with random jitter, and servers should limit how fast they accept new connections. See retries and timeouts.

Reconnection and resume

Connections will drop: phones change networks, laptops sleep, you deploy. Design for it from the start.

Give every event in a stream an increasing id. The client remembers the last id it processed and sends it when it reconnects. The server replays later events from a durable log, or, if the client is too far behind, tells it to reload the current state. Delivery is then at-least-once, and the client drops duplicates by id. SSE gives you the client half of this for free. The server half, storing events so that they can be replayed, is your job with every technique. See delivery semantics.

Scaling to millions of connections

With more than one server, the user you want to reach is probably connected somewhere else.

Scaling WebSockets with a pub/sub backplane8 components: Alice, Bob, Load balancer, Gateway 1, Gateway 2, Pub/sub backplane, Chat service, Message store. Connections: Alice to Load balancer; Bob to Load balancer; Load balancer to Gateway 1; Load balancer to Gateway 2; Gateway 1 to Chat service (1. Alice sends); Chat service to Message store (2. persist); Chat service to Pub/sub backplane (3. publish); Pub/sub backplane to Gateway 2 (4. to subscribers); Pub/sub backplane to Gateway 1.AliceBobLoad balancerlong idle timeoutGateway 1holds Alice's socketGateway 2holds Bob's socketPub/subbackplaneRedis, NATS or KafkaChat servicestatelessMessage storedurable, ordered per chat1. Alice sends2. persist3. publish4. to subscribers
Scaling WebSockets with a pub/sub backplane

Split the system into two tiers. Connection gateways hold the sockets and do little else: authenticate, heartbeat, forward. Stateless services behind them do the real work. To get a message to the right socket there are two common designs.

  • Pub/sub backplane. Each gateway subscribes to a channel for every user or room it currently holds. A service publishes to the channel without knowing where anyone is. It is simple, but with Redis Pub/Sub delivery is fire-and-forget, so a gateway that is briefly disconnected misses messages.
  • Routing registry. A shared store maps each user to their gateway, and the sender forwards directly to it. This wastes less, at the cost of keeping the registry correct as connections come and go.

Either way, persist messages before delivering them, so that the resume path can cover whatever the live path dropped. Large rooms raise a separate fan-out problem. When a mobile app is in the background its socket is gone, and you fall back to the platform’s push notifications. The chat system case study puts these pieces together.

When to choose each

Technique Direction Choose when Avoid when
Short polling Client pulls Updates are rare and seconds of delay are fine, such as job status Many clients, or low latency needed
Long polling Server to client You need a fallback that works through any HTTP path Message rates are high
SSE Server to client Feeds, notifications, live scores, progress, token streams The client sends often, or data is binary
WebSockets Both ways Chat, collaborative editing, multiplayer games Only the server pushes

Pick the simplest technique that meets the latency you need. A dashboard that refreshes every 30 seconds needs no sockets at all.

In the interview

Any design with chat, notifications, live location or collaborative editing needs this choice. State the direction and rate of traffic first, then choose: “updates flow one way, a few per minute, so SSE”, or “both sides send many small messages, so WebSockets”.

Then show that you know connections are state. Mention gateways separate from business logic, a backplane or registry to find the right gateway, heartbeats against idle timeouts, resume by last event id from a durable log, and jittered reconnects so that one failure does not become a storm. Those five points are what separate a senior answer from “use WebSockets”.

Key takeaways

  • HTTP is request and response, so the server cannot speak first. Polling, long polling, SSE and WebSockets are four ways round that.
  • Short polling trades latency against wasted requests. Long polling removes the waste but spends a full HTTP request per message.
  • SSE is one long HTTP response for server-to-client events, with automatic reconnection and resume built into the browser.
  • WebSockets give a two-way channel with tiny frames, and leave heartbeats, reconnection and resume for you to build.
  • Long-lived connections make servers stateful. Plan for idle timeouts, uneven balance, deploys and reconnect storms.
  • To reach a user connected to another server, put a pub/sub backplane or a routing registry behind the connection gateways, and keep a durable log for catch-up.

Check yourself

1. One million clients poll every 5 seconds. Roughly what request rate does the server see, and how long does a new message wait on average?
2. WebSocket connections through your load balancer drop whenever a user is quiet for about a minute. What is the likely cause and fix?
3. Alice's WebSocket is held by gateway 1 and Bob's by gateway 2. Alice sends Bob a message. How does it reach him?
4. A gateway holding 300,000 connections crashes. Two minutes later the rest of the fleet is overloaded and failing too. What went wrong, and what prevents it?
5. Live match scores are pushed to two million browsers. The browsers never send anything after subscribing. Which technique fits best?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is long polling?

The client sends a request and the server holds it open until it has data or a timeout passes, then the client immediately asks again. Delivery is near-instant, at one HTTP request per message.

What does SSE give you that WebSockets do not?

It is ordinary HTTP, the browser reconnects automatically, and it sends the last event id on reconnect so the server can resume. It is one-way and text only.

How does a WebSocket connection start?

As an HTTP/1.1 GET with an Upgrade header. The server replies 101 Switching Protocols, and the same TCP connection then carries two-way WebSocket frames.

Why do long-lived connections need heartbeats?

Load balancers, proxies and NAT devices close idle connections, and a peer can vanish without a clean close. Regular pings keep the path open and detect dead connections.

What is a pub/sub backplane for?

Delivering a message to a user whose connection is held by a different server. Gateways subscribe to channels for the users they hold, and any service can publish without knowing where anyone is connected.

How does a client catch up after a dropped connection?

It reconnects with backoff and jitter and sends the id of the last event it saw. The server replays later events from a durable log, or tells the client to reload state if it is too far behind.

Review the deck