HTTP
Server-Sent Events
Push live updates from the server to a browser over plain HTTP.
Normally the browser asks and the server answers. With Server-Sent Events (SSE) the browser opens one request and the server keeps it open, sending a message whenever it likes: a progress bar, live prices, a notification feed. It is simpler than a WebSocket when data flows only server to browser, and it reconnects by itself if the connection drops.
@Get("/events")
fun events() = SseStream { out ->
repeat(10) {
out.send("tick $it", event = "tick") // data: tick 0 / event: tick
Thread.sleep(1000)
}
}const es = new EventSource("/events");
es.addEventListener("tick", (e) => console.log(e.data)); // "tick 0", "tick 1", ...
es.onerror = () => console.log("connection lost, the browser reconnects");SseEmitter offers send(data, event), send(ServerSentEvent(data, event, id, retry)) and comment(text) (a keep-alive line). The response ends when the block returns.
A realistic example: order tracking
@Get("/orders/{id}/track")
fun track(@Param id: String) = SseStream { out ->
var last = ""
while (true) {
val status = orders.statusOf(id)
if (status != last) { out.send(status, event = "status"); last = status }
if (status == "DELIVERED") break
else out.comment("keep-alive")
Thread.sleep(2000)
}
}Notes
- Each open stream holds a virtual thread, which is cheap, so thousands of open streams are fine.
- Send a
comment("keep-alive")every 15 to 30 seconds so proxies and load balancers do not close an idle stream. - With several instances, produce events from a shared source (a queue, Redis pub/sub) rather than in-memory state of one instance.
- Authenticate the stream like any request (cookie or header); the browser's
EventSourcecannot set custom headers, so use cookies or a short-lived token in the URL. - SSE over HTTP/2 is not covered; use HTTP/1.1 for streams.
SSE or WebSocket?
| SSE | WebSocket | |
|---|---|---|
| direction | server to browser | both ways |
| works through ordinary proxies | yes | usually, with configuration |
| auto-reconnect | built in | you write it |
| use for | notifications, progress, feeds | chat, games, collaboration |