Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท WebSockets and SSE

Server-Sent Events (SSE) in Ktor - Live Streams over HTTP

Stream live updates from a Ktor server to the browser with Server-Sent Events. Learn the text/event-stream format, the sse route, reconnects and Last-Event-ID, and compare SSE with WebSockets.

Not every real-time feature needs a two-way connection. A progress bar, a stock ticker, a build log, a notification badge: the server pushes updates, and the client only listens. For that one-way case there is a simpler, older tool than WebSockets: Server-Sent Events (SSE). It is plain HTTP, the response just never ends, and the browser has a built-in EventSource class that reconnects by itself.

Ktor supports SSE with its own plugin and a route builder called sse. This lesson covers the wire format first (because it is tiny and you can run code that produces it), then the Ktor API, reconnect handling, and a comparison with WebSockets.

The wire format

An SSE response has the content type text/event-stream. The body is text, made of events separated by a blank line. Each event has lines with a field name, a colon and a value:

TEXT
id: 41
event: price
data: {"symbol":"KT","price":101.5}

data: first line
data: second line

: this is a comment, used as a keep-alive

  • data: is the payload; several data: lines are joined with newlines.
  • event: names the event type (default is message).
  • id: sets the last event id. If the connection drops, the browser reconnects and sends the header Last-Event-ID so the server can resume.
  • retry: suggests a reconnect delay in milliseconds.
  • A line starting with : is a comment, handy as a heartbeat.

In the browser:

JavaScript
const source = new EventSource("/events");
source.addEventListener("price", e => console.log(JSON.parse(e.data)));
source.onerror = () => console.log("lost connection; the browser will retry");

Producing the format yourself

Kotlin Format Kotlin values as SSE events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The data text can contain newlines, so the encoder writes one data: line per line. The browser glues them back together with \n. Forgetting that rule is a classic bug: a raw newline inside a single data: line ends the event early.

The sse route in Ktor

Kotlin
dependencies {
    implementation("io.ktor:ktor-server-sse:$ktorVersion")
}

fun Application.module() {
    install(SSE)
    routing {
        sse("/clock") {
            repeat(10) { n ->
                send(ServerSentEvent(data = "tick $n", event = "tick", id = n.toString()))
                delay(1.seconds)
            }
        }
    }
}

The block is a coroutine, exactly like a WebSocket session, but with send only (no incoming). When the block ends, Ktor completes the response and the browser's EventSource will reconnect after a short delay, which may not be what you want. To tell the browser to stop, close the stream with a final event of your own, such as event: done, and call source.close() on the client. Also remember that each open stream holds one connection per viewer, so plan for that in your proxy and file-descriptor limits.

Sending a live Flow is a natural fit:

Kotlin
sse("/prices") {
    prices.collect { quote ->
        send(ServerSentEvent(Json.encodeToString(quote), event = "price"))
    }
}

When the client goes away, the coroutine is cancelled, collect stops, and finally blocks run. Collecting a SharedFlow this way is how one producer feeds thousands of viewers, as the next lesson shows with channels and broadcasting.

Resuming with Last-Event-ID

Networks fail. A good SSE endpoint numbers its events and replays what a returning client missed. The browser sends Last-Event-ID: 41; the server then streams events with a higher id first.

Kotlin Stand-in: replay missed events after a reconnect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The client received events 1 to 3, lost the connection, and when it came back with Last-Event-ID: 3 it got 4, 5 and the update that happened during the outage. In Ktor you read the header with call.request.headers["Last-Event-ID"] inside the sse block.

Send a comment line (: ping) every 15 to 30 seconds. Proxies and load balancers close connections that stay silent, and the heartbeat also lets your server notice dead clients quickly.

SSE or WebSockets?

SSE WebSocket
Direction Server to client Both ways
Protocol Plain HTTP, works with normal proxies and HTTP/2 Upgrade to its own protocol
Reconnect Built into EventSource, with Last-Event-ID You write it
Data Text only Text and binary
Auth Cookies and headers through normal HTTP (with fetch streaming) Cookie or token tricks
Good for Feeds, notifications, progress, logs, dashboards Chat, games, collaborative editing

A good rule: start with SSE when the browser only needs to receive. Use ordinary POST requests for the rare messages the client sends. Switch to WebSockets when the client sends messages frequently or you need binary data.

Common mistakes

  • Buffering proxies. nginx buffers responses by default; set proxy_buffering off (or send X-Accel-Buffering: no) so events arrive immediately.
  • Compression on a stream. Gzip waits for a full buffer; disable compression for the event stream route.
  • No heartbeat. Idle streams are killed silently.
  • Unbounded history. Keep a bounded replay buffer, not the whole log in memory.
  • Too many connections per browser. Over HTTP/1.1 browsers allow about six connections per host; HTTP/2 removes that limit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What ends one event in the text/event-stream format?

    Events are separated by an empty line; field lines come before it.
  2. 2. What does the browser send when EventSource reconnects?

    That header lets the server resume from the right place.
  3. 3. Which feature is best served by SSE rather than WebSockets?

    Progress only flows from server to client, so SSE is simpler.
  4. 4. Why send a comment line like : ping periodically?

    Comments are ignored by the client but keep the connection active.

Summary

  • SSE streams text/event-stream text over plain HTTP; events end with a blank line.
  • Fields are data, event, id and retry; multi-line data needs one data: line per line.
  • Ktor's sse route is a coroutine that sends ServerSentEvent objects; a Flow is a natural source.
  • EventSource reconnects automatically and sends Last-Event-ID, so number events and replay.
  • Turn off proxy buffering and compression for the stream, and send heartbeats.

Next: Channels and Broadcasting