AI SystemsSystem Design, simply · Part 103
Why AI replies in pieces: streaming, and how the app knows the reply is finished
Why AI replies in pieces: an app streams and displays text as it is generated. Completion events tell the app when the response ends.

Drafted with AI assistance, then checked and edited by a human engineer · How we write
AI replies appear in pieces when an app displays generated text as it arrives. The Claude and OpenAI APIs can deliver that text as server-sent events, and the stream ends with an event the app reads to learn why the reply stopped.
Prerequisites
An HTTP response can be sent in parts over one open connection; the client does not have to wait for the last byte to read the first. You also need to read JSON, since each Claude API stream event carries its data as a JSON object.
Why AI replies in pieces
Making the text and delivering it are separate jobs, and delivery is the app's choice. Streaming means sending the reply as a series of small events while it is still being produced, so the app can show the beginning before the end exists. The OpenAI streaming guide describes the default: unless you ask for streaming, the API generates the entire output first, then sends it back in a single HTTP response. With long outputs that wait adds up, and streaming lets you start printing or processing the beginning while the rest is still being generated.

Turning streaming on is one setting in the request:
| API | Setting | Transport |
|---|---|---|
| Claude Messages API | "stream": true | Server-sent events |
| OpenAI Responses API | stream=True | Server-sent events |
Server-sent events (SSE) is a text format for a long-lived HTTP response: each event is a few field: value lines, and a blank line ends it. Other apps may use WebSockets or their own transport, or may buffer the whole reply and animate it afterwards; the pieces you see on screen do not prove which one an app uses. Our article on why AI starts answering before it is done covers what streaming changes about waiting time.
Is each piece a word?
Not necessarily. In the Claude Messages API, each piece is a delta, an incremental update to the content block at a given index. On the Claude streaming page, the sample text piece is a content_block_delta whose text_delta carries "ello frien", which is not made of whole words. Append every piece exactly as it came, with no added spaces.
Tool input is split too. In the page's tool use sample the input arrives as partial JSON strings, and the page says to accumulate them and parse the JSON once content_block_stop arrives.
How does the app know the reply is finished?
The completion event is provider specific. The Claude streaming page lists the event flow every Messages API stream uses:
message_start, with a Message object whose content is empty.- A series of content blocks. Each has a
content_block_start, any number ofcontent_block_deltaevents, and acontent_block_stop. - One or more
message_deltaevents, with top-level changes to the final Message. - "A final message_stop event."

The end of the page's basic sample (the full sample starts with message_start):
event: content_block_stop
data: {"type": "content_block_stop", "index": 0}
event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}
event: message_stop
data: {"type": "message_stop"}

| Event | What the app learns |
|---|---|
content_block_stop | One block is complete; for tool input, the JSON can now be parsed |
message_delta | Top-level changes such as stop_reason (end_turn in the basic sample, tool_use in the tool sample); its usage token counts are cumulative |
message_stop | The final event of the stream |
ping | Nothing about the reply; pings can appear any number of times |
error | Something failed mid-stream, for example an overloaded_error, which the page says would normally be an HTTP 529 without streaming (rate limit and overload errors are covered in why AI says too many requests after one message) |
The page also warns that new event types may be added. The OpenAI Responses API names its events differently: its guide lists response.created, response.output_text.delta, response.completed and error as the common ones.
How a client reads the stream
The network hands the client bytes, and a read does not line up with events. One read can end halfway through a data: line, and the next can hold three whole events. The SSE parsing rules work line by line on plain text; JSON is what the Claude API puts inside the data field, and the format itself does not require it.
A client that follows the standard does this:
- Decode bytes as streaming UTF-8, so a character split across two reads survives. Keep any unfinished line for the next read, including a trailing CR whose LF may arrive later. Lines end in CRLF, LF or CR.
- Skip lines that start with a colon. They are comments, and a server may send them alone to keep the connection open.
- For other lines, split at the first colon and drop one space after it.
eventsets the event type; eachdataline adds its value and a newline to a data buffer. - On a blank line, dispatch. If the data buffer is empty, dispatch nothing and reset. Otherwise drop the final newline, and the rest is the event's data.
- Only then, for Claude events, parse the data as JSON and apply it by
typeandindex: atext_deltaappends to the text of content blockindex, aninput_json_deltaappends to that block's raw JSON string.
The official SDKs and tested SSE parsers already handle these cases, so write your own only when you have a reason to.
Something between the API and the screen can also hold the bytes back. A reverse proxy that buffers responses (nginx has proxy_buffering on by default) can delay or batch delivery, so the text appears in large lumps or all at the end. To find where the delay sits, log the time of the first content_block_delta on your server and again in the client, with both clocks synchronized, and check the buffering settings of each proxy on the route. That gap also includes network, scheduling and rendering time, so read it together with the proxy settings.
Failure modes
| What breaks | What you see | Detect and fix |
|---|---|---|
| Proxy or middleware buffering | Text arrives in lumps or all at once | Compare first-event time at server and client with synchronized clocks and check proxy settings; turn off buffering for that route (nginx also honours an X-Accel-Buffering: no response header) |
| Parsing each read as one event, or every frame as JSON | Random JSON parse errors, lost text | Parse by line, skip comments and frames without data, as above |
Connection closes before message_stop | A reply that stops mid-sentence and looks finished | Mark it incomplete; offer a retry or continuation |
error event mid-stream | Partial text followed by nothing | Show the error next to the partial text; never mark it done |
stop_reason is max_tokens | Text cut at the token limit | Tell the user the reply was truncated |
For a stream that was cut off, the Claude page's recovery advice is to keep what arrived and send a continuation request. For Claude 4.5 and earlier models, the partial response goes in as the start of a new assistant message; for Claude 4.6 and later, the request is a user message holding the partial response and an instruction to continue. Tool use and thinking blocks cannot be partially recovered, so you resume from the most recent text block.
Trade-offs
| Option | Good for | Costs you | Use when |
|---|---|---|---|
| Stream and display | Chat screens, long answers | Parser, partial states, cancel and error handling; the OpenAI guide notes partial output is harder to moderate | A person is watching the reply |
| Stream inside the SDK, return the whole message | Large max_tokens, where the Claude page says the SDK requires streaming to avoid HTTP timeouts | No early text on screen | Background jobs that need the full result |
| Single response | Short outputs, simple code | The user waits for the whole reply | Batch work or short answers |
Adding streaming to your own chat screen
A prompt you can hand to your coding agent:
Stream the AI reply to my chat screen with server-sent events, append each text chunk as it arrives, and add a stop button.
Then check what it built. This checklist is for the Claude Messages API; other APIs use other event names.
| Check | Why |
|---|---|
| Text pieces are appended exactly as sent | Pieces like "ello frien" are not whole words, so added spaces corrupt the reply |
On message_stop, inspect stop_reason before deciding what comes next | end_turn is a finished turn; tool_use means the model wants a tool |
| Errors and user cancellation are handled separately from completion | An error event or a press on your stop button ends the stream without a finished reply (voice apps have their own version, see why the AI kept talking when you interrupted) |
An unexpected connection close before message_stop is treated as incomplete | message_stop is the final event the page defines |
| Unknown event types are ignored safely and logged for review | The page says new event types may be added, and one may matter to correctness |
Our take
When someone is waiting for the answer, seeing the first words early is often worth the parser, the extra handling and the harder moderation. Any request can be pending, failed or cancelled; streaming adds partial output, text already on screen that may never become a finished reply. The bug we would test for first is a partial reply shown as finished. If nobody watches the text appear, let the SDK collect the whole message and skip that work.
FAQ
Why do AI replies arrive in pieces?
The app receives the generated text incrementally and shows each piece as it arrives. The Claude and OpenAI APIs deliver those pieces as server-sent events.
Is each streamed piece one word?
No. The Claude streaming docs show a sample piece, "ello frien", that is not made of whole words. Append each piece as a string.
How does a chat app know the AI reply is finished?
It depends on the API. In the Claude Messages API, a final message_stop event ends the stream. The stop_reason in the message_delta before it says whether the turn finished (end_turn), needs a tool (tool_use) or was cut at the token limit (max_tokens). The OpenAI guide lists response.completed among its common streaming events.
This article describes public API documentation and general streaming patterns, not the private systems of any company or app.
Frequently asked questions
Why do AI replies arrive in pieces?
The app receives the generated text incrementally and displays each piece as it arrives, so the bubble fills in a little at a time. Some APIs, including the Claude and OpenAI APIs, deliver those pieces as server-sent events.
Is each streamed piece one word?
No. The Claude streaming docs show a sample text piece "ello frien", which is not made of whole words. Treat each piece as a string to append, not as a word.
How does a chat app know the AI reply is finished?
It depends on the API. In the Claude Messages API, a final message_stop event ends the stream, and the stop_reason in the message_delta before it says whether the turn finished (end_turn), needs a tool (tool_use) or was cut at the token limit (max_tokens). The OpenAI guide lists response.completed among its common events.
Sources
- Claude Platform Docs: Streaming messages (read 2026-11-22)platform.claude.com
- OpenAI API docs: Streaming API responses (read 2026-11-22)developers.openai.com
- HTML Living Standard: Server-sent events, interpreting an event streamhtml.spec.whatwg.org
- nginx docs: ngx_http_proxy_module, proxy_bufferingnginx.org