Live Updates & File Uploads

From Polling to Server-Sent Events


Learning Objectives

  • You can compare polling and server-sent events in terms of freshness, traffic, and recovery.
  • You can read a complete SSE event and distinguish its framing from an ordinary response body.
  • You can explain how an opening read and a change subscription cover changes between them.
  • You can consume a stream with bounded pending writes and release its server resources when delivery ends.

So far, the browser has usually learned about a change by making a request. That is sufficient for many applications. It becomes less convenient when another user changes the data and an open page should learn about it.

Imagine a queue-length display left open at a service desk. A staff member admits another person, changing the stored queue length. We will first let the display ask for that value again, then compare this with a connection that carries new observations as they become available.

We will compare the two delivery paths for the same queue, follow a small SSE exchange, and then connect resource snapshots to an HTTP response.

Polling intervals and overlapping requests

The service-desk display can stay current by requesting the queue length again after a delay. This is polling. Suppose a request takes longer than that delay: a fixed interval would start another request while the first is still pending. The display would have overlapping reads, and an older result could arrive last.

Instead, wait for the current read to finish before starting the delay for the next one. A promise that has either fulfilled or rejected is settled. Both outcomes need another scheduled read: the queue can change after a successful refresh, and a failed refresh may succeed next time.

We can express that sequence with setTimeout(callback, milliseconds), which schedules one later callback and returns a handle that clearTimeout can cancel. The function below waits for read to settle, then schedules the next call:

export const startPolling = (
read: (signal: AbortSignal) => Promise<void>,
milliseconds: number,
) => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
const poll = async () => {
try {
await read(controller.signal);
} catch (error) {
if (!controller.signal.aborted) {
console.error("Status refresh failed", error);
}
}
if (!controller.signal.aborted) {
timer = setTimeout(poll, milliseconds);
}
};
void poll();
return () => {
controller.abort();
if (timer !== undefined) clearTimeout(timer);
};
};

Return startPolling(...)’s cleanup function from the component’s onMount callback. The read function performs the fetch, handles the response, and updates the displayed queue length. Because read owns that update here, it must check signal.aborted after its awaited work and before changing the view. Aborting a request does not undo work that has already completed. A failed refresh should preserve the last known value and indicate that it may be stale.

Suppose the display last confirmed a queue length of four, and its next read fails. Showing zero would invent a new observation. Keep four visible and mark it stale instead. If the user leaves while a read is pending, its eventual result no longer belongs on screen.

In the next exercise, read returns a value and the polling controller owns the display update. Use its controlled timers to follow a pending read, a rejected refresh and cleanup.

Keep queue refreshes under control

0 / 45 points

Goal

Refresh a queue display without overlapping requests or losing its last confirmed value.

Files and supplied code

Edit polling.ts. The read callback has the exported Read type and resolves to a queue length. Schedule a callback with timers.after(ms, callback), which returns a numeric handle, and cancel it with timers.cancel(handle). The checks supply controlled timers and pending reads.

Task

Complete startPolling(read, render, timers, intervalMs). Render {value:null, stale:true} immediately and start one read. A successful read updates the retained value and renders stale:false. A rejected read retains the last value and renders stale:true.

After either outcome settles, schedule the next read for intervalMs later. No read or timer for another read should start while the current read is pending.

Return a stop function that cancels the scheduled callback and aborts an outstanding read through its signal. After stopping, a late result must neither render nor schedule more work. Calling stop more than once must have the same effect as calling it once.

intervalMs is a positive integer; successful reads return nonnegative integers. read returns a promise without throwing synchronously. Rendering and timer methods do not throw.

Examples

If a read remains pending for three seconds, no other read starts during that time. When it resolves to 4, the next read starts one interval later. If that refresh rejects, keep 4 and mark it stale. Stopping before the first read resolves leaves the initial view unchanged.

Check and submit

Choose Submit solution to run the checks. Submit only polling.ts. Scheduling is worth 15 points, failure/recovery 15, and stopping/late-result cleanup 15.

The delay between reads introduces a trade-off. A short interval discovers changes sooner but creates more requests, including requests that return the same state. A long interval reduces traffic while leaving the display out of date for longer. A variation called long polling lets the server hold a request until something changes or a timeout expires; the client then starts another request.

Polling and SSE on the same timeline

A snapshot contains a resource’s current values at one version. Suppose both approaches receive {length: 2, version: 5}. Here length is the queue length, and version is a counter that increases when its stored state changes. A staff action changes the queue to {length: 3, version: 6}. Both approaches deliver the same snapshot fields; their delivery timing differs. The connection may also carry a heartbeat, a small keepalive message that carries no new resource state.

TimeAuthoritative queuePolling every five secondsSSE connection
0 secondsLength 2, version 5GET returns version 5.Initial snapshot is version 5.
2 secondsLength 3, version 6Still displays version 5.Server sends version 6 after the change.
5 secondsStill version 6Next GET returns version 6.No new state event is needed.
10 secondsStill version 6Another GET returns the same value.Connection remains open, with bounded heartbeats if configured.

In this simplified timeline, reads complete immediately and messages have no delivery delay. The polling view discovers this change three seconds later; SSE can send it immediately after commitment. Polling uses repeated requests, while SSE keeps a connection open and needs disconnect cleanup. Both approaches observe the same committed state. After a connection gap, either can recover the current queue length with a fresh snapshot.

A freshness requirement helps choose between these costs. If a display may lag by five seconds and changes rarely, five-second polling can be sufficient. If changes must appear promptly to many viewers, SSE avoids repeated unchanged responses, but the application must budget for open connections and recover after gaps. An interval bounds detection delay only under the stated read and network assumptions; it cannot guarantee delivery during an outage.

Choose freshness and request costs

0 / 5 points

A queue display can lag by at most five seconds when reads and network delivery succeed. Changes are rare. Ignore read latency and compare one-minute steady operation, excluding the initial read: five-second polling makes 12 requests, while SSE keeps one connection open. Which conclusion follows?

The timeline compares delivery costs for the same state. Before connecting resource snapshots to a live response, inspect the format of one SSE event.

SSE event framing

Server-sent events use an HTTP response whose body contains a sequence of events. A browser’s EventSource consumes this format and reconnects when appropriate.

The wire format is the text sent in that response body. An SSE event has named fields and ends with a blank line; these event boundaries are its framing. For example, one clock event looks like this, including the blank line after data:

event: clock
data: {"observedAt":"2026-10-18T12:00:00.000Z"}

event: clock selects a listener registered for clock; data contains the string passed to that listener. Hono’s writeSSE constructs this format, and EventSource parses it. An event can span several network chunks.

A small server and browser exchange

A clock provides a simple source of changing values before we connect a queue or listing. This route sends one named clock event each second:

import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
export const clockApp = new Hono().get(
"/api/clock-events",
(c) =>
streamSSE(c, async (stream) => {
while (!stream.aborted) {
await stream.writeSSE({
event: "clock",
data: JSON.stringify({ observedAt: new Date().toISOString() }),
});
await stream.sleep(1000);
}
}),
);

streamSSE sets up the event response. writeSSE formats each event, and the loop awaits its write before waiting for the next second. A disconnected browser ends the loop through stream.aborted.

With that route mounted in the practice API on port 8000, this Svelte page opens the connection from the permitted practice client at http://localhost:5173:

<script lang="ts">
import { onMount } from "svelte";
let observedAt = $state("");
let connection = $state("connecting");
onMount(() => {
const source = new EventSource("http://localhost:8000/api/clock-events");
source.onopen = () => {
connection = "connected";
};
source.onerror = () => {
connection = source.readyState === EventSource.CLOSED ? "closed" : "reconnecting";
};
source.addEventListener("clock", (event) => {
const value = JSON.parse((event as MessageEvent).data) as { observedAt: string };
observedAt = value.observedAt;
});
return () => source.close();
});
</script>
<p>Connection: {connection}</p>
<p>Server observation: {observedAt || "No observation yet"}</p>

The listener’s name matches event: clock; its data is the JSON string sent by our route. onopen and onerror report connection changes separately from the last timestamp. EventSource retries temporary interruptions; a terminal error leaves it closed. source.close() stops it when the component is removed. This public clock sends no private data and needs no session credentials.

You can trace the exchange here or use the optional local setup to inspect it in the browser. The SSE guide describes the other event fields and connection behavior. A queue or listing needs an additional policy: recover its current state after a gap and bound the updates waiting for a slow connection.

Snapshots and bounded delivery

A connection may drop, a server may restart, and a tab may be suspended. An event ID is a label attached by the server. It only supports replay when the server actually retains and serves the corresponding history.

For an application that needs current state rather than every intermediate change, the server can begin each connection with a current snapshot. Attach a resource version that increases with each stored change so the server can deliver newer observations without sending the same or an older version again. The opening snapshot must cover changes that arrive while its read is pending.

An event hub groups listeners by resource. Subscribing registers a listener; unsubscribing removes it. A stream can receive changes while its first database read is still pending, so it needs somewhere to retain those observations. A bounded queue limits how much work a slow connection can leave in memory.

A slow client must not cause an unbounded list of pending snapshots in API memory. When a display needs only current state, closing an overloaded connection and beginning its replacement with a fresh snapshot avoids retaining a complete delivery history for that client.

A slow viewer fills its event queue

0 / 5 points

An SSE queue-length display needs only the current length. One slow browser has filled the server’s bounded queue of pending snapshots. Which response preserves a useful recovery path without allowing that client to consume unlimited memory?

The initial snapshot and subscription race

Reading state and only then subscribing creates a gap: version 6 can commit after a read returned version 5 but before the listener exists. Subscribe first, buffer events during the read, send its result, and then send only versions newer than the greatest already sent. Keep the same subscription while draining the queue.

Figure 1 shows how the initial snapshot and one event can overlap while keeping the delivered versions increasing.

Figure 1. A subscription covers changes that arrive while the initial snapshot is being read.
Read resultBuffered eventDelivery
Version 5Version 6Send 5, then 6.
Version 6Version 6Send 6 once.
Version 7Version 6Send 7; discard the older event.

Buffering keeps a snapshot for later delivery. If the source changes the object after sending it, the buffered values must still describe the observation that arrived. Assigning kept = received keeps two references to one object, so a change through either reference affects that same object. { ...received } creates another object with the current property values. For a snapshot containing only numbers, that copy retains its values when the received object changes. This is a shallow copy: a nested object would still need its own ownership decision.

Keep a received observation

0 / 5 points

A snapshot has only the two number-valued fields shown here. What are kept.length and received.length after this code runs?

const received = { length: 4, version: 6 };
const kept = { ...received };
received.length = 0;

Copying preserves the buffered values, while version comparison protects their delivery order. Later events follow the same version rule as buffered ones. Connection cleanup removes the listener and any heartbeat, including when a full queue ends delivery.

The opening sequence and version comparison solve different problems. Rejecting older values cannot repair a change missed before the listener existed. Use the timeline to follow both decisions in the next repair; its buffering and cleanup are already in place.

Keep an update received while a stream opens

0 / 20 points

Files and environment

Edit open-snapshots.ts. The supplied Deno tests provide a typed source.

Task

An update can arrive while the first snapshot read is pending. The opening sequence must retain that update even if the read returns an older version.

Repair the opening sequence in openSnapshots(source, send) and complete deliver. A delivered snapshot must be a copy, and its version must be strictly greater than every version already sent.

Keep the supplied buffer, its limit, cleanup and error handling. The initial snapshot is sent before newer buffered observations. Continue using the same subscription afterward. For example, a buffered version 6 after an initial 5 produces 5 then 6; an initial 6 already covers that buffered 6.

Versions and lengths are nonnegative integers. The source callbacks and send do not throw; read can reject. subscribe registers the listener, and its observation callbacks begin only after subscribe returns.

Check and submit

Choose Submit solution. The opening race is worth 10 points; covered versions and later live updates are worth 5 points each. The feedback names the event sequence to reconsider.

The opening sequence can be observed without relying on elapsed time. A controlled trace holds the read pending, supplies version 6 through the subscribed listener, then resolves the read with version 5: delivery should contain 5 followed by 6. If the read already contains version 6, delivery should contain it once. These controlled arrivals expose the missed-change and duplicate-delivery cases directly; a fixed sleep does not establish which happened first.

Access control for event streams

A live connection exposes resource values just as an ordinary GET does. Public events should contain only public fields. Private streams require authentication and authorization before opening, together with a policy for expired or revoked access during the connection. Native EventSource does not expose arbitrary request-header configuration like a general fetch call. A same-origin cookie design or another explicitly designed transport can carry the required identity without putting credentials in query strings.

A stream response cannot change its HTTP status after it has begun. Validate access before streaming and handle later errors as connection/event behavior.

Connect the HTTP event boundary

An async iterable produces values over time. for await ... of waits for each value without starting a polling timer. When those values become an HTTP response body, the consumer also needs to stop if the browser leaves. Hono’s stream.onAbort(callback) registers that cleanup. Cleanup also belongs in finally, because normal exhaustion and write errors end a stream too. Hono’s streaming helper supplies the response format and connection-abort information.

Here is the wiring for a generic notice source. In this outline, openNotices() returns {values: AsyncIterable<string>, stop(): void}. Its stop is idempotent, unblocks any pending read and ends the iterable; those properties let both paths use the same cleanup function:

return streamSSE(c, async (stream) => {
const source = openNotices();
const cleanup = () => source.stop();
stream.onAbort(cleanup);
try {
for await (const notice of source.values) {
await stream.writeSSE({ event: "notice", data: notice });
}
} finally {
cleanup();
}
});

The await inside the loop matters too. It waits for the current write to fulfill before the loop requests another value; a rejected write exits the loop. The source can still receive updates into its own bounded queue, but this consumer does not start a growing collection of unsettled write promises. Removing that await changes how much work can remain pending even if each event has the correct format.

Follow a pending stream write

0 / 5 points

A feed may have another value available, but the first write below is still pending. Which statement describes this loop?

for await (const snapshot of feed.snapshots) {
await stream.writeSSE({
event: "snapshot",
data: JSON.stringify(snapshot),
});
}

Alongside bounded writes, perform ID and permission checks before calling streamSSE, while an ordinary error status is still possible. Register abort cleanup before waiting for the first value; a client can leave while that value is still pending. If several helpers allocate resources, the same cleanup releases each one.

A public listing feed brings these decisions together. An ordinary request must first establish whether the listing is visible and whether another connection can be opened. Once the response starts, event framing and cleanup govern the ongoing exchange. Connect that HTTP boundary in the next exercise, using its completed snapshot feed and documented helper types.

Connect a bounded HTTP event stream

0 / 45 points

Goal

Expose a bounded public snapshot feed through real SSE responses.

Files and supplied code

Edit only api/src/live/events-api.ts. Hono is configured in the provided environment. supplied.ts provides:

  • EventsDependencies.read(id, signal) resolves to a valid public snapshot or null. observe(id, callback) registers an observer and returns an unsubscribe function; it can throw CapacityError.
  • openFeed(deps, id): {snapshots, closed, stop}. Its async iterable already subscribes before rereading, buffers up to 16 updates, sends strictly newer versions, and ends on overflow. stop() cancels its read and unsubscribes; it is idempotent. closed resolves when the feed stops.
  • startHeartbeat(stream, feed): starts one bounded keepalive and returns an idempotent stop function. When the feed closes, this helper also stops the heartbeat and aborts the response, releasing any blocked write. Connect the supplied helpers.

Supplied helper interfaces:

import type { SSEStreamingApi } from "hono/streaming";
type Snapshot = {
listingId: number;
currentPrice: number;
endsAt: string | null;
status: "active" | "closed";
version: number;
};
type EventsDependencies = {
read(id: number, signal: AbortSignal): Promise<Snapshot | null>;
observe(id: number, receive: (value: Snapshot) => void): () => void;
};
declare class CapacityError extends Error {}
declare const openFeed: (
deps: EventsDependencies,
id: number,
) => {
snapshots: AsyncIterable<Snapshot>;
closed: Promise<void>;
stop(): void;
};
declare const startHeartbeat: (
stream: SSEStreamingApi,
feed: { closed: Promise<void> },
) => () => void;

stream.onAbort(cleanup) registers cleanup for a disconnected client. The for await (const value of iterable) loop waits for successive values. Cleanup also belongs in finally, because normal completion or a write error can end the loop. Stopping these supplied helpers more than once is safe.

Task

Complete createEventsApp for GET /api/listings/:listingId/events. The ID must consist of decimal digits and represent a positive safe integer; otherwise return 400. Before opening any subscription, call read to check visibility. A null result returns 404. Open a new feed after that lookup, mapping CapacityError to 503 before streaming begins.

Use streamSSE to send named snapshot events with JSON data. Public snapshots contain exactly listingId, currentPrice, endsAt, status and version.

Register abort cleanup before consuming the feed. Start the supplied heartbeat with startHeartbeat(stream, feed) and iterate feed.snapshots. Both helpers must stop on abort or completion, including when the supplied queue overflows while a response write is still pending.

Sources follow their exported types. The supplied helpers handle read cancellation and version selection. The ordinary HTTP request still governs bid acceptance.

Examples

Listing 12 can open a complete event: snapshot frame. A private listing returns 404 without opening a subscription. Cancelling the client’s reader while the opening read is pending must cancel that read and release its observer and heartbeat.

Check and submit

Choose Submit solution to run the checks. Submit only api/src/live/events-api.ts. Access is worth 10 points, actual framing 15, capacity/overflow 5, and abort cleanup 15. Framing credit also checks that the endpoint preserves the supplied opening/version algorithm when consuming the feed; that algorithm remains supplied.

Observe one complete SSE event

A hub check establishes which listener received a snapshot. An HTTP observation also checks the route’s status, content type and wire framing. It reads until the event’s terminating blank line, even when its bytes span several network chunks, and uses a deadline to bound that read.

An SSE response intentionally remains open, so response.text() may never finish. The observation must abort the request and cancel any pending reader operation in finally, including after a failed assertion or deadline. After cancellation, check that the observer and heartbeat have been released. An abort while the opening read is still pending exposes an early disconnect. The supplied route can be inspected this way without another local application.

The optional finite response test provides a smaller framing example and a local mutation walkthrough.

The queue display now has two ways to learn about a change: another read after the previous one settles, or observations delivered through an open response. The streaming route checks access before opening and releases its resources when delivery ends. A snapshot’s version identifies the delivered observation. Next, we follow the committed operation that supplies those public snapshots. The browser’s recovery and editing decisions follow that server-side path.

Check Your Understanding

  1. How do polling frequency and read duration affect freshness and request load?
  2. What separates one complete SSE event from the next?
  3. Which change can be missed if subscription begins only after the opening read?
  4. Why should a stream consumer await each write, even when its source has a bounded queue?
  5. Which resources must be released if the viewer leaves before the first value arrives?

After publishing committed changes, we will follow client recovery and editable views.