Skip to content
mentoor

Topic 1 of 4 · 5 min read

How server-sent event streams work

Goal: Read a raw event stream log and reconstruct the final message, stop reason and token usage from its events.

A streamed model response is a long-lived HTTP response whose body is a series of small, named events, and the finished message exists only when you have read all of them. Server-sent events (SSE) is the format most providers use: the server sends Content-Type: text/event-stream and keeps the connection open.

Check yourself · 1 of 3

In a server-sent event stream, what ends one event?

Choose one answer

Why it matters

If you only know the final JSON shape, a stream looks like noise. When a reply is cut off, the usage numbers look wrong or the stop reason is missing, the answer is in the event log. Being able to read that log is the fastest way to debug streaming code.

The wire format

Each event is a few text lines followed by a blank line. A line starting with event: names the event, a line starting with data: carries a JSON payload, and the empty line ends the event. A line starting with a colon is a comment, often used as a keep-alive. Browsers have EventSource for GET requests, but most model APIs need a POST with headers, so you read the body with fetch and parse the lines yourself or use the vendor SDK.

The event sequence

Anthropic's Claude API sends the same order every time:

  1. message_start: a message object with the id, model and empty content.
  2. For each content block: content_block_start, then many content_block_delta events, then content_block_stop. A text block carries text_delta pieces. A tool call block carries input_json_delta pieces.
  3. message_delta: top-level changes, including the stop_reason and the usage counts. The usage here is cumulative, so use the last value, do not add them up.
  4. message_stop: the end.

ping events can appear anywhere and should be ignored. OpenAI's Responses API uses different names, such as response.output_text.delta and response.completed, but the idea is the same: start, deltas, then a final event with status and usage.

Before and after

Weak: a client that appends every data: payload to a string and treats the string as the answer. It ends up with JSON noise, ping events and metadata in the reply.

Better: a client that switches on the event type.

for await (const ev of events) {
  if (ev.type === "content_block_delta" && ev.delta.type === "text_delta") {
    text += ev.delta.text;
  } else if (ev.type === "message_delta") {
    stopReason = ev.delta.stop_reason;
    outputTokens = ev.usage.output_tokens;
  }
}

What goes wrong

  • Ignoring unknown events. Providers add event types. Skip what you do not know, do not throw.
  • Missing the stop reason. max_tokens means the answer was cut off. Showing it as complete hides a truncated reply.
  • Summing usage. Adding every usage value double counts.
  • Treating a closed connection as success. Without message_stop the message is incomplete.

Examples

Reading a short event log

event: message_start
data: {"type":"message_start","message":{"id":"msg_01","content":[]}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo"}}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"},"usage":{"output_tokens":2}}

The text is "Hello". The stop reason is max_tokens, so the answer was cut off. There is no message_stop, so the log itself may also be incomplete.

Key points

  • A stream is one long HTTP response with Content-Type text/event-stream, made of events separated by blank lines.
  • A Claude stream runs message_start, then content blocks with start, delta and stop events, then message_delta and message_stop.
  • The stop reason and cumulative usage arrive in message_delta, near the end of the stream.
  • Unknown or ping events should be skipped, not treated as errors.
  • Without the final stop event the message is incomplete, even if the connection closed cleanly.

Common mistakes

  • Concatenating every data payload instead of switching on the event type.
  • Adding up the usage values from several events when the numbers are cumulative.
  • Throwing an error on an event type the code does not know yet.
  • Treating a closed connection as a finished answer without checking for the final event.

Check yourself · 2 of 3

In a Claude message stream, which event carries the stop reason and the final token usage?

Choose one answer

Check yourself · 3 of 3

A client logs these events for one answer: message_start, several content_block_delta with text_delta, content_block_stop, message_delta with stop_reason max_tokens, message_stop. What does the user see and what should the app show?

Choose one answer

Practice items, not counted towards your mastery.

Start here