Real-time APIs
medium 27 minHTTP lets the client ask and the server answer.
Video lesson · Chapter 1 of 6
Short polling spends requests on silence
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
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.
April 2011
RFC 6202 collects the known issues and good habits of long polling and HTTP streaming.
December 2011
RFC 6455 standardises the WebSocket protocol.
2015
Server-Sent Events becomes a W3C Recommendation on 3 February. Today the WHATWG HTML standard maintains it.
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.
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?
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
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
| Use | What flows | Usually |
|---|---|---|
| Chat | Messages both ways | WebSocket |
| Live dashboards and tickers | Values to the client | SSE |
| Multiplayer games | Positions and actions, many a second | WebSocket, or WebRTC data channels when old positions may be lost |
| Notifications | Rare, short | SSE, or the phone's push service when the app is closed |
| Editing together | Small changes both ways | WebSocket |
| Location tracking | Positions up, map down | POST up and SSE down, or WebSocket |
| Live video | Large media | Not these: media protocols such as HLS or WebRTC. Chat beside it: WebSocket |
| Devices and sensors | Small readings | MQTT or WebSocket |
| Generated text | Words as they come | SSE |
Way 1
Long polling
One message, then silence
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.
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| Field | Meaning |
|---|---|
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 |
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");Drop and resume
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:
EventSourcecannot set them. Use a cookie orfetch - Internet Explorer and Edge before version 79
Way 3
WebSocket
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 life of a connection
Events in the browser
| Event | When |
|---|---|
onopen | Connected, you may send |
onmessage | A message arrived |
onerror | Something failed. No details for the page |
onclose | Closed, 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
| WebSocket | SSE | Long polling | |
|---|---|---|---|
| Direction | Both ways | Server to client | Server to client |
| Protocol | ws, wss (after an HTTP handshake) | HTTP | HTTP |
| Data | Text and binary | UTF-8 text | Anything |
| Reconnect | You write it | Built in | You write it |
| Resume | You write it | Last-Event-ID, if the server kept events | Cursor |
| Browsers | All modern ones | All modern ones, not Internet Explorer | All |
| Networks | Some proxies block it; wss helps | Passes, if nothing buffers | Passes |
| Per idle client | One connection | One connection | One connection and a request every 30 to 60 s |
| Effort | Highest | Low | Medium |
Choose
Correctness
Reconnect and catch up
- 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
Save before sending
The store is the truth. The live push is only the fast way.
- 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
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
Two servers and pub/sub
Connections and memory
Fan-out is the real load
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
| Way | Examples |
|---|---|
| WebSocket | Slack and Discord offer WebSocket connections for apps and bots. Editors such as Figma, trading screens and browser games |
| SSE | Streaming answers of language models (OpenAI's API documents it), build logs, live scores |
| Long polling | Fallback 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.