Skip to content

Server-sent events and WebSockets

The Relay dashboard shows job status, and today it polls GET /jobs/:id every two seconds for every visible job. Fifty open dashboards make twenty-five requests a second that mostly answer “no change”. The server knows the moment a job changes, so it should say so.

HTTP has two ways to push. Server-sent events (SSE) keep one response open and write events into it. It goes one way, from the server to the client, over plain HTTP. A WebSocket is a two-way channel that starts as an HTTP request and then stops being HTTP. Relay uses SSE for “tell me everything” and a WebSocket where the client also needs to talk (“now watch job 7, stop watching job 3”).

An SSE response has the content type text/event-stream, and its body is text in a fixed format. An event is a few field: value lines, and a blank line ends it:

Terminal window
retry: 1000
id: 3
event: job
data: {"id":3,"jobId":"j1","status":"done"}
: a comment line, ignored by clients (useful as a heartbeat)
  • data: is the payload. Relay sends JSON. A payload may span several data: lines.
  • event: names the event type, so the client can listen for job separately.
  • id: is the event’s id. The client remembers the last one it saw.
  • retry: tells the client how many milliseconds to wait before it reconnects.
  • A line starting with : is a comment. A comment every 15 seconds keeps proxies from closing an idle stream. Bun.serve also closes a connection after 10 seconds without traffic by default, so on Bun send the heartbeat more often than that, raise idleTimeout, or call server.timeout(request, 0) for the stream’s request.

Framing is a pure function, so test it on its own:

interface JobEvent {
readonly id: number
readonly jobId: string
readonly status: "queued" | "running" | "done" | "failed"
}
function formatSse(event: JobEvent): string {
return `id: ${event.id}\nevent: job\ndata: ${JSON.stringify(event)}\n\n`
}

JSON.stringify never emits a raw newline, so data: stays on one line. The final \n\n is the part people forget, and without it the client never sees the event.

A Response takes a ReadableStream as its body (see Web Streams). Keep the stream’s controller, and enqueue bytes into it whenever an event happens:

const encoder = new TextEncoder()
const streams = new Set<ReadableStreamDefaultController<Uint8Array>>()
function events(): Response {
const ref: { controller?: ReadableStreamDefaultController<Uint8Array> } = {}
const body = new ReadableStream<Uint8Array>({
start(controller) {
ref.controller = controller
streams.add(controller)
controller.enqueue(encoder.encode("retry: 1000\n\n"))
},
cancel() {
if (ref.controller !== undefined) streams.delete(ref.controller)
},
})
return new Response(body, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } })
}
function broadcast(frame: string): void {
const bytes = encoder.encode(frame)
for (const controller of streams) {
try {
controller.enqueue(bytes)
} catch {
streams.delete(controller) // the stream is already closed
}
}
}

Two details matter here. cancel() runs when the client disconnects, so forget the controller there. Otherwise streams grows with every dead tab and enqueue throws on closed streams. And the first enqueue is not decoration: with an empty body Bun does not send the response headers until the first byte, so a client calling fetch() would wait for the first event before it saw the response. Writing retry: straight away sends the headers at once.

Connections drop: a laptop sleeps, a deploy restarts the server. A browser’s EventSource reconnects by itself after the retry delay, and sends the id of the last event it saw in the Last-Event-ID header. The server’s job is to replay what the client missed:

declare const history: readonly { readonly id: number }[]
function parseLastEventId(header: string | null): number {
if (header === null) return 0
const id = Number(header)
return Number.isInteger(id) && id > 0 ? id : 0
}
function missed(request: Request) {
const lastId = parseLastEventId(request.headers.get("last-event-id"))
return history.filter((event) => event.id > lastId)
}

The header comes from the network, so it is string | null and can say anything ("abc", "-4"). Parse it like any other input: bad values mean “start from the beginning”. This only works if ids grow with every event, and if the server keeps enough history. Relay keeps all events in memory, which is fine for a lesson. A real server would keep the last few thousand, or a database, and decide what to do when the client’s id is older than anything it kept.

The browser side needs no library:

const source = new EventSource("/events")
source.addEventListener("job", (message) => {
const event = JSON.parse(message.data) // still unknown: decode it as in lesson 2
console.log(event)
})

EventSource can only send GET and cannot set headers, which is a reason to use a WebSocket when you need to authenticate with something other than a cookie.

A WebSocket starts as a GET with Upgrade: websocket. In a route you call server.upgrade(request). If it returns true, Bun has taken the connection over, and the handler returns nothing. After that the websocket handlers get the messages, not the routes:

interface WsData {
readonly clientId: string
}
const server: Bun.Server<WsData> = Bun.serve({
port: 0,
routes: {
"/ws": (request, srv) => {
if (srv.upgrade(request, { data: { clientId: crypto.randomUUID() } })) return undefined
return new Response("upgrade failed", { status: 400 })
},
},
websocket: {
open(ws) {
ws.send(JSON.stringify({ hello: ws.data.clientId }))
},
message(ws, message) {
// `message` is string | Buffer: a text frame or a binary frame
ws.send(typeof message === "string" ? message : "binary frames are not supported")
},
close(ws, code, reason) {
console.log(ws.data.clientId, "left", code, reason)
},
},
})
await server.stop(true)

data is per-connection state that you attach at upgrade time and read as ws.data. Annotating the server as Bun.Server<WsData> is how TypeScript learns its type. Without the annotation, upgrade(request, { data }) is an error.

A job-status feed is “send this to everyone who watches job 7”. Bun has that built in. A socket subscribes to a topic (any string), and server.publish(topic, data) sends to all subscribers:

const server = Bun.serve({
port: 0,
fetch: () => new Response("n"),
websocket: {
message(ws, message) {
if (message === "watch") ws.subscribe("job:j1")
if (message === "unwatch") ws.unsubscribe("job:j1")
},
},
})
server.publish("job:j1", JSON.stringify({ type: "event" }))
await server.stop(true)

Bun cleans up a closed socket’s subscriptions for you. Without topics, Relay would keep its own Map<jobId, Set<ws>> and remove sockets on close: the same leak as the dead SSE streams above.

Both directions carry JSON, and each direction has a closed set of messages. Make them types, as in discriminated unions:

type JobStatus = "queued" | "running" | "done" | "failed"
interface JobEvent {
readonly id: number
readonly jobId: string
readonly status: JobStatus
}
type ClientMessage =
| { readonly type: "subscribe"; readonly jobId: string }
| { readonly type: "unsubscribe"; readonly jobId: string }
type ServerMessage =
| { readonly type: "subscribed"; readonly jobId: string }
| { readonly type: "unsubscribed"; readonly jobId: string }
| { readonly type: "event"; readonly event: JobEvent }
| { readonly type: "error"; readonly reason: "bad_json" | "bad_message" }
function describe(message: ServerMessage): string {
switch (message.type) {
case "subscribed":
return `watching ${message.jobId}`
case "unsubscribed":
return `stopped ${message.jobId}`
case "event":
return `${message.event.jobId} is ${message.event.status}`
case "error":
return `server rejected a frame: ${message.reason}`
}
}

Add a message to the union, and every switch that lacks a case stops compiling. That is the reason to write a protocol as a union and not as a pile of if (msg.type === ...) checks.

The types above describe what you send. What arrives is bytes. A client can send a binary frame, invalid JSON, or valid JSON of the wrong shape, and the server must survive all three. It is the same boundary as lesson 2, on a socket:

type ClientMessage =
| { readonly type: "subscribe"; readonly jobId: string }
| { readonly type: "unsubscribe"; readonly jobId: string }
type Parsed =
| { readonly ok: true; readonly value: ClientMessage }
| { readonly ok: false; readonly reason: "bad_json" | "bad_message" }
function parseClientMessage(data: string | Buffer): Parsed {
if (typeof data !== "string") return { ok: false, reason: "bad_message" }
let json: unknown
try {
json = JSON.parse(data)
} catch {
return { ok: false, reason: "bad_json" }
}
if (typeof json !== "object" || json === null) return { ok: false, reason: "bad_message" }
const type: unknown = Reflect.get(json, "type")
const jobId: unknown = Reflect.get(json, "jobId")
if (typeof jobId !== "string" || jobId === "") return { ok: false, reason: "bad_message" }
if (type === "subscribe") return { ok: true, value: { type, jobId } }
if (type === "unsubscribe") return { ok: true, value: { type, jobId } }
return { ok: false, reason: "bad_message" }
}

type === "subscribe" narrows type from unknown to the literal, so { type, jobId } is a valid ClientMessage with no cast. When parsing fails, reply with an error message and keep the socket open. Closing it makes a client with one bug reconnect in a loop, and an attacker’s garbage should cost you one small reply each.

The client must do the same for messages from the server. A browser tab runs old code against a new server after every deploy, so “the server always sends valid JSON” is not a safe assumption.

This is a local exercise: it opens real sockets. Copy both files into the Relay project in one folder, such as src/networking/realtime/, rename main.starter.ts to main.ts, and run bun test. The tests connect with fetch (reading the SSE stream) and with new WebSocket, both on port 0.

main.starter.ts (rename to main.ts)
// Relay's dashboard wants live job status. Two transports, one feed of events:
// - GET /events is server-sent events (SSE): a plain HTTP response that never ends. A browser
// `EventSource` reconnects by itself and sends the id of the last event it saw.
// - GET /ws is a WebSocket where the client subscribes to and unsubscribes from single jobs.
// The starter has wrong framing, ignores Last-Event-ID and has no WebSocket at all.
//
// Rules:
// - formatSse(event) is one SSE frame: "id: <id>\nevent: job\ndata: <JSON of the event>\n\n".
// The blank line at the end is what ends a frame.
// - parseLastEventId(header) returns the number in the header, or 0 when it is null, not an integer,
// or negative.
// - parseClientMessage(data) accepts text only. Invalid JSON: { ok: false, reason: "bad_json" }.
// Binary data, or JSON that is not { type: "subscribe" | "unsubscribe", jobId: <non-empty string> }:
// { ok: false, reason: "bad_message" }. Otherwise { ok: true, value }.
// - startFeed() starts Bun.serve on port 0 and returns { server, publish }. publish(jobId, status)
// gives the event the next id (1, 2, 3, ...), keeps it in a history and sends it to everyone who is
// listening, then returns the event.
// - SSE: GET /events answers with content-type text/event-stream and cache-control no-store. It
// first replays the history events with an id greater than Last-Event-ID, then streams new ones.
// The very first thing written is the frame "retry: 1000\n\n" (reconnect after 1 s). It also makes
// Bun send the response headers at once: with an empty body, fetch() would wait for the first event.
// When the client goes away the stream is forgotten (no writes to a cancelled stream).
// - WebSocket: GET /ws upgrades (400 if the upgrade fails). The client sends ClientMessages and gets
// ServerMessages as JSON text: subscribe -> { type: "subscribed", jobId }, unsubscribe ->
// { type: "unsubscribed", jobId }, a bad frame -> { type: "error", reason }. The socket stays open
// after a bad frame. Subscribed clients receive { type: "event", event } for that job only, using
// Bun's topics (ws.subscribe, server.publish) with the topic `job:${jobId}`.
export type JobStatus = "queued" | "running" | "done" | "failed"
export interface JobEvent {
readonly id: number
readonly jobId: string
readonly status: JobStatus
}
export type ClientMessage =
| { readonly type: "subscribe"; readonly jobId: string }
| { readonly type: "unsubscribe"; readonly jobId: string }
export type ServerMessage =
| { readonly type: "subscribed"; readonly jobId: string }
| { readonly type: "unsubscribed"; readonly jobId: string }
| { readonly type: "event"; readonly event: JobEvent }
| { readonly type: "error"; readonly reason: "bad_json" | "bad_message" }
export type ParsedClientMessage =
| { readonly ok: true; readonly value: ClientMessage }
| { readonly ok: false; readonly reason: "bad_json" | "bad_message" }
export function formatSse(event: JobEvent): string {
return `id: ${event.id}\ndata: ${JSON.stringify(event)}\n`
}
export function parseLastEventId(header: string | null): number {
return Number(header)
}
export function parseClientMessage(data: string | Buffer): ParsedClientMessage {
return { ok: true, value: { type: "subscribe", jobId: String(data) } }
}
export function startFeed() {
const history: JobEvent[] = []
const server = Bun.serve({
port: 0,
fetch: () => new Response(history.map(formatSse).join(""), { headers: { "content-type": "text/plain" } }),
})
function publish(jobId: string, status: JobStatus): JobEvent {
const event: JobEvent = { id: history.length + 1, jobId, status }
history.push(event)
return event
}
return { server, publish }
}
main.test.ts
import { afterEach, expect, test } from "bun:test"
import { formatSse, parseClientMessage, parseLastEventId, startFeed, type ServerMessage } from "./main.ts"
const cleanup: Array<() => unknown> = []
afterEach(async () => {
for (const fn of cleanup.splice(0)) await fn()
})
function start() {
const feed = startFeed()
cleanup.push(() => feed.server.stop(true))
return feed
}
async function openSse(url: URL | string, lastEventId?: string) {
const res = await fetch(new URL("/events", url), lastEventId === undefined ? {} : { headers: { "last-event-id": lastEventId } })
if (res.body === null) throw new Error("no body")
const reader = res.body.getReader()
cleanup.push(() => reader.cancel())
const decoder = new TextDecoder()
let buffer = ""
async function next(): Promise<string> {
for (;;) {
const end = buffer.indexOf("\n\n")
if (end >= 0) {
const frame = buffer.slice(0, end)
buffer = buffer.slice(end + 2)
return frame
}
const { done, value } = await reader.read()
if (done) throw new Error("stream ended")
buffer += decoder.decode(value, { stream: true })
}
}
expect(await next()).toBe("retry: 1000")
return { res, next, leave: () => reader.cancel() }
}
async function openSocket(url: URL) {
const ws = new WebSocket(new URL("/ws", url).href.replace("http", "ws"))
const inbox: string[] = []
const waiting: Array<(message: string) => void> = []
ws.onmessage = (e) => {
const text = String(e.data)
const waiter = waiting.shift()
if (waiter === undefined) inbox.push(text)
else waiter(text)
}
await new Promise<void>((resolve, reject) => {
ws.onopen = () => resolve()
ws.onerror = () => reject(new Error("socket error"))
})
cleanup.push(() => ws.close())
const next = (): Promise<ServerMessage> =>
new Promise<string>((resolve) => {
const ready = inbox.shift()
if (ready === undefined) waiting.push(resolve)
else resolve(ready)
}).then((text) => JSON.parse(text))
return { send: (data: string | Uint8Array<ArrayBuffer>) => ws.send(data), next }
}
test("formatSse is one complete frame", () => {
expect(formatSse({ id: 3, jobId: "j1", status: "done" })).toBe(
'id: 3\nevent: job\ndata: {"id":3,"jobId":"j1","status":"done"}\n\n',
)
})
test("parseLastEventId falls back to 0 for anything that is not a positive integer", () => {
expect(parseLastEventId("12")).toBe(12)
expect(parseLastEventId(null)).toBe(0)
expect(parseLastEventId("abc")).toBe(0)
expect(parseLastEventId("-4")).toBe(0)
expect(parseLastEventId("1.5")).toBe(0)
})
test("parseClientMessage separates bad JSON from a bad message", () => {
expect(parseClientMessage('{"type":"subscribe","jobId":"j1"}')).toEqual({ ok: true, value: { type: "subscribe", jobId: "j1" } })
expect(parseClientMessage('{"type":"unsubscribe","jobId":"j1"}')).toEqual({ ok: true, value: { type: "unsubscribe", jobId: "j1" } })
expect(parseClientMessage("{oops")).toEqual({ ok: false, reason: "bad_json" })
expect(parseClientMessage('{"type":"subscribe"}')).toEqual({ ok: false, reason: "bad_message" })
expect(parseClientMessage('{"type":"subscribe","jobId":""}')).toEqual({ ok: false, reason: "bad_message" })
expect(parseClientMessage('{"type":"delete","jobId":"j1"}')).toEqual({ ok: false, reason: "bad_message" })
expect(parseClientMessage("[1]")).toEqual({ ok: false, reason: "bad_message" })
expect(parseClientMessage(Buffer.from("{}"))).toEqual({ ok: false, reason: "bad_message" })
})
test("SSE answers with the event-stream headers", async () => {
const feed = start()
const { res } = await openSse(feed.server.url)
expect(res.headers.get("content-type")).toContain("text/event-stream")
expect(res.headers.get("cache-control")).toBe("no-store")
})
test("SSE streams events published after the client connected", async () => {
const feed = start()
const sse = await openSse(feed.server.url)
feed.publish("j1", "queued")
feed.publish("j1", "running")
expect(await sse.next()).toBe('id: 1\nevent: job\ndata: {"id":1,"jobId":"j1","status":"queued"}')
expect(await sse.next()).toBe('id: 2\nevent: job\ndata: {"id":2,"jobId":"j1","status":"running"}')
})
test("SSE replays what the client missed after Last-Event-ID", async () => {
const feed = start()
feed.publish("j1", "queued")
feed.publish("j1", "running")
feed.publish("j1", "done")
const sse = await openSse(feed.server.url, "2")
expect(await sse.next()).toBe('id: 3\nevent: job\ndata: {"id":3,"jobId":"j1","status":"done"}')
feed.publish("j2", "queued")
expect(await sse.next()).toBe('id: 4\nevent: job\ndata: {"id":4,"jobId":"j2","status":"queued"}')
})
test("publishing after a client left does not throw", async () => {
const feed = start()
const sse = await openSse(feed.server.url)
feed.publish("j1", "queued")
await sse.next()
await sse.leave()
await Bun.sleep(20)
expect(feed.publish("j1", "running").id).toBe(2)
})
test("a WebSocket client gets events only for the jobs it subscribed to", async () => {
const feed = start()
const socket = await openSocket(feed.server.url)
socket.send('{"type":"subscribe","jobId":"j1"}')
expect(await socket.next()).toEqual({ type: "subscribed", jobId: "j1" })
feed.publish("j2", "queued")
feed.publish("j1", "running")
expect(await socket.next()).toEqual({ type: "event", event: { id: 2, jobId: "j1", status: "running" } })
})
test("unsubscribe stops the events for that job", async () => {
const feed = start()
const socket = await openSocket(feed.server.url)
socket.send('{"type":"subscribe","jobId":"j1"}')
await socket.next()
socket.send('{"type":"unsubscribe","jobId":"j1"}')
expect(await socket.next()).toEqual({ type: "unsubscribed", jobId: "j1" })
feed.publish("j1", "done")
socket.send('{"type":"subscribe","jobId":"j2"}')
expect(await socket.next()).toEqual({ type: "subscribed", jobId: "j2" })
})
test("bad frames get an error reply and the socket stays open", async () => {
const feed = start()
const socket = await openSocket(feed.server.url)
socket.send("{oops")
expect(await socket.next()).toEqual({ type: "error", reason: "bad_json" })
socket.send('{"type":"subscribe"}')
expect(await socket.next()).toEqual({ type: "error", reason: "bad_message" })
socket.send(new Uint8Array([1, 2, 3]))
expect(await socket.next()).toEqual({ type: "error", reason: "bad_message" })
socket.send('{"type":"subscribe","jobId":"j1"}')
expect(await socket.next()).toEqual({ type: "subscribed", jobId: "j1" })
})

The starter formats frames wrongly, ignores Last-Event-ID and has no WebSocket. Fix the two parsers and the framing first (their tests need no server), then the SSE stream, then the socket.

  • SSE is a response with content-type: text/event-stream that stays open. A frame is id:, event:, data: lines and a blank line. Write one early (retry:) so the headers are sent.
  • Forget a stream in cancel(). After a drop, EventSource reconnects and sends Last-Event-ID: replay what is newer, and parse the header like any input.
  • In Bun.serve, server.upgrade(request) turns a route into a WebSocket. The websocket handlers get message, open and close. Type the per-socket data with Bun.Server<Data>.
  • ws.subscribe(topic) and server.publish(topic, data) are the built-in publish/subscribe.
  • Write both directions of a protocol as discriminated unions, and parse every incoming frame as unknown. Reply to a bad frame with an error message, and keep the socket open.