HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 16“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
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:
Define an SSE stream as UTF-8 events separated by a blank line, with event, data, id, and retry fields.
Explain why a tutor POST uses fetch plus a parser, and when a cookie-authenticated GET may use EventSource.
Draw the path from the lesson player through session checks to a TokenSource, and show completion never moves.
Encode multi-line data fields and ignore comment heartbeats the way the HTML parser does.
Parse chunks that split an event across TCP packets, including a single leading space after the colon.
Send JSON errors for auth and validation before the response commits to text/event-stream.
Represent idle, streaming, complete, and incomplete panel states so a partial draft is not stored as finished text.
Keep provider credentials on the server and keep prompts out of shared logs.
Choose SSE, a job-status poll, or a WebSocket from the direction of the bytes and the latency budget.
Test the encoder, the unauthorized short-circuit, and an aborted stream without a network call.
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 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:
Line
Meaning
event: token
Event name. The default name, when this line is absent, is message.
data: hello
One line of the payload. Several data lines in one block are joined with \n.
id: 7
Last event id the client should echo as Last-Event-ID on a reconnect.
retry: 10000
Reconnection delay in milliseconds, for clients that auto-reconnect.
: ping
A 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:
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
event
data JSON
Panel does
meta
requestId, promptVersion
Stores the id. Shows "Writing…".
token
text fragment
Appends text.
done
finish: stop or length
Marks the draft complete.
error
reason
Marks 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. */
exporttypeTenantId=string;
exporttypeUserId=string;
exportinterfaceStreamRequest{
tenantId: TenantId;
userId: UserId;
lessonId:string;
lessonVersion:number;
question:string;
/** Set by the server from the session. Never trust the JSON body for this. */
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
importtype{ TutorEvent }from"./types.js";
exportinterfaceSseBlock{
event:string;
data:string;
id?:string;
}
/** One leading space after ":" is the spec's optional separator, not payload. */
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.
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.
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
Situation
HTTP
Learner sees
Source called
No session
401 JSON
Sign-in prompt. Lesson still visible if it was public.
No
Lesson locked
403 JSON
Lesson without a tutor panel
No
Empty or huge question
400 JSON
Inline validation
No
First byte already sent, then source throws
200 SSE
Incomplete draft, reason unavailable
Yes
Learner presses Stop
200 SSE, then close
Incomplete draft, reason aborted
Stopped
Cap reached
200 SSE
Complete draft, finish length
Stopped 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.
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.
Draw the sequence in this lesson with your service names. Mark the line where the status becomes 200 and can no longer change.
Implement encode, parse, openTutorStream, and reducePanel as specified, including the locked-section test.
Add the abort test and the comment-heartbeat test.
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.
List meters: time to first token event, stream duration, abort rate, error rate by reason, fragment count. Label any target numbers as illustrative.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.