Live Updates: Optional Background
This chapter contains optional local observations and additional architecture background. Each section links back to its source topic. Required exercises include their own fixtures.
Observe the SSE clock locally
Run the server and browser exchange from the main chapter to observe its response format and connection lifetime.
To run this observation, use Part 4’s
practice-typed-http/ setup.
If api/deno.json lacks a hono/ prefix, add this entry alongside its existing
hono mapping, preserving other entries:
"hono/": "npm:/hono@4.13.5/"This matching prefix resolves hono/streaming.
Copy the main chapter’s TypeScript route into
api/src/routes/clock-routes.ts in the practice application.
In api/src/app.ts, import clockApp from ./routes/clock-routes.ts and add
app.route("/", clockApp) before the app is exported, keeping the existing routes
and CORS middleware. The supplied API already permits the practice client at
http://localhost:5173.
Copy the main chapter’s Svelte page into
client/src/routes/clock/+page.svelte. It consumes the API on port 8000.
With the practice services running, open http://localhost:5173/clock. Observe
the clock events in the browser’s Network panel, then navigate away and confirm
that the connection closes. The returned source.close() is component-removal
cleanup, as introduced with onMount in Part 2. Do not announce the clock through
a live region every second; Part 6 explained why that would be intrusive.
Return to snapshots and bounded delivery.
A WebSocket echo exchange
This example extends WebSockets & Bidirectional Communication.
We will start with an echo: the browser sends text and the server sends that
same text back. This small exchange lets us follow the connection from opening
through message delivery to cleanup. You can read and trace the code, or optionally
run it using Part 4’s
practice-typed-http/ setup.
The live-listing examples continue to use SSE and ordinary HTTP.
A bounded echo exchange
A WebSocket starts with an HTTP request asking to upgrade the connection.
After accepting the upgrade, the server and browser exchange WebSocket messages
on that connection. Deno.upgradeWebSocket returns the response that completes
this handshake and the socket used for the later messages. The
Deno WebSocket example
shows this API.
The socket’s readyState indicates whether it is open. Its
bufferedAmount
is the number of outgoing bytes queued but not yet transmitted. The checks below
reject unsupported messages and stop adding work for a slow connection. Close
code 1008 indicates a message-policy violation; 1013 asks the client to try
again later because the connection cannot be served now.
What should happen if a message arrives while the socket is closing, or if an open socket already has too much outgoing data? Express those decisions in order before connecting them to the message callback:
| First matching condition | Effect |
|---|---|
| Socket is not open. | Do nothing. |
| Input is binary or longer than the text limit. | Close with policy code 1008. |
| Outgoing bytes exceed the buffer limit. | Close with temporary-overload code 1013. |
| Otherwise. | Send the original text once. |
A bound is inclusive: exactly 1000 string units fits a 1000-unit limit; 1001 does
not. JavaScript string.length counts a supplementary Unicode character as two
units. Validate the message before checking its outgoing buffer, so overlapping
failure conditions have a predictable outcome.
The completed server below applies that order after connection upgrade and Origin handling.
To observe that policy over an actual connection, create
api/src/examples/echo-server.ts without replacing the ordinary API entry point.
The HTTP upgrade supplies the socket; subsequent messages arrive through its
onmessage callback:
Deno.serve({ port: 8011 }, (request) => { if (new URL(request.url).pathname !== "/api/echo") { return new Response("Not found", { status: 404 }); } if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") { return new Response("WebSocket upgrade required", { status: 426 }); } if (request.headers.get("origin") !== "http://localhost:5173") { return new Response("Forbidden", { status: 403 }); } const { socket, response } = Deno.upgradeWebSocket(request); socket.onmessage = (event) => { if (socket.readyState !== WebSocket.OPEN) return; if (typeof event.data !== "string" || event.data.length > 1000) { socket.close(1008, "Invalid message"); return; } if (socket.bufferedAmount > 64 * 1024) { socket.close(1013, "Slow connection"); return; } socket.send(event.data); }; socket.onerror = () => console.error("Echo connection failed"); return response;});Returning response completes the upgrade handshake. Later messages run through
socket.onmessage, which applies the policy in the table above. With the
practice client running, open a second terminal at practice-typed-http/:
docker compose run --rm --no-deps -p 127.0.0.1:8011:8011 api deno run --allow-net src/examples/echo-server.tsThis starts a separate process using the existing API image and source mount. The explicit port mapping exposes its listener; compose run does not publish the usual API port. Stop the echo process with Ctrl+C after the observation.
The fixed origin matches the practice browser at http://localhost:5173. It is not authentication: a non-browser caller can construct headers. This local echo demonstration has no private data. A private application must check its session and resource permissions before upgrading, and enforce permissions on subsequent actions.
The example accepts at most 1000 JavaScript string units and closes a connection whose outgoing buffer is too large. Deployment-level frame and connection limits are separate from these application checks. Keep this demonstration local.
Connect the echo client and release its socket
Create client/src/routes/echo/+page.svelte:
<script lang="ts"> import { onMount } from 'svelte'; let reply = $state(''); let connection = $state('connecting');
onMount(() => { const socket = new WebSocket('ws://localhost:8011/api/echo'); let stopped = false; socket.onopen = () => { if (stopped) return; connection = 'open'; socket.send('Hello'); }; socket.onmessage = (event) => { if (!stopped && typeof event.data === 'string') { reply = event.data; } }; socket.onerror = () => { if (!stopped) connection = 'error'; }; socket.onclose = () => { if (!stopped) connection = 'closed'; }; return () => { if (stopped) return; stopped = true; socket.onopen = null; socket.onmessage = null; socket.onerror = null; socket.onclose = null; socket.close(); }; });</script>
<p>Connection: {connection}</p><p>Reply: {reply || 'Waiting for the server'}</p><a href="/">Leave the echo page</a>Open http://localhost:5173/echo. The reply should become Hello only after the connection opens and the server echoes it. In the browser’s Network panel, inspect the WebSocket exchange, follow the link away, and confirm that the connection closes. Return to the page and observe one new connection. Stop the echo server and observe the closed/error feedback. A secure hosted page would need an appropriate wss: endpoint; this address is only for local practice.
The open event confirms that the handshake completed, so the client can now
call send. An echoed value shows that the message made a round trip;
acceptance of a business operation still requires
authorization, validation and persistence. The SSE marketplace uses its existing
HTTP bid response to tell the bidder whether a bid was accepted.
Leaving the page can race with an already queued reply. Clearing the installed handlers prevents later dispatch through them, but a callback already in the queue may still run. A local stopped flag lets that callback return without sending or updating a removed view. Pair clearing the handlers with closing the socket. Trace cleanup before opening and after a reply to check both paths.
Return to choosing a communication channel.
Changes from another process
Imagine the API running in one terminal and the maintenance command in another. Each is a process: a running program with its own memory. The API’s event hub reaches listeners registered in that process. The API and command-line program (CLI) share database rows but keep separate JavaScript objects and listeners.
The separate command has not invoked any listener in the API’s hub, so its commit can leave an open viewer unchanged.
To discover writes from other processes, the API can use an observer that periodically rereads subscribed resources with a limit on pending work. Under successful read and network conditions, its next reread can discover a version committed by a separate CLI. The existing finalizer stays unchanged. Repeated finalization produces no new version to deliver.
Reconnecting and reading the current snapshot reveals a closure made by the CLI. During an open connection, those periodic rereads let the API detect changes committed by the CLI. The opening-read and change-subscription interfaces keep these jobs distinct.
Return to Publishing Committed Changes.
A finite response test and mutation
Consider a library notice sent as one SSE event. This complete example constructs
a response and checks what a caller receives. It uses Deno’s test function and
the @std/assert alias already configured in the practice API:
import { assertEquals } from "@std/assert";
const noticeResponse = () => new Response("event: notice\ndata: The library closes at six.\n\n", { headers: { "Content-Type": "text/event-stream" }, });
Deno.test("a notice response declares and frames one event", async () => { const response = noticeResponse();
assertEquals(response.status, 200); assertEquals(response.headers.get("Content-Type"), "text/event-stream"); assertEquals( await response.text(), "event: notice\ndata: The library closes at six.\n\n", );});Read the test as setup, action and assertions. Calling noticeResponse produces
the response. The first two assertions inspect its status and declared format;
the last reads the body and checks the event name, data and terminating blank
line. The test has no database or listening server to start.
You can trace the values in the listing without running it. To try it locally,
save the example as api/src/examples/notice-response_test.ts in the existing
practice-typed-http/ application.
From that application’s root, run this optional check:
docker compose run --rm --no-deps api deno test --cached-only src/examples/notice-response_test.tsThe existing API image and import map supply Deno and @std/assert; no new
dependency is needed. A passing result reports one passed test. It means that
this response had the three properties asserted above.
Predict a framing failure, then restore it
In the response construction, remove only the final \n from the first string.
Its ending becomes six.\n instead of six.\n\n. Leave the expected string in
the assertion unchanged. Before rerunning, predict which assertion will fail.
The status and content type still match. The body assertion fails because the response is missing the blank line that terminates the event. The assertion location identifies where the missing boundary was detected; changing the expected body would hide the defect rather than repair it. Restore the response’s second newline and check that the test passes again.
This example has a finite body, so response.text() can finish. It checks a
constructed response directly, without Hono routing or a real network connection.
An SSE endpoint intentionally keeps its body open, so its check needs to stop
after the event of interest instead of waiting for the whole response.
Return to observing one complete SSE event.
An illustrative two-user browser workflow
An illustrative browser journey can connect the listing, upload and live-view features. Following a seller’s image and a buyer’s bid lets us ask whether the separately checked pieces produce the intended result together.
Use separate browser sessions for the seller and buyer so their cookies do not mix. Playwright calls each isolated cookie/storage session a browser context; for a manual observation, separate browser profiles serve the same purpose. Two ordinary tabs in one profile share the session.
A seller uploads a draft image and publishes the listing. In another browser context, a buyer opens it and bids. The seller’s open page should show the accepted price without reloading or losing input focus. Reloading the listing then checks whether its image is still available; leaving and returning lets the test inspect whether the old connection was released and a new one opened.
The journey combines capabilities you have worked on with surrounding application features. Use that distinction when tracing it:
| Journey observation | Your focused contribution in this part | Surrounding application pieces |
|---|---|---|
| A draft image is accepted and later displayed. | File receipt, authorized image service, and accepted/rejected image UI. | Sessions, listing routes, repositories, and the compensation helper. |
| An accepted bid reaches the seller’s open page. | Publication after commit, SSE delivery, and version-aware live detail. | The bid transaction, completed feed helper, and EventSource adapter. |
| A return visit displays the image and opens a fresh connection. | Metadata-based image display and connection cleanup. | Navigation and the application’s page composition. |
This conceptual walkthrough shows how the pieces fit together. Use focused rejection, race and storage-failure cases to locate specific mistakes; the two-browser journey checks how the pieces work together.
Return to Testing Live Updates & Image Storage.
Reconciliation after crashes
A reconciliation job compares stored objects with authoritative metadata after crashes. It must not delete bytes merely because an earlier response was lost: that loss does not establish whether the metadata committed. Reconciliation is outside the required image-service implementation.
Return to Authorized Image Storage & Display.
Check Your Understanding
- Why must a WebSocket wait for its open event before sending?
- Which state is shared by two API processes using one database, and which remains local?
- What does a finite response test establish that differs from an open-stream observation?