Free learning / 40-minute lab + optional cancellation workshop
Streaming 101: when is a response actually finished?
See how bytes become events and a partial draft becomes a reviewable result. Compare six local HTTP responses, including interrupted streams and incomplete messages.
No account needed. Use your own copy for writing and keep the original as a reference.
Engineering lab library / Run locally
See what arrived—and what actually completed.
Predict six responses, then change byte grouping and completion requirements separately. Keep partial output distinct from a finished result.
Real HTTP on a temporary loopback port with scripted text. No model, credentials, external service or files. Byte slices and events are observed; model tokens and latency are not measured.
Search titles, outcomes and prerequisites, then narrow by runtime.
2 of 2 labs · All labs
Start here / Node.js 24 · Offline exercise
Client cancellation and server effects
Abort three real response streams, then query the recorded rows to distinguish continued work, a cooperative stop and a prior write.
Node.js 24 · Built-in SQLite · Ephemeral loopback HTTP · No packages or model
Node.js 24 · Offline exercise
Streaming 101 · real local HTTP
Reconstruct events across byte boundaries, withhold interrupted output and expose a premature-completion defect.
Node.js 24 · Standard library · Loopback only · No model
You ask an assistant for a draft. Words begin appearing, then the answer stops halfway through a sentence. Did it finish? Did the connection fail? Can you use what appeared? Those are separate questions, and a forward-deployed engineer needs an interface that tells the difference.
This original 40-minute lesson starts with the mechanism, then follows six actual local HTTP responses. It uses fictional text and no model, credentials, packages or cloud account. You need Node.js 24 and permission to listen on a temporary loopback port on your own computer. Nothing is exposed to your network.
1. Name the pieces before following the stream
Streaming is a way to deliver a response incrementally while work proceeds, instead of waiting to deliver the whole body at once. It is a delivery behavior, not a language, model or agent framework. It can make progress visible sooner; it does not by itself make generation faster or the answer correct.
Think of a download progress display. Seeing bytes arrive is different from having a complete, usable file. The analogy has a limit: a generated response usually does not have a known final size, and its content still needs review.
| Piece | Plain meaning | What it does not establish |
|---|---|---|
| Byte chunk | A portion of the response body delivered to the reader | One complete event, character or model token |
| UTF-8 decoder | Code that reconstructs text from bytes, keeping unfinished characters between reads | A complete application message |
| Server-sent events (SSE) | A text format for sending events from a server over HTTP | The event names or success rules of a particular model API |
| Delta | An addition or change to the result being assembled | A complete answer or executable tool arguments |
| Completion event | An application-defined signal that a message has ended | A factual answer, approved action or acceptable stop reason |
In the supplied lab, an event has an event: line, a data: line containing JSON and a blank line that ends the event. The reader must wait for that boundary before parsing the JSON. The service invents start, text_delta and done for this teaching exercise. They are not a provider's API contract.
2. Follow a draft from bytes to a reviewable result
Our fictional service writes three additions: Café , pump: and check seal. The client accumulates them into Café pump: check seal. while marking the preview as partial. The accented character is intentional: one character can occupy more than one byte. The same decoder keeps its state across reads.
Follow four decisions in order:
- Confirm the HTTP status and content type before interpreting the body.
- Decode bytes, retain unfinished text, then parse complete event records.
- Update the preview as deltas arrive while keeping it visibly provisional.
- Require the documented completion and acceptable stop reason, then validate the assembled result before the application's next action.
HTTP 200 only describes the response status. The body can subsequently break, end early or contain invalid events. Our lab waits for normal transport end, valid records and done with reason normal before marking a result ready-for-content-review. That deliberately narrow result is not permission to execute a tool or publish the text.
UNDERSTAND THE SYSTEM
The text arrived. Did the response finish?
Follow a fictional maintenance draft through an HTTP stream. The visible preview, event record and completion decision change independently. These are explained examples of the accompanying local lab, not a live model call.
Watch one example, step by step.
Read the full worked example
- 01A successful status starts the response
HTTP 200 arrives before the body finishes. The start event identifies this fictional request but supplies neither a draft nor completion. Later failure is still possible.
START: Status 200 · completion not observed
- 02The first text is a preview
The first text_delta contains Café. The preview can now show something useful, labeled partial. The accented character may span byte reads; keep the same decoder across those reads.
PARTIAL: Café · receiving · do not act
- 03Different byte slices, the same message
The lab's fragmented case feeds received data to the decoder one byte at a time. It reconstructs the same five events and text. These controlled parser slices are not measured network packets or model tokens.
FRAGMENTED: Many slices → same events → same text
- 04A clean connection end can be incomplete
The missing-done case ends the HTTP body normally after two additions. The preview says Café pump: and there is no completion event. The reader withholds it. In connection-lost, a body-read error provides another reason to withhold; remote work cannot be inferred from that error alone.
MISSING-DONE: Transport ended · message incomplete · withheld
- 05Normal completion permits content review
A valid done event reports normal completion, and the body ends without an error. The assembled text becomes ready for content review. That does not establish factual correctness or approve an agent's next action.
COMPLETE: Normal completion → ready for content review
- 06A completed message can still be withheld
The limited case has full-looking text and a done event, but its reason is length_limit. This application's contract rejects that reason. The separate malformed case cannot parse the final JSON and is also withheld.
LIMITED: Completion observed · reason not accepted
Read the connections in plain English
- 01Response service → Byte reader
One read can contain partial or multiple records. It is not a token boundary.
- 02Byte reader → Complete event
Decode and retain partial text before parsing a complete event.
- 03Complete event → Draft preview
Only text additions change the draft. Progress remains provisional.
- 04Complete event → Acceptance check
Inspect the completed message and its stop reason before continuing.
- 05Draft preview → Acceptance check
A nonempty draft is insufficient without valid completion evidence.
Check your understanding: The connection ended normally and some text appeared. Can the app mark the draft complete?
Only if the service's documented completion evidence and your acceptance checks are satisfied. In the lab, the missing-done case has both a normal HTTP end and partial text, yet must remain incomplete.
3. Predict and run six local responses
First open Streaming 101 and choose Try it. The visual replay pairs each received event with the draft it produces. Compare the missing-completion case with its deliberately broken rule, then run the same cases below. The replay is a recording, not a live model response.
Download fde-streaming-lab.mjs into a new folder. Use the same Node.js 24 command throughout:
node --version
node fde-streaming-lab.mjsThe file starts a server bound to 127.0.0.1 on an available port, makes six requests and closes the listener. It writes no files and reads no credentials. The server's short pauses make intermediate states observable; they are not measurements of inference performance. It does not retry failed requests.
Before running it, predict the completion decision for each case:
| Case | What the server or reader changes | Expected observation |
|---|---|---|
| complete | Three deltas followed by normal completion | Full text, completion observed, ready for content review |
| fragmented | Same response; client feeds its decoder one byte at a time | Same text and events despite many more parser slices |
| missing-done | HTTP body ends normally after two deltas, without completion | Partial text, transport ended, completion absent; withheld |
| connection-lost | Connection is destroyed after two deltas | Partial text, body-read-interrupted; withheld |
| limited | Full-looking text followed by a length-limit reason | Completion observed, but withheld by this app's contract |
| malformed | Final event contains invalid JSON | Invalid record; withheld |
The report also includes frames: received event records paired with the reader state immediately after each record. decoderSample selects the two one-byte calls that reconstruct é in the fragmented case. These observations let you connect the free visual replay to the actual local experiment.
Compare httpStatus, transportEnded, events, completionObserved, reason and decision. All six begin with 200. In previews, find text that appeared before any completion event. Do not infer a token count from text length, event count or receivedChunkBytes: the lab runs no model or tokenizer.
receivedChunkBytes records actual body reads; their grouping can vary by runtime and transport. parserSlices counts the pieces passed into our decoder. The fragmented case deliberately re-slices received bytes on the client. It does not claim that the network delivered one-byte packets. The controlled experiment isolates the parser's ability to preserve boundaries.
4. Change one assumption and explain the consequence
Keep the original file. In a first copy, change SLICE_BYTES = 1 to SLICE_BYTES = 7 and rerun. The fragmented case should have fewer parser calls but the same five events and complete text. A reader that relies on each read being a complete JSON object cannot meet that property.
Starting from the original, make a second copy and change REQUIRE_DONE = true to REQUIRE_DONE = false. This deliberately weakens the example's acceptance rule. The missing-done case now promotes Café pump: even though no completion arrived. The lost connection, invalid record and explicit length limit should still be withheld. Explain why a check that only asserts a nonempty response would miss this defect. Do not carry this broken rule into an application.
This is a small protocol lesson, not a general-purpose SSE implementation. The reader supports only the two-field, LF-delimited records emitted by this server. A complete SSE parser also handles other line endings, comments, multiple data lines and additional fields. Use the maintained SDK or parser appropriate to your production service, then test its behavior at your application's boundary.
5. Connect this to Claude and an agent workflow
Claude's documented stream has message and content-block events, text or tool input deltas, a stop reason and final message_stop. These names differ from our teaching protocol. Follow the provider's current SDK and event contract. Tool input can arrive as JSON fragments: a fragment is not yet validated tool arguments. Assemble the intended input, validate its schema and authorize the operation in trusted application code before executing it.
If the stream fails, retain an explicitly incomplete preview and the request's safe diagnostic metadata. A missing final event does not tell you whether a remote operation continued, how much it cost or whether an external effect occurred. Reconnection and safe retry are separate designs. This lab performs one attempt per case and has no continuation, replay or effect reconciliation.
In the UI, separate “receiving,” “ready for review,” “stopped” and “interrupted.” Do not let partial markup run as HTML or partial tool input trigger an action. When a user cancels, stop consuming and request supported cancellation; verify what the provider actually promises about remote work and billing. The local connection-lost case does not test provider cancellation.
For a real deployment, inspect buffering at the application, proxy and gateway. Measure first useful output and completed useful output separately. A responsive animation cannot establish either result. Do not add timing claims based on this fixture's deliberate pauses.
6. Hand over a response contract
Produce a small integration card with:
- The actual endpoint, content type, event schema and supported client version.
- Which preview states are visible and what qualifies as completed input.
- The acceptable stop reasons and content checks before downstream work.
- What happens after malformed data, a disconnect, timeout or user cancellation.
- How request identity, retry policy and unknown usage are recorded safely.
Keep your six predictions, observed report and two independent changes. Ask a receiver why both a clean HTTP end and a visible sentence can still be insufficient. Then give them a tool-input fragment and ask what must happen before an agent may use it. A good explanation names assembly, validation, authorization and the unresolved remote outcome without inventing certainty.
Continue in the guided streaming lesson with existing training access, then build the first bounded LangChain agent.
Primary references checked 22 October 2026:
7. Observe what cancellation does to server work
This optional 25-minute workshop extends the original six responses without changing them. The earlier connection-lost case establishes an incomplete response. Here you will deliberately cancel a real client response and inspect what happened on the server. Cooperative cancellation means application code observes a stop condition at a supported boundary. It is not an automatic reversal of work that already happened.
Download the cancellation and effects companion. Use Node.js 24 with its built-in SQLite module and permission to open an ephemeral port on 127.0.0.1. It uses no packages, model, credentials or external service. Its SQLite table is in memory; no existing database or local document is opened. A Node SQLite experimental warning may appear on the teaching runtime; it is separate from the program's result.
Before running, each participant predicts the stored row count for three cases. The fictional effect is recording a maintenance draft in the local table. It is not sending a message, changing a client system or approving an agent's tool call. The fixture deliberately owns both ends of HTTP so that the receiving engineer can obtain evidence beyond the interrupted stream.
node --version
node fde-stream-cancellation.mjs compareThe client starts one work request, reads a provisional preview and calls AbortController.abort(). Its next body read rejects. The server observes the response close before it finishes. The driver then releases the waiting work and, after that work settles, makes a separate read-only GET /evidence request. That endpoint queries the actual SQLite rows. No work request is automatically retried.
The cases use explicit ordering barriers instead of timing guesses. They do not measure cancellation latency or promise that a provider stops when a socket closes. A response's close event can also follow a normal response; inspect the unfinished state and the specific application contract.
UNDERSTAND THE SYSTEM
Stopping the stream does not undo the work
Three independently reset local HTTP cases have the same client cancellation and different stored outcomes. This visual explains the supplied schedule; run the Node.js companion for actual HTTP and SQLite evidence.
Watch one example, step by step.
Read the full worked example
- 01Ignore the disconnect
After the client aborts and the response closes, the driver releases the pending work. This handler ignores the disconnected flag and inserts one row. The client has no completed stream, but the separate evidence read finds the write.
IGNORE DISCONNECT: Aborted reader · 1 stored row
- 02Stop before the write
The same sequence reaches a handler that checks the disconnected flag before the synchronous local INSERT. It skips that write. The evidence read returns zero rows. This establishes one bounded cooperative stop, not cancellation of every downstream service.
COOPERATIVE STOP: Aborted reader · 0 stored rows
- 03Cancel after the write
This case inserts the row before sending the preview. The client then cancels and the unfinished response closes. One row still exists: stopping the reader does not reverse the earlier write. Recovery needs the actual operation contract and authorized owner.
WRITE ALREADY HAPPENED: Aborted reader · 1 earlier row
Read the connections in plain English
- 01Client cancels → Response closes
Follow the actual client abort to the server's observed unfinished response close.
- 02Response closes → Server work
The handler must decide what cancellation means for this operation; the socket does not undo a write.
- 03Server work → Read the evidence
Wait for the operation to settle, then query the actual recorded state.
Check your understanding: The client reports AbortError. Can the pod tell the operator that nothing was recorded?
No. All three cases abort the reader, while the evidence endpoint reports one, zero and one rows. State that the stream stopped; establish the operation outcome separately. If that evidence is unavailable, preserve the unknown outcome and use the service's supported reconciliation route.
8. Compare three cancellations with different outcomes
| Case | Where the write sits | Handler behavior after the disconnect | Rows found by the separate evidence read |
|---|---|---|---|
ignore-disconnect | Waiting until the response closes | Continues and inserts the draft | 1 |
stop-before-write | Waiting at the same boundary | Checks the disconnected flag and skips the INSERT | 0 |
already-written | INSERT happens before the preview is sent | Cancellation arrives after the write | 1 |
The client stops consuming in all three cases. Its AbortError cannot distinguish these stored outcomes. In the first case, application work continues after the connection ends. In the second, an explicit application check prevents the pending local write. In the third, cancellation cannot reverse the existing row. Preserve the actual event order, client observation and separately queried rows; do not replace them with one ambiguous “cancelled” status.
The zero-row case uses a synchronous local check followed by a synchronous SQLite operation. Adding an asynchronous remote tool call creates another boundary: the remote service may accept work before your cancellation arrives. Define its cancellation, status and reconciliation contract instead of generalizing this fixture's cooperative stop.
Controlled change: keep the original file, then change only HONOR_DISCONNECT = true to HONOR_DISCONNECT = false in a copy. Predict all three row counts before running compare. The stop-before-write case should now record one row; the other two should remain one. Locate the changed decision in the actual event trace. The original self-test checks the unmodified baseline, not whether an intentionally broken copy still passes.
Transfer challenge: remove access to the evidence endpoint from the receiving team's scenario. What can the operator be told from the preview and abort alone? Preserve “stream stopped; operation outcome unknown,” identify the authorized service owner and define the next evidence request. Do not borrow credentials, replay the work blindly or claim an undo. A compensating operation, if the business permits one, is a separately authorized action with its own result.
9. Give the receiver an operation outcome
Work in pairs, with one builder and one receiver. Each keeps an initial prediction. The builder supplies the exact file, command and output; the receiver locates the abort, unfinished response close, write or skipped write, and the later evidence request without narration. Switch roles for the changed copy. Record any hint or takeover rather than giving the group one shared success label.
The pod lead coordinates the unresolved question and the next update. The application owner defines supported cancellation boundaries, the operation owner establishes the recorded outcome, and the receiving operator decides the next permitted workflow step under the actual policy. A transport event supplies none of those authorities.
Candidate / command / case / output location:
My initial prediction / personally observed client outcome:
Response close / work decision / write ordering:
Separate evidence request / actual rows / remaining unknown:
Operator message and permitted next step:
Next owner / evidence needed / update trigger:
My contribution / receiving check / help used / revised explanation:Keep the original and changed-copy reports. A participant who can distinguish all three cases has explained this controlled experiment; that is not a claim of provider cancellation guarantees or independent deployment readiness. Continue to the protected streaming lesson for the receiving interpretation and knowledge check.
Mechanism references checked 26 October 2026: AbortController.abort and Node.js HTTP response lifecycle. The fixture, barriers, maintenance record and team exercise are original LockedIn Labs teaching material.