Live updates: SSE and WebSockets
IntermediateHow a server sends news the moment it happens: polling, a stream of Server-Sent Events, and a WebSocket that talks both ways after one HTTP request.Builds on HTTP requests and responses
GET /scores HTTP/1.1Host: live.exampleAccept: text/event-stream HTTP/1.1 200 OKContent-Type: text/event-stream data: {"home":1,"away":0} GET /chat HTTP/1.1Host: live.exampleUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Empty
Spaceplay or pause←→previous or next stepRback to the start
Explanation
3 min read
On this page
How can a server send updates to the browser?
In HTTP the browser asks and the server answers; a server cannot start a conversation. For live scores, chats, notifications or a shared document, the page needs news the moment it happens. There are three common ways to get it:
- Polling. Ask again every few seconds. Simple, but most answers say "nothing new", and news waits until the next question.
- Server-Sent Events (SSE). One request whose response never finishes: the server writes an
event into it whenever there is news. The page reads them with
EventSource. - WebSockets. One request that upgrades the connection into a two-way channel, where both
sides send small whenever they like. The page uses
WebSocket.
How do SSE and WebSockets work underneath?
- SSE is plain HTTP. The response has
Content-Type: text/event-stream, and each event is a fewfield: valuelines (data:,id:,event:) ended by a blank line. If the connection drops,EventSourcereconnects by itself and sendsLast-Event-ID, so the server can resume. - A WebSocket starts as HTTP. The
GETcarriesUpgrade: websocketand a randomSec-WebSocket-Key. The server answers101 Switching ProtocolswithSec-WebSocket-Accept, a hash of that key, and from then on the connection carries WebSocket frames, not HTTP. - Frames are small. A text message costs only a few bytes of framing, with no headers or cookies repeated on every message. Ping and pong frames keep an idle connection alive, and a close frame ends it cleanly.
- Choosing. Use SSE when only the server talks, such as scores, notifications or a progress bar: it works with ordinary HTTP servers and reconnects by itself. Use a WebSocket when the browser sends often too, such as chats, games or collaborative editing.
What do people get wrong about live updates?
Mini example
A stream can name its events and number them. The page listens with
source.addEventListener('goal', …), and after a reconnect the browser sends the last id it saw:
GET /scores HTTP/1.1Host: live.exampleAccept: text/event-streamLast-Event-ID: 2 HTTP/1.1 200 OKContent-Type: text/event-stream id: 3event: goaldata: {"home":2,"away":1,"minute":78} Quick check
A dashboard only needs to show new orders as they arrive. Which fits best?
Further reading
All steps as text
- Step 1:
A live score page wants to show a goal the moment it happens. In HTTP the server can only answer, so the simplest trick is polling: ask again every few seconds.
- Step 2:
Most of those answers say nothing new, and a goal can wait seconds to show. With Server-Sent Events, the page opens one request instead and asks for a stream.
Lines 1–3
- Step 3:
The server answers with
text/event-streamand then simply doesn’t finish the response. The connection stays open, waiting for news.Lines 5–6
- Step 4:
Goal! The server writes an event into the open response: a
data:line and a blank line. The page’sEventSourcefires at once.Line 8
- Step 5:
More events follow on the same response. Each can carry an
id; if the connection drops, the browser reconnects by itself and says where it stopped. - Step 6:
SSE only goes from server to browser. A chat needs both ways, so it opens a WebSocket, which starts as an ordinary GET asking to
Upgrade.Lines 10–15
- Step 7:
The random key lets the browser check that it is talking to a real WebSocket server. CORS doesn’t cover WebSockets, so the server must check
Originitself.Line 14
- Step 8:
101 Switching Protocols: the accept value is a hash of the key, and from now on this connection no longer speaks HTTP. Both sides can send whenever they like.Lines 17–20
- Step 9:
Sara types “Hi all” and the page calls
socket.send(). It travels as a small frame: no request line, no headers, just a few bytes around the text. - Step 10:
Another visitor has a WebSocket open to the same server. The server pushes Sara’s message to them right away, without being asked.
- Step 11:
They reply, and the server passes it on to Sara. Messages go both ways on the same connections, at any moment.
- Step 12:
When the chat is quiet, the server sends a ping and the browser answers pong by itself. That keeps routers and proxies from dropping an idle connection.
- Step 13:
Sara closes the tab. The browser sends a close frame, the server answers with one, and the connection ends cleanly.
- Step 14:
Polling asks again and again, SSE keeps one HTTP response open for news from the server, and a WebSocket turns one request into a two-way channel.