Server-Sent Events in Vapor
A lot of the servers I build end up with a job that runs longer than the request that started it. It might be a build, or an LLM response that comes back a few tokens at a time. Either way, the client needs a way to follow along.
Polling is what most of us do first. The client asks every couple of seconds and the server mostly says "not yet". It works, but it's wasteful and the updates always feel late. WebSockets fix the lag, but now you have a protocol upgrade and a two-way channel when you only need one direction, and you have to write the reconnect logic yourself.
I think Server-Sent Events get overlooked here. SSE is a regular HTTP request with a response that stays open, and the server writes text events to it as they happen. Browsers have a built-in client called EventSource that reconnects by itself and tells the server the last event it saw. The format is simple too. An event is a line like data: something followed by a blank line.
You can do SSE in Vapor today, but Vapor doesn't have an API for it, so you write the wire format by hand on top of a body stream. I got tired of writing that code, so I pulled it into a library. It started out as vapor-sse. As of 2.0 it also works with Hummingbird, so it's now called swift-sse.
SSE in plain Vapor
Here's an SSE endpoint in Vapor 4 with no library.
app.get("events") { req -> Response in
Response(
status: .ok,
headers: [
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
],
body: .init(managedAsyncStream: { writer in
for i in 0..<10 {
var buffer = ByteBufferAllocator().buffer(capacity: 32)
buffer.writeString("data: tick \(i)\n\n")
try await writer.writeBuffer(buffer)
try await Task.sleep(for: .seconds(1))
}
})
)
}
It works, but there are a few things in there you have to get right every time.
The headers are the easy part. If you leave off text/event-stream, the browser won't treat the response as an event stream. If you leave off no-cache, a proxy might try to cache a response that never ends.
The wire format is harder to get right. Every event has to end with a blank line, so data: tick 0\n\n is correct and data: tick 0\n is wrong. With the second one the client never fires an event, and you don't get an error or a log line anywhere. The connection looks healthy and your UI shows nothing. A newline inside the payload is a problem too, because the client only gets the first line of it. Pretty-printed JSON is full of newlines.
You also need three lines of ByteBuffer code for every event you send. And once you send more than strings, there's a JSONEncoder and a Data to String conversion at every call site.
None of this is hard to write, but it's easy to get slightly wrong, and when you do nothing tells you.
The same endpoint with swift-sse
import Vapor
import SSE
app.get("events") { req in
req.sse { sse in
for i in 0..<10 {
try await sse.send("tick \(i)")
try await Task.sleep(for: .seconds(1))
}
}
}
req.sse sets the headers, opens the body stream, and passes your closure an SSEContext. You call send and the library takes care of the format. The stream stays open for as long as your closure is running. When the closure returns, the stream ends. If it throws, the error ends the stream. I like this because there's no close call to forget about.
Here's the same endpoint in Hummingbird.
import Hummingbird
import SSE
let router = Router()
router.get("events") { request, context in
Response.sse { sse in
for i in 0..<10 {
try await sse.send("tick \(i)")
try await Task.sleep(for: .seconds(1))
}
}
}
The closure and SSEContext are the same in both frameworks. Only the call that creates the response changes. The Hummingbird response also leaves out the Connection header, since HTTP/2 doesn't allow it.
The rest of this post uses Vapor. In Hummingbird, replace req.sse with Response.sse and the rest is the same.
One note on versions. swift-sse 2.x is for Vapor 5 and Hummingbird 2, and 1.x is for Vapor 4. The sse API is the same in both. I wrote the samples in this post against Vapor 4, so the few that touch Vapor directly (the plain endpoint above, the test, and the response header near the end) look a little different on Vapor 5.
The wire format
An event in the SSE spec is a few prefixed lines followed by a blank line. ServerSentEvent models that directly.
public struct ServerSentEvent: Sendable {
public var id: String?
public var event: String?
public var data: String?
public var retry: Int?
public var comment: String?
}
data is the payload. event gives the event a name, so a client can listen for only that kind. id is the value the client sends back when it reconnects, and retry tells the client how many milliseconds to wait before it does. comment is a line the client ignores. I'll come back to that one when we get to keep-alives.
The serializer handles multi-line payloads for you.
if let data {
for line in data.split(separator: "\n", omittingEmptySubsequences: false) {
result += "data: \(line)\n"
}
}
Each line of the payload gets its own data: prefix, which is what the spec asks for, and the client joins them back together with newlines. So you can send pretty-printed JSON or a stack trace and all of it arrives.
Sending JSON
Most of the time you're sending JSON. send takes any Encodable value.
struct Progress: Codable, Sendable {
var step: String
var percent: Int
}
app.get("build", ":id", "progress") { req in
req.sse { sse in
try await sse.send(Progress(step: "resolving", percent: 10))
try await sse.send(Progress(step: "compiling", percent: 60))
try await sse.send(Progress(step: "done", percent: 100))
}
}
The default encoder uses .sortedKeys and .withoutEscapingSlashes, so the output is on one line and the keys are always in the same order. The key order matters for testing, since it lets you compare the exact bytes of a stream.
If your model has dates or you want a different key strategy, pass in your own encoder.
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.keyEncodingStrategy = .convertToSnakeCase
app.get("events") { req in
req.sse(encoder: encoder) { sse in
try await sse.send(Progress(step: "resolving", percent: 10))
}
}
Named events
One stream can carry more than one kind of message. If you give each event a name, the client can listen for each kind separately.
app.get("build", ":id", "progress") { req in
req.sse { sse in
for await update in buildUpdates(for: req.parameters.get("id")!) {
switch update {
case .progress(let p):
try await sse.send(event: "progress", data: p)
case .log(let line):
try await sse.send(event: "log", data: line)
case .finished(let result):
try await sse.send(event: "finished", data: result)
return
}
}
}
}
The return in the last case ends the closure, which ends the stream, and the client sees the response finish normally.
In the browser, each name gets its own listener.
const source = new EventSource("/build/42/progress");
source.addEventListener("progress", (e) => {
const { step, percent } = JSON.parse(e.data);
bar.style.width = `${percent}%`;
label.textContent = step;
});
source.addEventListener("log", (e) => appendLine(e.data));
source.addEventListener("finished", () => source.close());
Pay attention to the last line. EventSource reconnects every time a connection ends, even when the server ended it on purpose, and it keeps doing that until you call close(). So if your stream has a real end, send an event that says so and have the client close the connection.
Keeping the connection alive
Proxies and load balancers close connections that sit idle for too long, and mobile networks do the same. The timeout is usually somewhere between 30 and 90 seconds.
Comments are how you deal with this. The client throws them away, so you can send one any time you have nothing else to say and the connection stays active.
app.get("queue", "watch") { req in
req.sse { sse in
var lastCount = -1
while true {
let count = try await Job.query(on: req.db).filter(\.$state == .pending).count()
if count != lastCount {
try await sse.send(event: "depth", data: ["pending": count])
lastCount = count
} else {
try await sse.sendComment("keep-alive")
}
try await Task.sleep(for: .seconds(15))
}
}
}
SSEContext is Sendable, so you can also pass it to a child task and run a heartbeat next to your real work. This is safe. Each event is serialized up front and goes to the connection in a single write, one event at a time. Two tasks that send at the same time won't end up with one event in the middle of another.
You don't get ordering between tasks tho. If two tasks send at the same moment, either one can go first. If you put an id on events so clients can resume, send those from one task. Sends from a single task stay in order because each await finishes before the next one starts.
The loop above also handles clients that disconnect. There's no callback for that. Once the connection is gone a write will eventually fail, the error gets thrown out of your closure, and the loop stops. So the heartbeat is also how you find out the client left.
Resuming after a reconnect
WebSockets don't give you this one for free. When EventSource reconnects, it sends the last id it received in a Last-Event-ID header. If your events have IDs, you can start from where the client left off.
app.get("build", ":id", "progress") { req in
let lastID = req.lastEventID.flatMap(Int.init) ?? 0
return req.sse { sse in
// Replay anything the client missed.
for entry in await log.entries(after: lastID) {
try await sse.send(ServerSentEvent(
id: String(entry.sequence),
event: "log",
data: entry.text
))
}
// Then send new entries as they arrive, each with its ID.
for await entry in await log.stream() {
try await sse.send(ServerSentEvent(
id: String(entry.sequence),
event: "log",
data: entry.text
))
}
}
}
req.lastEventID is read outside the closure, from the request, since that's where the header is. Every event also needs an id, because the client can only resume from the last ID it got.
ServerSentEvent also has retry, if you want to control how long the client waits before it reconnects.
try await sse.send(ServerSentEvent(retry: 10_000, comment: "backing off"))
I'd use this when a server is overloaded and you want clients to come back in ten seconds, where a browser would normally retry after a few.
Testing
The output is the same on every run, so a test can compare the whole response body against a string. This one is from the 1.x test suite.
@Test func sseNamedEventWithJSON() async throws {
struct Update: Codable, Sendable {
var status: String
}
try await withApp { app in
app.get("events") { req in
req.sse { sse in
try await sse.send(event: "status", data: Update(status: "ok"))
}
}
try await app.testing().test(.GET, "events") { res async in
#expect(res.body.string == "event: status\ndata: {\"status\":\"ok\"}\n\n")
}
}
}
app.testing() collects the full body, so a stream that ends is tested like any other route. You don't need a real client or a parser. This is why the default encoder sorts keys.
If a route streams forever, give it a way to stop in tests. A bounded loop works, or a cancellation that the test triggers.
Before you deploy
There are two things I'd check before this goes to production.
The first is proxy buffering. nginx buffers proxied responses by default. With SSE that means your events sit in the buffer and arrive all at once when it fills up or the connection closes, and from the client it looks like the server never sent anything. In Vapor 4, Response is a class with mutable headers, so you can turn buffering off for a route.
app.get("events") { req -> Response in
let response = req.sse { sse in
try await sse.send("hello")
}
response.headers.add(name: "X-Accel-Buffering", value: "no")
return response
}
Vapor 5 made Response a struct with HTTPFields headers, so the code looks a little different there, but the header is the same.
nginx isn't the only one. Cloudflare and ALB each handle streaming responses in their own way, so check whatever sits in front of your app.
The second is connection limits. Every open stream holds a connection for as long as it lives. Over HTTP/1.1 a browser only allows six connections per origin, and SSE streams count against that. HTTP/2 multiplexes streams over one connection, which removes the limit, so make sure it's turned on. On the server, a few thousand idle streams still use real memory and file descriptors, so plan for that.
Reading the stream from Swift
Browsers have EventSource. On Apple platforms, URLSession.bytes(for:) gets you a basic client in about twenty lines.
var request = URLRequest(url: url)
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
let (bytes, _) = try await URLSession.shared.bytes(for: request)
var line = [UInt8]()
var data = ""
for try await byte in bytes {
guard byte == UInt8(ascii: "\n") else {
line.append(byte)
continue
}
let text = String(decoding: line, as: UTF8.self)
line.removeAll(keepingCapacity: true)
if text.isEmpty {
// A blank line ends the event.
if !data.isEmpty { handle(data) }
data = ""
} else if text.hasPrefix("data:") {
let value = text.dropFirst(5).drop(while: { $0 == " " })
data += data.isEmpty ? value : "\n" + value
}
}
I read bytes here and split the lines myself. bytes.lines looks like the obvious choice, but it skips blank lines, and the blank line is how you know an event ended.
This only handles data. A full client also tracks event and id, and reconnects with Last-Event-ID. It can be this short because SSE is text over a normal HTTP response.
Try it
.package(url: "https://github.com/kylebrowning/swift-sse.git", from: "2.0.0")
That gets you the Vapor 5 API, which is the default. For Hummingbird, turn on the Hummingbird trait.
.package(
url: "https://github.com/kylebrowning/swift-sse.git",
from: "2.0.0",
traits: ["Hummingbird"]
)
A trait list replaces the default, so SwiftPM never resolves Vapor in a Hummingbird project. If you're on Vapor 4, use from: "1.0.0" and you'll stay on 1.x.
2.x needs Vapor 5.0.0-beta.4 or newer with Swift 6.4, or Hummingbird 2 with Swift 6.2. 1.x needs Vapor 4.121.3 or newer and Swift 6. The README has the full version table. If you already depend on vapor-sse, the old URL redirects to the new repo, so your manifest keeps working.
The core of the library doesn't import a web framework, and each framework's API is one small file behind a package trait. The whole library is six files and about four hundred lines, so you can read all of it in a few minutes. I kept it small on purpose. The SSE spec is small, and I didn't think the library needed to be any bigger.
If you have a use case it doesn't cover, please open an issue, because that's the feedback I want most right now. It's MIT licensed and lives at github.com/kylebrowning/swift-sse.
If you only need to push updates from the server to the client, try SSE before you reach for a WebSocket.