Card 04/ 10
Server-Sent Events: A One-Way Stream to the Browser
One HTTP response that does not end, carrying each update as a few lines of text.
Server-sent events (SSE) let a server push updates to a browser over one HTTP response that does not end. The browser opens it once, and the server writes each event into it as a few lines of text whenever there is news. Data flows one way only, from server to client, and the browser reconnects by itself if the stream drops.
Who starts, and which way. The client opens the stream with an ordinary request. From then on only the server sends. If the client needs to send something, it makes a separate request.
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 1
event: score
data: {"home": 0, "away": 0}
id: 2
event: score
data: {"home": 1, "away": 0}
id: 3
event: score
data: {"home": 1, "away": 1}Reading the stream. Each event is a few field: value lines ended by a blank line. The id matters on reconnect: the browser's EventSource sends the last id it saw in a Last-Event-ID header, so the server can resend what was missed.
What it costs the server. One open response per connected reader, held for as long as they watch. Messages carry no request overhead, so a busy stream is cheap per update.
Use it when
- Only the server has news to send, such as live scores, prices or progress
- Readers are browsers, which reconnect and resume by themselves
- The path already carries ordinary HTTP
Avoid it when
- The client sends often, which needs a two-way connection
- Pages open many streams over HTTP/1.1, where browsers allow about six connections per site and each stream holds one; HTTP/2 lifts this
One product that uses it. The Claude API streams a long answer back as server-sent events, so text appears as it is generated rather than all at once.
So when only the server talks, a stream of server-sent events is the simplest way to deliver news at once, with reconnection built in.
← → move through sections and cards