AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 16

    Streaming AI Responses with Server-Sent Events

    TechLearningPro's "Explain this section" button used to wait for the whole draft.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 16 · AI and LLM Application Fundamentals

    Lesson Overview

    TechLearningPro's "Explain this section" button used to wait for the whole draft. On a long section the edge closed the idle response, the player showed a spinner, and learners clicked again. The API started a second generation while the first was still running on the provider. Support could see the finished paragraph only in a log. The learner never saw a token.

    That failure is a transport problem sitting on top of the boundary from Modern Full-Stack Architecture and AI-Native Applications. The model is still a server-side dependency. Completion is still a quiz fact. What changes is when bytes reach the browser. Server-Sent Events (SSE) is the HTML standard for a one-way stream of named events over HTTP. The server writes text/event-stream. The player paints each token event as it arrives, and a stop control aborts the work.

    This lesson builds that path with a local token source. You will encode and parse SSE the way the HTML Living Standard defines it, refuse to open the stream until the session may read the section, and keep a partial draft from looking complete when the connection dies. No provider SDK and no live key. When you later bind a real model, you read that provider's current streaming guide and adapt it behind the same TokenSource port. Token prediction is the vocabulary for why text arrives in pieces. This lesson is the HTTP contract around those pieces.

    Planning assumptions, labeled so they are not a capacity plan:

    • The tutor explains one authorized section. Output stays under a few hundred tokens.
    • The player uses fetch and a ReadableStream, because the request is a POST that carries the question. The browser EventSource API is GET-only and cannot attach an arbitrary Authorization header.
    • Illustrative timeouts: 1.5 seconds to the first token event, 8 seconds for the whole stream. Replace them with measurements from your edge.
    • A dropped generation is not restarted by the server. A new click is a new request id.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Define an SSE stream as UTF-8 events separated by a blank line, with event, data, id, and retry fields.
    2. Explain why a tutor POST uses fetch plus a parser, and when a cookie-authenticated GET may use EventSource.
    3. Draw the path from the lesson player through session checks to a TokenSource, and show completion never moves.
    4. Encode multi-line data fields and ignore comment heartbeats the way the HTML parser does.
    5. Parse chunks that split an event across TCP packets, including a single leading space after the colon.
    6. Send JSON errors for auth and validation before the response commits to text/event-stream.
    7. Represent idle, streaming, complete, and incomplete panel states so a partial draft is not stored as finished text.
    8. Abort the token source when the client disconnects, using the AbortSignal pattern from Modern JavaScript, Async Programming and Web APIs.
    9. Keep provider credentials on the server and keep prompts out of shared logs.
    10. Choose SSE, a job-status poll, or a WebSocket from the direction of the bytes and the latency budget.
    11. Test the encoder, the unauthorized short-circuit, and an aborted stream without a network call.
    12. Name the cost failure mode: an automatic reconnect that starts a second paid generation.

    Prerequisites

    • You can read the tutor boundary in lesson 1: the server holds the model call, the browser holds no provider credential, and a timeout still leaves the lesson readable.
    • You can follow an async iterator and an AbortSignal. Lesson 4 is the refresher. Node.js 20 or newer is the lab runtime, pinned the same way as that lesson. Confirm with node --version.
    • You can read TypeScript under "strict": true. The language lesson is TypeScript for Production Full-Stack Development. A primer lives at /learn/typescript.
    • You know HTTP status codes well enough to see that a 401 must be a normal JSON response, because a stream cannot change its status after the first byte.
    • You do not need a model account. The lab's ScriptedTokenSource yields strings from memory.

    If a proxy in your environment buffers responses until they complete, the player will still look "stuck" after this code is correct. The operations notes below name the headers. Verify them against your proxy's current documentation.

    Detailed Core Concepts

    What the learner is waiting on

    A section explanation is a sequence of text fragments. The product value is the first readable words, then a steady append, then a clear end. Waiting for the last fragment makes the interface feel broken even when the model is healthy. Streaming exists so the player can paint fragment 1 while fragment 20 is still being produced.

    The fragments are still a draft. They do not set lesson_progress.completed_at. They do not get a "complete" badge in the panel until a done event arrives. A connection drop leaves an incomplete draft on screen and the lesson body untouched.

    The SSE record format

    The HTML Living Standard defines the event stream format. The response Content-Type is text/event-stream. The body is UTF-8. Events are blocks separated by a blank line. Inside a block, each line is a field:

    LineMeaning
    event: tokenEvent name. The default name, when this line is absent, is message.
    data: helloOne line of the payload. Several data lines in one block are joined with \n.
    id: 7Last event id the client should echo as Last-Event-ID on a reconnect.
    retry: 10000Reconnection delay in milliseconds, for clients that auto-reconnect.
    : pingA comment. The line starts with :. Clients ignore it. Proxies still see bytes.

    The specification strips one leading space after the colon. data: hello and data:hello carry the same payload hello. A second space would be part of the data. Field names and the rules for a null character inside id are in the spec; this lab rejects newlines inside event and id at encode time so we never emit a block the parser would split.

    A block with only a comment, or only an event name and no data, does not dispatch an application event. Heartbeats are comments for that reason. They keep the socket warm without appending text to the tutor panel.

    Official references, which you should re-read when you implement against a browser:

    EventSource and fetch

    The browser built-in EventSource opens a GET request, follows the reconnect rules, and exposes onmessage plus listeners for custom event names. It sends cookies for a same-origin URL. Its constructor does not take a request body or a custom header map. That is a good fit for a public or cookie-authenticated stream that only needs a URL.

    The tutor needs a JSON body: tenant comes from the session, and the question comes from the learner. This course's player uses fetch with POST, reads response.body as a ReadableStream, and runs the parser in this lesson. You control retry. You do not get EventSource's automatic reconnect, which is what you want for a paid generation. MDN documents that an HTTP 204 response causes EventSource to close without reconnecting; confirm that sentence on the current MDN page before you depend on it. With fetch, you simply do not start a second request unless the learner asks.

    HTTP/1.1 browsers limit how many connections they open to one host. Several long-lived streams on one page can stall images and API calls. Keep one tutor stream per open panel. HTTP/2 multiplexes streams on one connection; confirm the current browser limits rather than hard-coding a number from an old article.

    Events this product emits

    eventdata JSONPanel does
    metarequestId, promptVersionStores the id. Shows "Writing…".
    tokentext fragmentAppends text.
    donefinish: stop or lengthMarks the draft complete.
    errorreasonMarks the draft incomplete. Lesson body stays.

    meta is sent after authorization, as the first event, so a client that sees tokens without meta can treat the stream as corrupt. done is the only event that means "you may keep this as a finished draft." finish: length means the server stopped at maxTokens. The text is still a finished draft under that cap; the UI can show that it was cut short. An error is never a finished draft.

    Once the server has written the SSE status line, it cannot switch to HTTP 500. Later failures travel as an error event and then the body ends.

    Resume, retry, and money

    Last-Event-ID lets a client say "I already saw events through this id." That header is useful when the server stored the events and can replay them without calling the model. This lab does not store them. A production resume log is a separate table keyed by requestId, written as events are flushed, and read only for the same tenant and user. Without that table, the server ignores Last-Event-ID and the client does not auto-retry. A silent second POST is a second bill and a second draft that may not match the words already on screen.

    User-initiated retry creates a new requestId. The panel replaces the incomplete draft only after the learner confirms, or it starts a fresh panel. Do not concatenate a new stream onto an old one unless both share an id you can prove.

    Streams versus jobs

    Token streaming fits a section explanation inside the player's latency budget. A summary of an entire course does not. That work is a job with a status URL the client can poll, which API Design with REST, OpenAPI and GraphQL Concepts already frames as work that must not hold one HTTP request open for minutes. Lesson 19's router will refuse to put course-scale generation on this stream.

    Structured JSON from Structured Outputs, JSON Mode and Function Calling is a poor candidate for token-by-token rendering. Partial JSON does not parse. If a feature must stream and end as JSON, buffer the token texts until done, then run the lesson 15 parser. Paint a progress state in the meantime, not a half object.

    WebSockets

    A WebSocket is a two-way session. Use it when the learner must send mid-stream — cancel is already covered by aborting fetch, so it is not a reason to open a socket. Tool approvals and live collaboration are reasons, and they belong to later agent lessons. A socket is a second protocol to authenticate, time out, and scale. SSE stays on ordinary HTTP, which your existing access logs and proxies already understand.

    Architecture and Request Flow

    flowchart TB
      subgraph browser [Browser]
        Player[Lesson player]
        Parser[SSE parser]
      end
    
      subgraph server [TechLearningPro API]
        Auth[Session and lesson ACL]
        Gate[Validate question and caps]
        Session[Stream session]
      end
    
      subgraph model [Model boundary]
        Source[TokenSource port]
      end
    
      Player -->|POST question| Auth
      Auth -->|401 or 403 JSON| Player
      Auth --> Gate
      Gate -->|400 JSON| Player
      Gate --> Session
      Session -->|text/event-stream| Parser
      Session --> Source
      Parser -->|append tokens| Player
      Player -->|abort on Stop| Session

    Authorization and validation finish before the Content-Type switches to text/event-stream. The token source sees an AbortSignal tied to the client connection. PostgreSQL is not on this diagram because this request does not write completion. A separate progress route remains the only writer, as in lesson 1.

    sequenceDiagram
      participant Player
      participant API
      participant Source as TokenSource
      Player->>API: POST /tutor/stream
      API->>API: session, ACL, question length
      API-->>Player: 200 text/event-stream
      API-->>Player: event meta
      API->>Source: stream with AbortSignal
      Source-->>API: text fragment
      API-->>Player: event token
      Source-->>API: text fragment
      API-->>Player: event token
      API-->>Player: event done
      Note over Player: Stop aborts the signal and Source returns

    Step-by-step Implementation

    The lab lives in packages/tutor-stream/ and compiles with "strict": true. Run it with Node's type stripper or a local tsc. Nothing opens a socket to a model host.

    Step 1: Name the events and the port

    packages/tutor-stream/src/types.ts

    typescript
    /** Ids arrive as strings from the session layer. Brand them in the auth package. */
    export type TenantId = string;
    export type UserId = string;
    export interface StreamRequest {
    tenantId: TenantId;
    userId: UserId;
    lessonId: string;
    lessonVersion: number;
    question: string;
    /** Set by the server from the session. Never trust the JSON body for this. */
    callerMayReadSection: boolean;
    promptVersion: string;
    maxTokens: number;
    }
    export interface TokenSource {
    /**
    * Yields text fragments in order.
    * Must return promptly when signal is aborted.
    * Must not throw secrets in error messages.
    */
    stream(input: StreamRequest, signal: AbortSignal): AsyncIterable<string>;
    }
    /** Application events after the SSE parser has decoded a block. */
    export type TutorEvent =
    | { event: "meta"; requestId: string; promptVersion: string }
    | { event: "token"; text: string }
    | { event: "done"; finish: "stop" | "length" }
    | { event: "error"; reason: "timeout" | "aborted" | "unavailable" };
    export type PanelState =
    | { status: "idle" }
    | { status: "streaming"; text: string; requestId: string }
    | { status: "complete"; text: string; requestId: string; finish: "stop" | "length" }
    | { status: "incomplete"; text: string; requestId: string; reason: string };

    maxTokens counts fragments from the source in this lab. A production adapter counts provider output tokens and documents the unit in the adapter, not in the panel.

    Step 2: Encode and parse the wire format

    packages/tutor-stream/src/sse.ts

    typescript
    import type { TutorEvent } from "./types.js";
    export interface SseBlock {
    event: string;
    data: string;
    id?: string;
    }
    /** One leading space after ":" is the spec's optional separator, not payload. */
    function splitField(line: string): { field: string; value: string } | "comment" {
    if (line.startsWith(":")) return "comment";
    const colon = line.indexOf(":");
    if (colon === -1) return { field: line, value: "" };
    let value = line.slice(colon + 1);
    if (value.startsWith(" ")) value = value.slice(1);
    return { field: line.slice(0, colon), value };
    }
    /**
    * Emit one SSE block, including the trailing blank line.
    * Newlines inside data become extra data: lines, which parsers join with "\\n".
    */
    export function encodeSseBlock(input: { event: string; data: string; id?: string }): string {
    if (input.event.length === 0 || /[\r\n]/.test(input.event)) {
    throw new Error("bad_event_name");
    }
    if (input.id !== undefined && (input.id.length === 0 || /[\r\n\0]/.test(input.id))) {
    throw new Error("bad_event_id");
    }
    const lines: string[] = [];
    if (input.id !== undefined) lines.push(`id: ${input.id}`);
    lines.push(`event: ${input.event}`);
    for (const part of input.data.split("\n")) lines.push(`data: ${part}`);
    return `${lines.join("\n")}\n\n`;
    }
    /** Comment block. Clients must not treat this as a token. */
    export function encodeSseComment(comment: string): string {
    const safe = comment.replace(/[\r\n]/g, " ");
    return `: ${safe}\n\n`;
    }
    export function createSseParser(onBlock: (block: SseBlock) => void): {
    push(chunk: string): void;
    } {
    let buffer = "";
    return {
    push(chunk: string) {
    buffer += chunk.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    let splitAt = buffer.indexOf("\n\n");
    while (splitAt !== -1) {
    const raw = buffer.slice(0, splitAt);
    buffer = buffer.slice(splitAt + 2);
    const block = parseBlock(raw);
    if (block) onBlock(block);
    splitAt = buffer.indexOf("\n\n");
    }
    },
    };
    }
    function parseBlock(raw: string): SseBlock | undefined {
    let eventName = "message";
    let id: string | undefined;
    const dataLines: string[] = [];
    let sawData = false;
    for (const line of raw.split("\n")) {
    if (line === "") continue;
    const field = splitField(line);
    if (field === "comment") continue;
    if (field.field === "event" && field.value.length > 0) eventName = field.value;
    if (field.field === "id") id = field.value;
    if (field.field === "data") {
    sawData = true;
    dataLines.push(field.value);
    }
    }
    if (!sawData) return undefined;
    return { event: eventName, data: dataLines.join("\n"), id };
    }
    export function encodeTutorEvent(event: TutorEvent, id?: string): string {
    return encodeSseBlock({ event: event.event, data: JSON.stringify(eventData(event)), id });
    }
    function eventData(event: TutorEvent): object {
    if (event.event === "meta") {
    return { requestId: event.requestId, promptVersion: event.promptVersion };
    }
    if (event.event === "token") return { text: event.text };
    if (event.event === "done") return { finish: event.finish };
    return { reason: event.reason };
    }

    JSON.stringify is safe for these objects because every field is a string you set. Do not stringify a raw provider body you have not inspected.

    Step 3: Decide JSON versus a stream

    packages/tutor-stream/src/session.ts

    typescript
    import type { StreamRequest, TokenSource, TutorEvent } from "./types.js";
    import { encodeSseComment, encodeTutorEvent } from "./sse.js";
    export type StreamOpen =
    | { kind: "json"; status: 400 | 401 | 403; error: string }
    | { kind: "sse"; events: AsyncIterable<string> };
    const MAX_QUESTION = 500;
    export function openTutorStream(
    request: StreamRequest,
    source: TokenSource,
    signal: AbortSignal,
    requestId: string,
    ): StreamOpen {
    if (!request.callerMayReadSection) {
    return { kind: "json", status: 403, error: "forbidden" };
    }
    const question = request.question.trim();
    if (question.length === 0 || question.length > MAX_QUESTION) {
    return { kind: "json", status: 400, error: "bad_question" };
    }
    if (request.maxTokens < 1 || request.maxTokens > 400) {
    return { kind: "json", status: 400, error: "bad_token_cap" };
    }
    return {
    kind: "sse",
    events: generate(request, source, signal, requestId),
    };
    }
    async function* generate(
    request: StreamRequest,
    source: TokenSource,
    signal: AbortSignal,
    requestId: string,
    ): AsyncIterable<string> {
    yield encodeTutorEvent({
    event: "meta",
    requestId,
    promptVersion: request.promptVersion,
    });
    yield encodeSseComment("ping");
    let count = 0;
    try {
    for await (const text of source.stream(request, signal)) {
    if (signal.aborted) {
    yield encodeTutorEvent({ event: "error", reason: "aborted" });
    return;
    }
    if (text.length === 0) continue;
    count += 1;
    yield encodeTutorEvent({ event: "token", text }, String(count));
    if (count >= request.maxTokens) {
    yield encodeTutorEvent({ event: "done", finish: "length" });
    return;
    }
    }
    yield encodeTutorEvent({ event: "done", finish: "stop" });
    } catch {
    yield encodeTutorEvent({ event: "error", reason: "unavailable" });
    }
    }

    The catch maps every source failure to unavailable. Log the internal error beside requestId on the server. Do not put error.message into the SSE payload. Provider messages sometimes echo request content.

    packages/tutor-stream/src/scripted-source.ts

    typescript
    import type { StreamRequest, TokenSource } from "./types.js";
    /** In-memory fragments. This is not a model and it does not read the environment. */
    export class ScriptedTokenSource implements TokenSource {
    private readonly parts: readonly string[];
    constructor(parts: readonly string[]) {
    this.parts = parts;
    }
    async *stream(_input: StreamRequest, signal: AbortSignal): AsyncIterable<string> {
    for (const part of this.parts) {
    if (signal.aborted) return;
    yield part;
    }
    }
    }

    Step 4: Reduce events in the player

    packages/tutor-stream/src/panel.ts

    typescript
    import type { PanelState, TutorEvent } from "./types.js";
    export function reducePanel(state: PanelState, event: TutorEvent): PanelState {
    if (event.event === "meta") {
    return { status: "streaming", text: "", requestId: event.requestId };
    }
    if (event.event === "token") {
    if (state.status !== "streaming") return state;
    return { ...state, text: state.text + event.text };
    }
    if (event.event === "done") {
    if (state.status !== "streaming") return state;
    return {
    status: "complete",
    text: state.text,
    requestId: state.requestId,
    finish: event.finish,
    };
    }
    const requestId = state.status === "idle" ? "" : state.requestId;
    const text = state.status === "idle" ? "" : state.text;
    return { status: "incomplete", text, requestId, reason: event.reason };
    }

    Wire fetch in the player with AbortController. Pass signal to fetch. On Stop, call abort(). Read response.body with getReader(), decode UTF-8 with TextDecoder in stream mode, and push strings into createSseParser. Parse the JSON data and narrow it to TutorEvent before calling reducePanel. If response.ok is false, read a short JSON error and do not start the parser. Accessible UI Engineering and Design Systems covers the live region: announce "explanation ready" when status becomes complete, and do not fire an assertive alert on every token.

    Step 5: Commit the HTTP response only after the gate

    On Node's node:http server, call writeHead with status 401, 403, or 400 and Content-Type: application/json when openTutorStream returns kind: "json". When it returns kind: "sse", call writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform" }), then flushHeaders() if you are on ServerResponse, then write each encoded string. If the response closes before writableFinished, abort the controller that you passed into openTutorStream. That is the disconnect path.

    X-Accel-Buffering: no is an nginx response header that asks nginx not to buffer the stream. Node ignores it. Add it only when the hop in front of you is nginx, and confirm the directive in the current nginx proxy documentation. Do not gzip this route unless you have tested that the compression layer flushes. A buffer that waits for the full body undoes the lesson.

    Step 6: Run

    From packages/tutor-stream:

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/session.test.ts

    Cleanup is deleting the package if you created it only for the lab. Do not point TokenSource at a live host from this exercise.

    Security

    • Authentication runs before openTutorStream. A missing session is HTTP 401 JSON from the route, with the token source uncalled. The lab function starts at the ACL flag; the route must set that flag from the session.
    • Authorization is the lesson ACL. callerMayReadSection === false returns 403 and does not iterate the source. A stream of a locked lesson is a data export, one token at a time.
    • Input validation caps the question at 500 characters and the fragment cap at 400. The cap is a cost and a latency control.
    • Secrets stay in the future provider adapter. ScriptedTokenSource reads no environment variable. When you add an adapter, load the credential from the process environment or a secret manager. Never write it into an SSE data line.
    • Tenant isolation is the session's tenant. Do not accept tenantId from the browser as the authority. Log requestId, tenantId, userId, promptVersion, fragment count, and the terminal event. Do not log the question or the fragments in a shared sink.
    • Prompt injection can still arrive inside question. Streaming does not make the model a security boundary. The draft cannot complete a lesson. Later safety lessons add output checks; this lesson keeps the draft off the system of record.

    The browser can read every event. Do not put another learner's progress, a system-prompt dump, or a stack trace in token or error.

    Error Handling

    SituationHTTPLearner seesSource called
    No session401 JSONSign-in prompt. Lesson still visible if it was public.No
    Lesson locked403 JSONLesson without a tutor panelNo
    Empty or huge question400 JSONInline validationNo
    First byte already sent, then source throws200 SSEIncomplete draft, reason unavailableYes
    Learner presses Stop200 SSE, then closeIncomplete draft, reason abortedStopped
    Cap reached200 SSEComplete draft, finish lengthStopped at cap

    Do not retry inside generate. A retry can bill a second generation while the first is still producing. One new request after an explicit click is the policy, with a new requestId.

    If the client sends Last-Event-ID and you have no stored events for that id and tenant, ignore the header. Replaying from the model is not replay.

    Testing

    packages/tutor-stream/src/session.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { reducePanel } from "./panel.js";
    import { ScriptedTokenSource } from "./scripted-source.js";
    import { createSseParser, encodeSseBlock } from "./sse.js";
    import { openTutorStream } from "./session.js";
    import type { StreamRequest, TutorEvent } from "./types.js";
    const request: StreamRequest = {
    tenantId: "ten_01",
    userId: "usr_01",
    lessonId: "lesson-16",
    lessonVersion: 1,
    question: "What does the server stream?",
    callerMayReadSection: true,
    promptVersion: "tutor-explain-3",
    maxTokens: 8,
    };
    test("round-trips a block split across chunks", () => {
    const encoded = encodeSseBlock({ event: "token", data: "hello", id: "1" });
    const seen: string[] = [];
    const parser = createSseParser((block) => seen.push(`${block.event}:${block.data}`));
    parser.push(encoded.slice(0, 5));
    assert.equal(seen.length, 0);
    parser.push(encoded.slice(5));
    assert.deepEqual(seen, ["token:hello"]);
    });
    test("does not open the source when the section is locked", async () => {
    let called = false;
    const source = {
    async *stream() {
    called = true;
    yield "nope";
    },
    };
    const opened = openTutorStream(
    { ...request, callerMayReadSection: false },
    source,
    new AbortController().signal,
    "req_1",
    );
    assert.equal(opened.kind, "json");
    assert.equal(called, false);
    });
    test("marks the panel complete only after done", async () => {
    const opened = openTutorStream(
    request,
    new ScriptedTokenSource(["The ", "server ", "writes events."]),
    new AbortController().signal,
    "req_2",
    );
    assert.equal(opened.kind, "sse");
    if (opened.kind !== "sse") return;
    let state = reducePanel({ status: "idle" }, {
    event: "meta",
    requestId: "req_2",
    promptVersion: request.promptVersion,
    } satisfies TutorEvent);
    const parser = createSseParser((block) => {
    const body = JSON.parse(block.data) as { text?: string; finish?: "stop" | "length" };
    if (block.event === "token" && body.text) {
    state = reducePanel(state, { event: "token", text: body.text });
    }
    if (block.event === "done" && body.finish) {
    state = reducePanel(state, { event: "done", finish: body.finish });
    }
    });
    for await (const chunk of opened.events) parser.push(chunk);
    assert.equal(state.status, "complete");
    if (state.status === "complete") assert.match(state.text, /server writes events/);
    });

    Add a fourth test that aborts the signal before iteration and expects the scripted source to yield nothing. Add a fifth that a comment block does not change panel text. The locked-section test is the security property: forbidden content does not reach the port.

    Performance and Cost

    Streaming changes latency the learner feels. It does not make tokens free.

    • Time to first event is the metric to put on the player budget. An illustrative target for this feature is 1.5 seconds to meta plus the first token, and 8 seconds until done or error. Measure both. A fast first token with a stalled rest is still a stuck panel; the idle comment every 15 seconds is for proxies, and an idle timeout on the server should still end the stream with error / timeout if you add a timer around the iterator.
    • Fragment cap of 400 matches the output cap in lesson 1. Raising it needs a measured reason.
    • No automatic retry. Reconnect storms during an incident are how a tutor button becomes the largest line on the bill.
    • One stream per panel. Extra streams hold file descriptors and provider concurrency.
    • Abort on disconnect. Lesson 4 stated the rule: if the UI stopped and the bill did not, the signal never reached the source. generate checks signal.aborted between fragments. The adapter you write later must pass that signal into the provider call.
    • Do not buffer the full body in a proxy or in gzip. The bytes you already generated should be on the wire.
    • Cache only a finished public explanation, keyed by tenant, lesson version, prompt version, and a hash of the question. Do not cache a partial stream. Do not share a personalized draft across users.

    Illustrative ratio: a double-click that starts two generations costs about twice the tokens of one explanation. The UI disables the button while status === "streaming" and aborts on Stop. That is the cost control you can ship before a live provider exists.

    Knowledge Check

    1. What problem does SSE solve for the tutor?

    It gets authorized draft text onto the screen as fragments, with a defined end, while the lesson and the completion fact stay independent. Without it, learners retry a slow JSON call and the platform pays for overlapping generations they never read.

    2. What alternatives exist, and when would you choose each?

    fetch plus this parser fits a POST that carries a question and must not auto-reconnect. EventSource fits a cookie-authenticated GET that should reconnect and does not need custom headers. A status poll fits a long job. A WebSocket fits a session where the client sends messages during the generation. Buffered JSON fits a short structured object that you will parse only when it is complete.

    3. Which data, identity, and trust boundaries matter?

    The browser is untrusted. The session decides callerMayReadSection and the tenant. The token source runs on the server. Events are visible to the caller, so they may contain the draft and must not contain credentials, other tenants' text, or raw provider errors. Completion stays on the progress route.

    4. What can fail, and how should the system respond?

    Auth and validation fail as JSON, with no stream and no model call. After the stream starts, source failures and aborts become error events and an incomplete panel. Hitting the cap becomes done with finish: length. The lesson page still renders.

    5. How would you test quality, security, performance, and cost?

    Tests cover a split chunk, a locked section that never calls the source, and a panel that becomes complete only after done. Security review checks that the route, not the body, sets the ACL flag, and that logs omit fragments. Performance review checks time to first event and proxy buffering. Cost review checks that abort reaches the source and that the client does not auto-POST on error.

    Hands-on Assignment

    Lab note. Use ScriptedTokenSource. Do not create a provider account or paste a key into the repo.

    Problem. Ship a design package and the TypeScript slice for a streaming section explanation on TechLearningPro. The lesson remains readable when the stream stops early. Completion is out of scope for this route.

    Tasks.

    1. Draw the sequence in this lesson with your service names. Mark the line where the status becomes 200 and can no longer change.
    2. Implement encode, parse, openTutorStream, and reducePanel as specified, including the locked-section test.
    3. Add the abort test and the comment-heartbeat test.
    4. Write the player rules: button disabled while streaming, Stop aborts, incomplete text is visually distinct from a complete draft, and a live region announces completion once.
    5. List meters: time to first token event, stream duration, abort rate, error rate by reason, fragment count. Label any target numbers as illustrative.
    6. State what you will re-read in the provider's streaming guide before replacing ScriptedTokenSource, and which port method stays stable.

    Deliverable. Diagram, source with no secrets, test output, the meter list, and a short note on why this route does not auto-reconnect.

    Challenge. Two tenants share a process. Show that a log line for tenant A's stream cannot include tenant B's question. Describe the resume table key you would require before honoring Last-Event-ID, and why a missing row must not call the token source again.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and privacy 20%. Tests and failure behavior 20%. Documentation of trade-offs 15%.

    Common Mistakes

    1. Buffering the stream at the proxy. Symptom: the panel jumps from empty to finished. Cause: gzip or an nginx buffer held the body. Fix: flush, and confirm X-Accel-Buffering only if you run nginx.
    2. Using EventSource for a POST with a bearer token. Symptom: the request has no body and no Authorization header. Cause: the constructor cannot send them. Fix: fetch and the parser in this lesson, or a cookie session on a GET if that matches your auth design.
    3. Auto-reconnect that starts a new generation. Symptom: one click, two bills, two drafts. Cause: EventSource retry, or a client retry loop, with no stored events. Fix: retry only from storage, or only after a click, with a new requestId.
    4. Opening the stream before the ACL check. Symptom: a locked excerpt appears as tokens, then a 403 you can no longer send. Cause: writeHead(200) ran first. Fix: JSON errors before SSE.
    5. Treating partial text as a finished draft. Symptom: a cut-off sentence is saved as the explanation. Cause: the UI set complete when the socket closed. Fix: complete only on done.
    6. Ignoring abort on the server. Symptom: Stop clears the panel and the source keeps yielding. Cause: the signal stopped at fetch. Fix: abort the controller tied to res close and pass it to TokenSource.
    7. Logging every fragment. Symptom: lesson text shows up in a vendor log product. Cause: debug logging of data. Fix: log ids, versions, counts, and the terminal reason.
    8. Parsing JSON on each token for a structured feature. Symptom: exceptions on incomplete objects, or worse, a loose parser accepts a prefix. Cause: lesson 15's schema was applied mid-stream. Fix: buffer until done, then parse.
    9. Heartbeats dispatched as tokens. Symptom: the word "ping" appears in the explanation. Cause: a comment was encoded as data:. Fix: use encodeSseComment and a parser that drops colon lines.
    10. A second stream for the same panel. Symptom: sentences interleave. Cause: a re-render opened another fetch without aborting the first. Fix: one controller per panel, abort on cleanup.

    Summary

    Server-Sent Events let TechLearningPro show a tutor draft while it is being produced, using a documented HTTP format and a server-side token source. Authorization happens before the response commits to text/event-stream. The panel is complete only after done. Disconnect aborts the source so a stopped click does not keep spending. The browser never holds a provider credential, and this lab never contacts a provider. The port is what you will bind to a current streaming API after you read that provider's guide.

    Next Lesson Preview

    Embeddings, Similarity Search and Vector Fundamentals takes the next step in how the platform finds the right lesson text before it asks a model to talk. You will compute cosine similarity in TypeScript, keep each tenant's vectors separate, and see why a keyword miss on "finish a lesson" is a geometry problem before it is a prompt problem.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.