System Design Simple logoSystem Design Simple Follow on YouTube

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.

Why AI replies in pieces: streaming, and how the app knows the reply is finished: diagrams from the video

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.

OpenAI API docs page Streaming API responses: by default the API generates the model's entire output before sending it back in a single HTTP response, and streaming lets you start printing the beginning while the full response is generated
OpenAI API docs, Streaming API responses, opening paragraph. Captured in Chrome on 2026-11-22. Source: developers.openai.com.

Turning streaming on is one setting in the request:

APISettingTransport
Claude Messages API"stream": trueServer-sent events
OpenAI Responses APIstream=TrueServer-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:

  1. message_start, with a Message object whose content is empty.
  2. A series of content blocks. Each has a content_block_start, any number of content_block_delta events, and a content_block_stop.
  3. One or more message_delta events, with top-level changes to the final Message.
  4. "A final message_stop event."
Claude Platform Docs Streaming messages page, Event types section: each stream uses message_start, a series of content blocks with content_block_start, content_block_delta and content_block_stop, one or more message_delta events, and a final message_stop event
Claude Platform Docs, Streaming messages, Event types. Captured in Chrome on 2026-11-22. Source: platform.claude.com.

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"}
Claude Platform Docs basic streaming response sample: message_start, content_block_start, ping, two content_block_delta events, content_block_stop, message_delta with stop_reason end_turn, and message_stop
Claude Platform Docs, Streaming messages, Basic streaming request response sample. Captured in Chrome on 2026-11-22. Source: platform.claude.com.
EventWhat the app learns
content_block_stopOne block is complete; for tool input, the JSON can now be parsed
message_deltaTop-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_stopThe final event of the stream
pingNothing about the reply; pings can appear any number of times
errorSomething 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:

  1. 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.
  2. Skip lines that start with a colon. They are comments, and a server may send them alone to keep the connection open.
  3. For other lines, split at the first colon and drop one space after it. event sets the event type; each data line adds its value and a newline to a data buffer.
  4. 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.
  5. Only then, for Claude events, parse the data as JSON and apply it by type and index: a text_delta appends to the text of content block index, an input_json_delta appends 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 breaksWhat you seeDetect and fix
Proxy or middleware bufferingText arrives in lumps or all at onceCompare 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 JSONRandom JSON parse errors, lost textParse by line, skip comments and frames without data, as above
Connection closes before message_stopA reply that stops mid-sentence and looks finishedMark it incomplete; offer a retry or continuation
error event mid-streamPartial text followed by nothingShow the error next to the partial text; never mark it done
stop_reason is max_tokensText cut at the token limitTell 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

OptionGood forCosts youUse when
Stream and displayChat screens, long answersParser, partial states, cancel and error handling; the OpenAI guide notes partial output is harder to moderateA person is watching the reply
Stream inside the SDK, return the whole messageLarge max_tokens, where the Claude page says the SDK requires streaming to avoid HTTP timeoutsNo early text on screenBackground jobs that need the full result
Single responseShort outputs, simple codeThe user waits for the whole replyBatch 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.

CheckWhy
Text pieces are appended exactly as sentPieces like "ello frien" are not whole words, so added spaces corrupt the reply
On message_stop, inspect stop_reason before deciding what comes nextend_turn is a finished turn; tool_use means the model wants a tool
Errors and user cancellation are handled separately from completionAn 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 incompletemessage_stop is the final event the page defines
Unknown event types are ignored safely and logged for reviewThe 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

  1. Claude Platform Docs: Streaming messages (read 2026-11-22)platform.claude.com
  2. OpenAI API docs: Streaming API responses (read 2026-11-22)developers.openai.com
  3. HTML Living Standard: Server-sent events, interpreting an event streamhtml.spec.whatwg.org
  4. nginx docs: ngx_http_proxy_module, proxy_bufferingnginx.org

storyai systemsstreamingllmserver-sent eventssse

System Design Simple logo
System Design Simple

Written by a software engineer and system architect with 10+ years of building production web, payment, ticketing and accounting systems in Japan and Nepal. About us