16 min read
Streaming AI responses with SSE
In one sentence: With streaming, the model’s API sends the answer piece by piece, as it writes it, as SSE events. Your backend translates them into its own and passes them on to the browser at once: Carmen sees the first word as soon as it exists, and if she closes the tab, the shop cancels the call.
What you will learn
- Explain the difference between time to first token and total time, and why streaming changes what the person waiting notices.
- Read the events Claude’s API sends and translate them into your own API’s events.
- Read a stream from the browser with fetch and a reader, and cancel the call to the model when the customer leaves.
- Handle an error that arrives halfway through the answer, and configure nginx so it doesn’t hold back the stream.
Before you start, read: 01-model-apis.md phase-4/08-real-time.md phase-8/04-reverse-proxy.md
The problem
Section titled “The problem”Imagine that Carmen asks and the screen stays still. Lesson 1’s shop waits for the model’s whole answer before sending anything. Carmen doesn’t know whether the assistant is thinking or has frozen, and she reloads the page: another question, paid for again.
In the AI chats you use, the text appears word by word. The answer doesn’t finish sooner: it starts sooner. In Phase 4 we told you that model APIs send their answers piece by piece with SSESSE stands for Server-Sent Events.A way for the server to notify the client as soon as something happens. The client makes a normal HTTP request and the server leaves the response open, writing an event into it, a few lines of text, every time there’s news. It only goes one way, from the server to the client.Go to definition. Here you see it, from the model to the shop and from the shop to the browser.
The analogy
Section titled “The analogy”The analogy
At a conference, the simultaneous interpreter doesn’t wait for the speaker to finish: they translate sentence by sentence, as they hear it, and you listen almost at the same time. The consecutive interpreter waits until the end and tells you everything at once: meanwhile, the room sits in silence.
Streaming is the simultaneous interpreter. And if you get up and leave, the booth notices and stops translating for you.
Where the analogy breaks down
- An interpreter changes the words. The shop doesn’t touch the model’s text: it only changes the wrapping, the names of the events.
- What’s said is said, in a stream too. But if the model refuses halfway, the last event tells the browser to replace what it has shown with a fixed sentence.
- The speaker keeps talking even if the room empties, and so does the model, if nobody hangs up: that’s why the shop hangs up when Carmen leaves.
How it really works
Section titled “How it really works”What the person waiting notices: the first piece, not the last
Section titled “What the person waiting notices: the first piece, not the last”The model writes the answer piece by piece, in order. Without streaming, the shop gathers them all and sends the answer at the end. With streaming, it sends each piece as soon as it arrives:
| Whole answer (lesson 1) | Streaming | |
|---|---|---|
| First text on Carmen’s screen | When the model finishes | When the model writes the first piece |
| Time until the last word | The same | The same |
| What she sees while she waits | Nothing | The text, growing |
What Carmen notices is the Time to first tokenHow long the first word of a streamed answer takes to appear. It is what the person waiting notices: with streaming, a long answer can be read long before it ends.Go to definition: how long the first piece of the answer takes to arrive. It’s the cousin of web pages’ TTFBTTFB stands for time to first byte.The time to the first byte of the response, counted from the start of the navigation. It includes DNS, the handshakes and the wait for the server.Go to definition, for an answer that’s written as it arrives. You’ll measure it in “Try it.”
The first piece doesn’t come out instantly: before it, the model reads the question and thinks a little. The longer the answer, the more the difference shows.
What the API sends: its events, in order
Section titled “What the API sends: its events, in order”With "stream": true in the request, Claude’s API answers with a stream of SSE events, in the format from Phase 4: an event: line, a data: line with JSON and a blank line. This is the start and the end of one from the shop’s fake model, which imitates the API, without the events in the middle:
event: message_startdata: {"type":"message_start","message":{"id":"msg_fake_3","type":"message","role":"assistant","model":"claude-haiku-5-5","content":[],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":120,"output_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}}
…
event: content_block_startdata: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
event: content_block_deltadata: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"I'm the "}}
event: content_block_deltadata: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"fake mod"}}
…
event: message_deltadata: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null},"usage":{"output_tokens":30}}
event: message_stopdata: {"type":"message_stop"}The events always arrive in this order:
message_start: the message, still empty, with the input tokens.- For each block,
content_block_start, its pieces incontent_block_deltaandcontent_block_stop. In a text block, each piece is atext_delta; in a thinking one,thinking_deltaandsignature_delta. message_delta: why it stopped (stop_reason) and the output tokens.message_stop: the end.
In between, a ping may arrive, so the connection doesn’t look dead. And if something fails halfway, an error event: the answer had already started with a 200, so the failure can’t go in the status code.
The shop doesn’t read this by hand. The SDK asks for the stream with messages.stream(), which sends the same request with "stream": true:
// The same question, with the answer streamed (lesson 2): messages.stream() sends the same request// with "stream": true, and the API answers with events (Server-Sent Events) as the model writes.// What it returns is read event by event and, at the end, finalMessage() gives the whole message,// as messages.create() would. Calling it doesn't wait for anything: the errors (a 429, a network// cut) come out when reading the events. signal also fires when the customer leaves: the shop// stops receiving an answer nobody is going to read.export function askStreaming(client: Anthropic, messages: Message[], signal: AbortSignal) { return client.messages.stream( modelRequest(messages, instructions, { model: config.MODEL, effort: config.EFFORT }), { signal }, );}What it returns is read event by event, and at the end, finalMessage() gives the whole message, the same one messages.create() would give: with its text, its stop_reason and its usage.
One route, two answers: Accept decides
Section titled “One route, two answers: Accept decides”The route is still POST /v2/assistant. What changes is what the client asks for in the Accept header:
// Whole or streamed? The customer says so in Accept, the header with the content types it wants to// receive: with text/event-stream, events; with anything else (application/json, the */* curl// sends, or none), the whole answer in JSON, as in lesson 1. It's one route that answers in two// ways, because what's asked for is the same: the assistant's answer. Hono's accepts understands// the header's weights (text/event-stream;q=0 means "not that").function wantsStream(c: Context): boolean { const format = accepts(c, { header: 'Accept', supports: ['application/json', 'text/event-stream'], default: 'application/json', }); return format === 'text/event-stream';}With text/event-stream, events; with anything else, lesson 1’s whole JSON. It’s Phase 2’s Content negotiationWhen the client says in its headers what it prefers (a language, a format, a compression) and the server picks, among the versions it has of the same address, the one that fits best. The Vary header warns caches that the response depends on those headers.Go to definition: what’s asked for is the same, the assistant’s answer, in two formats. A frontend that already used the JSON keeps working without changing anything.
The shop’s events, not the model’s
Section titled “The shop’s events, not the model’s”The shop doesn’t pass the API’s events on to the browser as they are. It has its own, few and with its own names, in src/assistant/events.ts:
// What the shop sends down the stream: each event with its name (the event: line) and its data (the// data: line, in JSON).// text one more piece of the answer, as it arrives from the model: { text }. All of them// together, in order, are the whole answer.// end the answer has finished. Its data is the same answer as without streaming (modelAnswer,// in conversation.ts): the whole text, whether the model refused and the tokens it cost.// If it refused, refused is true and the text is the shop's fixed sentence: the frontend// replaces whatever it has shown so far with it.// error something failed halfway: a Problem Details, like the body of any of the shop's errors.// Then the stream closes, with no end.// Lesson 3 adds one more, tool (what the assistant is doing: "searching products…"): one more line// in this type and its translation below; route.ts writes them all the same way (asSSE).export type AssistantEvent = | { event: 'text'; data: { text: string } } | { event: 'end'; data: Answer } | { event: 'error'; data: Problem };And a function that translates each of the model’s events:
// A model event, as one of the shop's; undefined if there's nothing to tell the customer. Only the// pieces of text (text_delta) go through. The rest stays in the shop: message_start and// message_delta carry the tokens and why it stopped, which arrive together in end; what the model// thinks before answering (thinking) isn't for the customer; and the others only mark where each// block starts and ends.export function shopEvent(event: Anthropic.MessageStreamEvent): AssistantEvent | undefined { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') { return { event: 'text', data: { text: event.delta.text } }; } return undefined;}- Only the pieces of text go through, as
textevents. What the model thinks isn’t for Carmen, and the other events only mark where each block starts and ends. - The tokens and the reason it stopped arrive together at the end, in
end, with the same answer as the JSON:text,refusedandusage. Ifrefusedistrue, the frontend replaces what it has shown with the fixed sentence. - If something fails halfway, an
errorevent with a Problem DetailsThe standard shape of the body of an error response in an API, written down in RFC 9457: a JSON with type (what kind of problem it is), title (its summary), status (the status code), detail (what happened this time) and instance (which of the times). It’s sent with the content type application/problem+json.Go to definition, like the body of any of the shop’s errors (Phase 4).
Why translate? The frontend only knows the shop’s events. If tomorrow you change models, or providers, or their API changes the format of its events, you change this function, and the frontend doesn’t even notice. And the shop’s OpenAPI document can describe them, because they’re its own.
Before the first event, a normal error; after it, an error event
Section titled “Before the first event, a normal error; after it, an error event”The status code of an HTTP response goes in its first line, and it goes out only once. That’s why the shop waits for the model’s first event before opening its stream:
// The model's events are read one by one, with this reader. It's asked for now, before waiting// for anything: the events the SDK reads before there's a reader, that reader never sees.const events = stream[Symbol.asyncIterator]();
// Until the first event arrives (message_start), the shop hasn't sent anything to the customer. A// failure here (a 429, a 529, the model not answering) is a normal error response, with its// status code and its Retry-After, as without streaming.let event: IteratorResult<Anthropic.MessageStreamEvent>;try { event = await events.next();} catch (error) { return answerFailure(c, error);}- Claude API → Shopmessage_start
- Shop → Carmen200, text/event-stream
- Claude API → Shoptext_delta, text_delta…
- Shop → Carmentext, text…
- Claude API → Shopmessage_delta, message_stop
- Shop → Carmenend, with the tokens
- If the API fails before its first event (a
429, a529, a model that doesn’t answer), the shop hasn’t sent anything yet: it answers lesson 1’s503, in JSON and withRetry-After. - If it fails afterward, the
200has already gone out. The failure arrives as anerrorevent, with the same Problem Details that would have been the body of the503, and the stream closes, with noend.
The frontend has to handle both cases: an error code before starting, and an error event halfway, with part of the text already on screen.
The customer leaves: cancel the call to the model
Section titled “The customer leaves: cancel the call to the model”If Carmen closes the tab halfway, nobody is going to read the rest. The shop notices and cancels the call to the model:
// With it, the call to the model is cancelled if the customer leaves halfway. The call gets both// signals together (AbortSignal.any): the first one to fire cancels it.const cancel = new AbortController();const stream = askStreaming(client, messages, AbortSignal.any([cancel.signal, signal]));cancelis anAbortController: an object with a signal (cancel.signal) that fires when someone callscancel.abort().- The call to the model gets the signals together (
AbortSignal.any):cancel’s andsignal, which already joins the 50-second time limit and Carmen’s request (lesson 1). The first one to fire cancels it. - Once inside the stream,
sse.onAbort(() => cancel.abort())callsabort()when the connection with Carmen closes.
When it fires, the SDK cuts its connection with the API, and the log keeps one line: “the customer left: cancelling the call to the model.” Whether the API then stops charging for what it no longer writes, we haven’t checked: its documentation doesn’t say.
In the browser: fetch and a reader
Section titled “In the browser: fetch and a reader”In Phase 4, the browser read an order’s events with EventSource. That won’t do here: EventSource only makes GET requests, without a body, and the conversation goes in the body of a POST. The frontend uses fetch, as for any other request, and reads the response as it arrives:
fetchsends thePOSTwithAccept: text/event-stream, and resolves as soon as the headers arrive, without waiting for the body.res.bodyis the body as a StreamData that arrives or is sent little by little, in chunks, instead of all at once, so a program can read it as it arrives. In a Node.js server, the body of a request is a stream.Go to definition: a reader (getReader()) returns the chunks as they arrive, andTextDecoderStreamturns them from bytes into text.- A chunk isn’t an event. It can bring two events, or half of one: the frontend gathers the text and cuts it at each blank line, the end of an event.
- From each event, the
event:line says what it is, and thedata:line, in JSON, its data: withtext, it adds the piece; withend, it finishes; witherror, it shows the problem.
EventSource reconnects on its own if the connection drops. With fetch, reconnecting is up to you, and here it isn’t a good idea: asking again is asking again, and paying again. You’ll write it in “Try it.”
What a proxy does to a stream: nginx’s buffering
Section titled “What a proxy does to a stream: nginx’s buffering”On your server, nginx sits in front of the API (Phase 8). By default, it holds what the API sends until it has a whole block: that’s buffering, which is fine for normal responses. With a stream, Carmen would get the answer all at once, at the end, and streaming would be pointless. Step 48 turns it off for this route:
# The streaming assistant (Phase 11, lesson 2): the answer arrives piece by piece, as the model# writes it, and with buffering nginx would keep it until it had a whole block: the customer# would see the answer all at once, at the end, and streaming would be pointless. Hence# proxy_buffering off, as for an order's events. The same route also answers in JSON (without# Accept: text/event-stream), and a short, whole response is not changed by it.# proxy_read_timeout stays at its 60 seconds: they're what nginx waits between two reads. When# streaming, there are seconds at most between two pieces; in JSON, the API sends nothing until# it has the whole answer, and the shop cuts that before, at 50 seconds (ASSISTANT_TIMEOUT_MS,# in src/config.ts), to answer its own 503 and not nginx's 504.location = /v2/assistant { proxy_pass http://shop; proxy_buffering off;}location = /v2/assistant: only this address, exactly.proxy_buffering off: each piece goes out toward Carmen as soon as it arrives. For a JSON response, short and whole, it changes nothing.proxy_read_timeoutstays at 60 seconds: it’s what nginx waits between two reads, and between two pieces much less time goes by. The JSON response, which sends nothing until the end, is cut earlier by the shop, at 50.
Try it
Section titled “Try it”The goal: watch the answer arrive piece by piece, measure when the first byte arrives with and without streaming, leave halfway and check that the shop cancels, and read the stream from the browser the way your frontend would.
The shop’s outputs are from lesson 1’s fake model; Claude’s we don’t copy.
Get the step ready
Section titled “Get the step ready”Put your project on step 48, as in the introduction, start the shop and sign Carmen in:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/48-streaming.tar.gztar -xzf 48-streaming.tar.gzcp -R 48-streaming/. shop-api/cd shop-apidocker compose up -d --build --waitAPI=$(docker compose port api 3000)curl -s -o /dev/null -c carmen.txt --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' $API/v2/sessionexport $(grep '^ANTHROPIC_API_KEY=' .env)Step 48 brings no new packages: you don’t need npm install. The last line loads your key for the first test, as in lesson 1.
The API’s events, once
Section titled “The API’s events, once”1. The Claude API’s stream
curl -sN https://api.anthropic.com/v1/messages \-H "x-api-key: $ANTHROPIC_API_KEY" -H 'anthropic-version: 2026-10-21' \--json '{"model":"claude-haiku-5-5","max_tokens":2048,"output_config":{"effort":"low"},"stream":true, "messages":[{"role":"user","content":"What is a hoodie, in two sentences?"}]}'-N makes curl write each piece as soon as it arrives, without holding it back. It comes out like the one in “What the API sends,” with Claude’s text. Look at the order: message_start with input_tokens, the content_block_delta events with their text_delta, and at the end message_delta, with stop_reason and output_tokens. If there’s a thinking block before the text, it arrives empty: the model doesn’t show what it thinks.
If instead of events you get a JSON with "type": "error", the stream never started: read it as in lesson 1. This is the only time you’ll see these events: from here on, the shop translates them.
The shop’s events
Section titled “The shop’s events”2. The shop’s stream
curl -N -b carmen.txt -H 'Accept: text/event-stream' \--json '{"messages":[{"role":"user","text":"What should I get for the cold?"}]}' $API/v2/assistantWhat you will see:
event: textdata: {"text":"I'll tel"}
event: textdata: {"text":"l you sl"}
event: textdata: {"text":"owly, pi"}
event: textdata: {"text":"ece by p"}
event: textdata: {"text":"iece, th"}
…
event: enddata: {"text":"I'll tell you slowly, piece by piece, the way a long answer from the model arrives: first a few words, then some more, and so on until the end. Streamed, you see them arrive; without it, you wait until it is whole.","refused":false,"usage":{"input":120,"output":30}}One event: text line for each piece, and at the end event: end, with the whole answer and its tokens. Join the text events in order, and you have the text of end. Not a trace of the API’s events: no message_start, no thinking. This output, trimmed, is from lesson 1’s fake model, which writes slowly: with Claude, the text will be different.
--json sets Accept: application/json, and the -H replaces it with text/event-stream. Without it, the answer arrives whole in JSON, as in lesson 1.
With and without streaming: when the first byte arrives
Section titled “With and without streaming: when the first byte arrives”Now the same question twice, without showing the answer (-o /dev/null): curl only writes when the first byte arrived and when the last one did.
3. The times
QUESTION='{"messages":[{"role":"user","text":"How do I wash a cotton hoodie without it shrinking?"}]}'curl -s -o /dev/null -w 'JSON: first byte %{time_starttransfer} s, total %{time_total} s\n' \-b carmen.txt --json "$QUESTION" $API/v2/assistantcurl -s -o /dev/null -w 'streaming: first byte %{time_starttransfer} s, total %{time_total} s\n' \-b carmen.txt -H 'Accept: text/event-stream' --json "$QUESTION" $API/v2/assistantWhat you will see:
JSON: first byte 9.035688 s, total 9.035827 sstreaming: first byte 0.015627 s, total 9.143494 sThese are from the fake model with SCENARIO=slow, which writes for about 9 seconds. In JSON, the first byte arrives at the same time as the last: the shop waits for the end. With streaming, right away, and the total is similar. With Claude, measure yours.
With streaming, the first byte is the headers, which the shop sends as soon as the model starts; the first piece of text arrives later: with the fake model, after 1.75 seconds; with Claude, when it finishes thinking.
Leave halfway
Section titled “Leave halfway”--max-time 2 makes curl give up after 2 seconds and close the connection, like Carmen closing the tab:
4. Leaving halfway, and what the log says
curl -N --max-time 2 -b carmen.txt -H 'Accept: text/event-stream' \--json '{"messages":[{"role":"user","text":"Tell me in detail what the difference is between a T-shirt and a hoodie."}]}' $API/v2/assistantdocker compose logs api --since 1m --no-log-prefix | grep 'customer left'What you will see:
event: textdata: {"text":"I'll tel"}
curl: (28) Operation timed out after 2005 milliseconds with 39 bytes received{"level":30,"time":1795280284292,"pid":1,"hostname":"9830c899545b","requestId":"7a86b09f-302d-402c-aab1-2e1c35d4af73","msg":"the customer left: cancelling the call to the model"}First one or more event: text lines come out (here, one: this is lesson 1’s fake model, which writes slowly), and then curl: (28), which has given up. Look at the log line: the shop has seen Carmen leave and has cancelled the call to the model. There’s no end: nobody was going to read it.
If you get the end before the 2 seconds, the answer was short: go down to --max-time 1. If the log says nothing, wait a second and repeat the second line.
From the browser
Section titled “From the browser”Open http://localhost:3000/ in Chrome (or your $API’s port) and, in DevTools (how to open it), the Console tab. It has to be a page from the shop, so the requests go to its same origin. If Chrome asks you to type allow pasting, do it, as in Phase 4.
5. The stream, with fetch and a reader
await fetch('/v2/session', { method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ email: 'carmen@example.com', password: 'carmen-practice-2026' }) })const res = await fetch('/v2/assistant', {method: 'POST',headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },body: JSON.stringify({ messages: [{ role: 'user', text: 'What should I get for the cold?' }] }),})const reader = res.body.pipeThrough(new TextDecoderStream()).getReader()for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) console.log(chunk.value)What you will see:
event: textdata: {"text":"I'm the "}
event: textdata: {"text":"fake mod"}
event: textdata: {"text":"el: I un"}
…
event: enddata: {"text":"I'm the fake model: I understand nothing, I just repeat your last question. It was: \"What should I get for the cold?\".","refused":false,"usage":{"input":120,"output":30}}Line by line:
- The first
fetchsigns Carmen in: the browser stores the cookie and sends it with the next one, as the shop’s website does. - The second asks for the answer as a stream.
awaitwaits only for the headers: the body keeps arriving. res.body.pipeThrough(new TextDecoderStream())turns the body’s bytes into text, andgetReader()gives a reader.- The
forasks for a chunk withreader.read()until one arrives withdone: true, the end, and writes each one.
Look at where each console.log cuts. The fake model sends everything at once: it all came out in a single one (without the events in the middle); with SCENARIO=slow, one per event. A chunk can bring two events, or half of one: that’s why a real frontend gathers the text and cuts it at the blank lines before reading each event.
Challenge: repeat the second fetch with an AbortController (const stop = new AbortController(), and signal: stop.signal in the options), and write setTimeout(() => stop.abort(), 1500) before the for. What happens in the console, and what does the shop’s log say?Show answer
After 1.5 seconds, stop.abort() cancels the request: the for stops with an AbortError in red, and the browser closes the connection. The shop sees it as in test 4: docker compose logs api --since 1m --no-log-prefix | grep 'customer left' shows the same line. It’s what your frontend would do with a “Stop” button: cancel in the browser, so the server cuts the call to the model.
When you finish, delete carmen.txt: it holds Carmen’s session.
On your server
Section titled “On your server”Step 48’s code arrives with the usual push. nginx doesn’t: it lives on the server, outside the image. Add the location from above to your site, /etc/nginx/sites-available/shop, next to the others, and reload as in Phase 8:
sudo nginx -t && sudo systemctl reload nginxBetter to add it by hand than to copy the step’s whole file: if you use Let’s Encrypt, your file has the certificate lines that certbot added, and copying over it would delete them. Do it before the push: an extra location changes nothing for the JSON response.
You have already seen it
Section titled “You have already seen it”- The AI chats that write word by word, like the Claude app: a stream like this one, read with
fetchand drawn as it arrives. - Those chats’ “Stop” button: it cancels the request in the browser, and the server stops asking the model for text.
- A request in DevTools that stays “pending” while the text appears: it’s the streamed answer, still open.
Common mistakes
Section titled “Common mistakes”- Passing the provider’s events on to the browser. Your frontend gets tied to their format: if it changes, or you change models, it breaks.
- Using
EventSourcefor a question. It only doesGET: the conversation goes in the body of aPOST. - Reading each chunk as if it were a whole event. A chunk can bring two events, or half of one.
- Not cancelling when the customer leaves. The model keeps writing, and you keep paying, for an answer nobody reads.
- Forgetting nginx’s
proxy_buffering off. The stream works on your computer and arrives all at once in production. - Reconnecting on your own after a drop. Asking again is paying again: let the person asking decide.
Summary
Section titled “Summary”- With streaming, the total time is the same, but the first word arrives much sooner: what the person waiting notices is the time to first token.
- The API sends SSE events in order (
message_start, thecontent_block_deltaevents,message_delta,message_stop), and the SDK reads them withmessages.stream()andfinalMessage(). - The shop translates them into its own,
text,endanderror: the frontend doesn’t depend on the provider’s format. - Before the first event, a failure is a normal
503; after it, anerrorevent. If the customer leaves, anAbortControllercancels the call to the model. - In the browser,
fetchwith a reader, cutting at blank lines; in production,proxy_buffering offin nginx.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Streaming messages, in Claude’s documentation: every event of the stream, with examples.
- Using readable streams, on MDN:
fetch’s reader, step by step. proxy_buffering, in nginx’s documentation.- Server-sent events, the specification of the format.