AlgoViz

Real-time APIs

medium 27 min

HTTP lets the client ask and the server answer.

Video lesson · Chapter 1 of 6

Short polling spends requests on silence

0:00 / 4:43

Polling vs SSE vs WebSocket

1:19Reel

Theory

Read or listen first. About 2 min.

What it is

In plain HTTP the client speaks first and the server answers. A real-time API lets the server deliver news the moment it exists: a chat message, a price, the position of a driver, the next word of a generated text.

There are three usual ways. Long polling is a question that waits for its answer. Server-sent events (SSE) is one answer that never ends. WebSocket is a connection on which both sides speak whenever they like.

Why it exists

Without them the client has to ask again and again. That wastes requests when nothing has changed, and is late when something has. The more often you ask, the more you waste; the less often, the later you are.

An open connection removes that trade, and brings a new one: the server must now remember who is connected, notice dead connections, and bring people up to date when they return.

A short history

  1. 2006

    Alex Russell gives the name Comet to the tricks, such as long polling, that let a server push data to a web page. In September the Opera browser implements an early form of server-sent events.

  2. April 2011

    RFC 6202 collects the known issues and good habits of long polling and HTTP streaming.

  3. December 2011

    RFC 6455 standardises the WebSocket protocol.

  4. 2015

    Server-Sent Events becomes a W3C Recommendation on 3 February. Today the WHATWG HTML standard maintains it.

  5. 2018

    RFC 8441 describes WebSocket over a single stream of an HTTP/2 connection.

Words to know

Full duplex
Both sides can send at the same time.
Handshake
The first exchange that sets up a connection.
Frame
One unit of data on a WebSocket: text, binary, ping, pong or close.
Heartbeat
A small regular message that shows the other side is alive.
Cursor
The number of the last message a client has seen.
Fan-out
One message delivered to many receivers.
Backpressure
Slowing or dropping when a receiver cannot keep up.

How it works

Step through the idea, or press Play.

Step 1 of 3

Keep a way open. A held request, a stream or a two-way connection

Understand it

Start here

Is the soup ready?

A child plays in a treehouse, and the soup is cooking in the kitchen. How does the news get up the ladder?

The treehouse and the kitchen
KitchenReady?NoRun and ask: 4 trips

Notice what never changes: the cook must remember the notes, or nothing can be caught up.

The idea

Asking or being told

Push

  • Delivered as soon as the data is ready
  • No empty answers
  • The server holds a connection per client
  • Needs reconnecting and catching up

Polling every second

  • 304, 304, 200, 304: mostly nothing new
  • Late by up to one interval
  • Load grows with clients, not with news
  • But simple, stateless and easy to cache

What polling costs

100,000 clients5 s=20,000 requests/saverage delay=5 s2=2.5 s\frac{100{,}000\ \text{clients}}{5\,\text{s}} = 20{,}000\ \text{requests/s} \qquad \text{average delay} = \frac{5\,\text{s}}{2} = 2.5\,\text{s}
With 100,000 open pages. If each gets one message a minute, push needs only about 1,667 sends a second.

Choosing between pull and push in general, including feeds and notifications, is the topic of push vs pull. When the receiver is another company's server, use a webhook.

Uses

Where it matters

UseWhat flowsUsually
ChatMessages both waysWebSocket
Live dashboards and tickersValues to the clientSSE
Multiplayer gamesPositions and actions, many a secondWebSocket, or WebRTC data channels when old positions may be lost
NotificationsRare, shortSSE, or the phone's push service when the app is closed
Editing togetherSmall changes both waysWebSocket
Location trackingPositions up, map downPOST up and SSE down, or WebSocket
Live videoLarge mediaNot these: media protocols such as HLS or WebRTC. Chat beside it: WebSocket
Devices and sensorsSmall readingsMQTT or WebSocket
Generated textWords as they comeSSE

Way 1

Long polling

One message, then silence

Ask, hold up to 30 seconds (some hold 60), answer with data or with nothing, ask again at once.

Good for

  • Old browsers and strict company networks
  • A fallback when WebSocket is blocked
  • Rare updates
  • Ordinary HTTP tools, logs and security

Costs

  • A full request per message or timeout
  • One message behind another: up to three network trips in a burst
  • Each client still holds a connection
  • Timeouts must be shorter than those of every proxy on the way

Way 2

Server-sent events

One ordinary GET with an answer of type text/event-stream that does not end. The browser's EventSource reads it, reconnects by itself and remembers the last id.

Text
GET /events HTTP/1.1Accept: text/event-streamHTTP/1.1 200 OKContent-Type: text/event-streamCache-Control: no-cacheretry: 5000event: messageid: 1data: {"user": "asha", "text": "Hello!"}event: notificationid: 2data: {"type": "alert", "message": "New order received"}: a comment, ignored by the client, good as a heartbeat
A blank line ends each event.
FieldMeaning
event:Type of the event (optional, default message)
id:Remembered, and sent back after a drop as Last-Event-ID
data:The payload. Several data lines are joined with line breaks
retry:How many milliseconds to wait before reconnecting
:A comment. Every 15 seconds or so it keeps proxies awake
JavaScript
const source = new EventSource("/events");source.onopen = () => console.log("connected");source.onmessage = (e) => console.log("message", e.data);source.addEventListener("notification", (e) => console.log("notification", e.data));source.onerror = () => console.log("lost, the browser will try again");
The browser sends the last id. The server must still have kept the events to send them again.

Drop and resume

The browser does its half by itself. Keeping 43 and 44 is your half.

Good for

  • News feeds, scores, tickers
  • Logs and build output
  • Progress of a long job
  • Notifications
  • Text that is generated word by word

Not for

  • Client to server: use a normal POST beside it
  • Binary data: it is UTF-8 text
  • More than 6 streams per browser and site on HTTP/1.1. HTTP/2 lifts this
  • Custom headers: EventSource cannot set them. Use a cookie or fetch
  • Internet Explorer and Edge before version 79

Way 3

WebSocket

HTTP
GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeOrigin: https://app.example.comSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The example values of RFC 6455. The accept value proves that the server understood WebSocket; it is not a password. Use wss, which is WebSocket over TLS.

The life of a connection

In the browser these are readyState 0, 1, 2 and 3. A closed WebSocket is never opened again: you make a new one.

Events in the browser

EventWhen
onopenConnected, you may send
onmessageA message arrived
onerrorSomething failed. No details for the page
oncloseClosed, with a code and a reason
  • Heartbeat

    The server sends a ping frame, for example every 30 seconds, and the browser answers pong by itself. No pong: close. Page code cannot send ping frames, so a client check needs an ordinary message.

  • Who is it?

    Check the user at the handshake (cookie, or a short ticket) and check the Origin header, or another site can connect with the user's cookie.

  • Slow readers

    Limit the buffer for each client. Merge, drop or close. They can catch up later.

  • Your own rules

    There is no request and answer built in. Put an id and a type in every message, and acknowledge what matters.

Good for

  • Chat
  • Multiplayer games
  • Editing together
  • Trading screens with orders
  • Anything both ways and frequent

Too much for

  • Updates from the server only: SSE
  • Rare updates: polling
  • Simple notifications
  • Request and answer: plain HTTP, with its caching and status codes

Compare

Side by side

WebSocketSSELong polling
DirectionBoth waysServer to clientServer to client
Protocolws, wss (after an HTTP handshake)HTTPHTTP
DataText and binaryUTF-8 textAnything
ReconnectYou write itBuilt inYou write it
ResumeYou write itLast-Event-ID, if the server kept eventsCursor
BrowsersAll modern onesAll modern ones, not Internet ExplorerAll
NetworksSome proxies block it; wss helpsPasses, if nothing buffersPasses
Per idle clientOne connectionOne connectionOne connection and a request every 30 to 60 s
EffortHighestLowMedium
All three hold a connection per client, so the number of connections is not the difference. Long polling adds request overhead; WebSocket adds a protocol of your own.

Choose

Libraries often start with long polling and move up to WebSocket when that works.

Correctness

Reconnect and catch up

  1. 1

    Number the messages

    One growing number per room or user, given by the store. Times are a poor choice: two messages can have the same one.

  2. 2

    Save before sending

    The store is the truth. The live push is only the fast way.

  3. 3

    Subscribe, then read history

    Start collecting live messages, read everything after the cursor, send the history, then the collected ones. Skip numbers already sent.

  4. 4

    Wait a random time before reconnecting

    Growing up to a limit, for example a random value between 0 and min(30, 2^tries) seconds.

Scale

From one server to many

One server

Clients A, B and C each hold an open connection to one connection server, which keeps the sockets in memory.
Everybody is in the same memory. A broadcast is a loop over the connections.

Two servers and pub/sub

Client A sends a message to connection server 1, which holds A. Server 1 saves it in a message store for catching up, and publishes it to Redis pub/sub by room. Pub/sub delivers it to connection server 2, which holds B, and server 2 pushes it to client B.
Each connection server subscribes only to the rooms of the clients it holds.

Connections and memory

100,000×50 KB=5 GB100,00030 s≈3,333 heartbeats/s100{,}000 \times 50\,\text{KB} = 5\,\text{GB} \qquad \frac{100{,}000}{30\,\text{s}} \approx 3{,}333\ \text{heartbeats/s}
Assumption: 50 KB per connection with buffers and TLS. Measure your own. File descriptor limits must be raised too.

Fan-out is the real load

10 messagess×10,000 people in a room=100,000 sends/s10\ \tfrac{\text{messages}}{\text{s}} \times 10{,}000\ \text{people in a room} = 100{,}000\ \text{sends/s}
Big rooms, not many rooms, hurt. Merge updates, sample, or let people pull.
  • Load balancer

    Long connections stay where they are. New servers fill slowly, so balance by number of connections, and raise idle timeouts.

  • Deployments

    Closing a server closes its clients. Drain slowly and let clients return at random times.

  • Presence

    Who is online: a key per client with a short life, renewed by heartbeats.

  • Closed apps

    A phone in a pocket has no socket. Use the push service of the platform, and catch up on opening.

Splitting traffic in general: load balancing. Durable streams instead of fire-and-forget pub/sub: queues.

In practice

Who uses what

WayExamples
WebSocketSlack and Discord offer WebSocket connections for apps and bots. Editors such as Figma, trading screens and browser games
SSEStreaming answers of language models (OpenAI's API documents it), build logs, live scores
Long pollingFallback of real-time libraries, Telegram's bot API (getUpdates), Amazon SQS receive with a wait time

Summary

The whole topic in one minute.

Ask who needs to speak. Only the server: SSE. Both, often: WebSocket. Old networks, or very rare news: long polling or plain polling. The delay is about the same for all push methods; the differences are direction, data type, reconnecting and what the network allows.

Connections always break, so number the messages, keep a history and let clients resume. With more than one server, pub/sub carries a message to the server that holds the receiver. And plan for the moment when everybody reconnects at once.

  • Short polling asks often, long polling waits, SSE streams one way, WebSocket works both ways.
  • Server to client only: start with SSE. Both ways and often: WebSocket. Minutes are fine: poll.
  • Connections always break: number, save, resume, and reconnect at random times.
  • With many servers, save the message, publish it, and let the server that holds the receiver push it.
  • Plan for slow readers, big rooms, deployments and the Origin check.

Sources