Module: L1-M03 · Duration: ~150 min (estimate, including the independent exercise) · Previous: L03 · Next: L05 - Mocking, recording and replaying provider responses
1. Introduction
A long answer can take many seconds to generate. If the application waits for all of it before showing anything, the user stares at an empty screen. Streaming sends the answer piece by piece as soon as the model produces it, so the user sees the text appear gradually.
For a tester, streaming raises two new questions: how to measure latency correctly, and how a mid-stream error is handled, when the HTTP status is already 200 but the stream can still report an error.
2. Learning objectives
- Explain how streaming works through server-sent events, and the order of the main events.
- Measure the time to first token (TTFT) and the total time of a streamed reply.
- Verify that the text assembled from the chunks, the stop reason and the usage of the stream are correct.
- Verify how the code handles an error event that appears in the middle of a stream.
- Design a measurable latency budget, and explain why a single measurement is not enough.
3. Prerequisites and tools
- L03: typed exceptions.
- L1-M01-L03: non-determinism. Latency, too, needs many measurements.
4. Concepts
4.1 Server-sent events (SSE)
When a request has "stream": true, the response is a stream of server-sent events: the server sends many
text events over the same HTTP connection [R1]. According to the streaming documentation, every stream has this order [R1]:
message_start: aMessageobject with emptycontent.- For each content block:
content_block_start, one or morecontent_block_delta, thencontent_block_stop. - One or more
message_delta: changes at the message level, for examplestop_reason. The token counts in theusageofmessage_deltaare cumulative. message_stop.
There are also ping events, and error events. For example, under high load a stream can receive overloaded_error,
which corresponds to HTTP 529 in non-streaming mode [R1].
Everyday example. A live text commentary of a football match: each line appears as soon as it happens, instead of waiting for the match report at full time. The first line is always "kick-off", the last one is "full time", and the final score only appears near the end.
Worked example (real run). List the events the fake sends for a two-chunk reply. Run it from the lab folder:
python - <<'EOF'
from lab.fake_api import stream_events
for name, data, wait in stream_events(["She ", "goes."]):
print(f"{name:<20} {data.get('delta', '')}".rstrip())
EOF
Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):
message_start
content_block_start
ping
content_block_delta {'type': 'text_delta', 'text': 'She '}
content_block_delta {'type': 'text_delta', 'text': 'goes.'}
content_block_stop
message_delta {'stop_reason': 'end_turn', 'stop_sequence': None}
message_stop
The order matches the list above: the text is in the content_block_delta events, while stop_reason
only appears in message_delta, near the end of the stream. Code that stops reading after the last text
chunk cannot know whether the reply was cut off.
4.2 TTFT and total time
Anthropic's glossary defines time to first token (TTFT) as the time it takes the model to generate the first token of the output after receiving the prompt, and as an important metric for interactive applications [R2].
| Metric | Measured from where to where | What the user feels |
|---|---|---|
| TTFT | Sending the request → the first text chunk | "Is the bot responding?" |
| Total time | Sending the request → the end of the stream | "How long until the full answer is there?" |
Everyday example. In a coffee shop, TTFT is the moment the waiter brings a glass of water and says "coming right up"; total time is when the coffee is on the table. Customers put up with a much longer wait for the coffee if someone responds right away.
Good vs bad. The same measurement:
| Weak report | Good report |
|---|---|
| "Response time: 2.1 seconds" | "TTFT 0.4 seconds, total time 2.1 seconds (one measurement, fake with a deliberate delay; not a real-model number)" |
The weak report does not say which metric it is, so nobody knows whether users stare at an empty screen for 0.4 seconds or for 2.1 seconds.
4.3 Errors after HTTP 200
The Errors documentation says that with streaming, errors can occur after the API has returned 200, and then
error handling does not follow the usual mechanism [R3]. The lab observed with anthropic 2.3.0: an error
event of type overloaded_error in the middle of a stream makes the SDK raise anthropic.APIStatusError with type == "overloaded_error". The user may already have seen part of the answer. The product has to decide
what to do with that part.
Everyday example. A courier delivers half of an order and only then says the rest is out of stock. You are holding half of it; the shop has to say clearly what is missing, instead of staying silent as if the order were complete.
Good vs bad.
| Weak test | Good test |
|---|---|
| Asserts that the HTTP status is 200 and treats that as success | The fake sends a few chunks and then an error event; the test asserts an APIStatusError with type == "overloaded_error" (section 8.2), and that the product does not show the part it received as a full answer |
4.4 Measuring latency correctly
- One measurement is not enough. Latency varies with the network, the provider's load, the prompt length and the output length. Measure many times and report the distribution, for example the median and a high percentile such as p95. (Level 2 covers how to summarise data that varies.)
- Measured from where? A measurement in a test includes the network from the test machine. Real users also have their own network and the backend's processing time.
- A fake API cannot measure the latency of the real model. With a fake, you only verify that the code measures correctly, by deliberately creating a known delay.
Everyday example. Asked "how long is your commute?", saying "25 minutes on average" hides the rainy morning stuck in traffic for 70 minutes. "Nine days out of ten it is under 30 minutes" is the number that helps you decide when to leave home.
Worked example. Ten TTFT measurements (seconds, invented numbers): 0.62; 0.70; 0.58; 0.66; 1.90; 0.64; 0.71; 0.60; 0.68; 0.65.
- Sort: 0.58; 0.60; 0.62; 0.64; 0.65; 0.66; 0.68; 0.70; 0.71; 1.90.
- Mean: total 7.74 / 10 = 0.774 seconds. One slow run pulls the mean up.
- Median: the mean of the 5th and 6th values = (0.65 + 0.66) / 2 = 0.655 seconds.
- p95 by the nearest-rank method: rank = 95 / 100 × 10 = 9.5 rounded up, so rank 10, the largest value: 1.90 seconds.
Against the budget "p95 below 1 second", this run fails, even though the mean is only 0.774 seconds. Note too that with 10 measurements, the p95 is simply the slowest one: you need more measurements for a stable p95. The extra exercise in section 9.1 uses exactly this example.
5. Technical deep dive
5.1 stream_with_timing
with client.messages.stream(model=model, max_tokens=max_tokens,
messages=[{"role": "user", "content": learner_text}]) as stream:
for text in stream.text_stream:
if first is None:
first = clock()
chunks.append(text)
final = stream.get_final_message()
client.messages.stream(...)opens a stream. Thewithblock guarantees the connection is closed.stream.text_streamreturns the pieces of text one by one. The first piece marks the TTFT.stream.get_final_message()returns the completeMessage, withstop_reasonandusage.clockdefaults totime.perf_counter, a precise clock for measuring time intervals. Passingclockin from outside (dependency injection, L1-M01-L02) makes the measuring logic testable without depending on real time.
Worked example (real run). Pass in a fake clock that returns 10.0 (start), 10.4 (first chunk) and 10.9 (end), in that order. Run it from the lab folder:
python - <<'EOF'
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"
from lab.fake_api import FakeClaudeAPI, Reply, stream_events
from lab.streaming import stream_with_timing
from lab.tutor_client import make_client
ticks = iter([10.0, 10.4, 10.9]) # start, first chunk, end (seconds)
with FakeClaudeAPI() as api:
api.queue(Reply(sse=stream_events(["She ", "goes."], stop_reason="max_tokens")))
r = stream_with_timing(make_client(base_url=api.base_url), "x", clock=lambda: next(ticks))
print(f"text={r['text']!r} stop_reason={r['stop_reason']} ttft_s={r['ttft_s']:.1f} total_s={r['total_s']:.1f}")
EOF
Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):
text='She goes.' stop_reason=max_tokens ttft_s=0.4 total_s=0.9
TTFT = 10.4 - 10.0 = 0.4 and total = 10.9 - 10.0 = 0.9, exact to the digit, on every machine: there is no
sleep at all, so a test built this way is never flaky. The clock is called exactly three times, as in
the code above.
Everyday example. Like a race official with a stopwatch: to check that the official presses the button at the right moments, you use a stopwatch whose readings you know in advance, not a real runner.
5.2 Creating a fake stream with a known delay
api.queue(Reply(sse=stream_events(["a", "b", "c"], first_delay=0.3, gap=0.1)))
The fake sends the events in exactly the order of section 4.1, waits 0.3 seconds before the first chunk and 0.1 seconds between chunks. So the TTFT must be ≥ 0.3 seconds, and the total time must be ≥ 0.5 seconds.
Good vs bad.
| Weak test | Good test |
|---|---|
assert result["ttft_s"] == 0.3: fails at random, because real time is always a little longer |
assert 0.3 <= result["ttft_s"] < result["total_s"] and result["total_s"] >= 0.5 (the test test_time_to_first_token_is_measured) |
With real delays you can only assert a range: the lower bound proves the code measures correctly, the upper bound (if any) is the budget. For exact numbers, use a fake clock as in section 5.1.
6. The QA perspective
- What to test: the text is assembled correctly;
stop_reasonandusagefrom the stream; the TTFT is measured correctly; errors in the middle of a stream; a reply truncated while streaming. - Why: streaming is a UX feature. Defects here show up as repeated text, missing text, or an unfinished answer with no notice.
- What can go wrong: chunks assembled in the wrong order or lost; the
stop_reasonat the end of the stream ignored; a mid-stream error that makes the UI hang; TTFT measured from the wrong moment. - Expected behaviour (an example to agree on): TTFT p95 under X seconds in environment Y. X and Y are decided by the product team based on measurements, not an industry-wide figure.
- How to detect it: a fake stream with a known delay (verifies the code); a live test repeated many times (measures the real system).
- How to report it: the number of measurements, median, p95, the measurement environment, the model, the prompt length, the output length.
7. Real-world scenarios
Scenario 1 - A speaking tutor (fictional). A speaking-practice app turns the answer into speech as soon as
the first chunk arrives. When an overloaded_error occurs in the middle of the stream, the app reads half a sentence and then goes silent.
Test: a fake stream with an error event in the middle, and a check that the app reports the error clearly.
Scenario 2 - An internal copilot (fictional). The team reports "average TTFT 0.8 seconds" from 5 measurements on a laptop in the office. Users at another branch find it much slower. Lesson: record where you measured, how many measurements, and use percentiles instead of the average.
8. Hands-on tutorial
8.1 Running the demo
python -m lab.demo l04
Actual output (2026-10-31):
text='She goes to school.' chunks=3 stop_reason=end_turn output_tokens=3
ttft >= 0.3 s: True total > ttft: True
The demo prints conditions (True/False) instead of seconds, because the seconds change between runs
and between machines.
8.2 Running the tests
python -m pytest tests/test_l04_streaming.py -v
Expected result: 4 passed. The mid-stream error test:
def test_error_in_the_middle_of_a_stream_raises(client, api):
events = stream_events(["partial "])[:4] + [
("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}, 0.0)]
api.queue(Reply(sse=events))
with pytest.raises(anthropic.APIStatusError) as caught:
stream_with_timing(client, "x")
assert caught.value.type == "overloaded_error"
[:4] takes the first four events (message_start, content_block_start, ping and one content_block_delta),
then adds the error event.
8.3 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| The TTFT test fails now and then | An overloaded machine pushes the latency past the upper bound | Loosen the upper bound; never tighten the lower bound |
ttft_s is None |
The stream has no text chunk at all | Check the fake's events; this is also a case worth testing |
9. Independent exercise
Problem: The product owner sets a latency budget: TTFT under 1 second (with a fake that has a 0.5-second delay).
Tasks:
- Copy
exercises/test_l04_latency.pyintotests/. - Assert that the TTFT lies in
[0.5, 1.0)seconds. Explain why both a lower bound and an upper bound are needed. - Assert that the stop reason of the stream is
max_tokens. - Write 3-5 sentences: a plan for measuring the real TTFT for LinguaBot (how many times, where, which metrics to report, how much it costs).
Test data: stream_events(["a", "b"], first_delay=0.5, stop_reason="max_tokens").
Deliverable: the test file and the measurement plan.
Acceptance criteria: the test passes reliably on your machine; the plan has the number of measurements, the environment, a percentile metric, and a cost estimate using the formula from L01.
Hint: the lower bound verifies that the code does measure correctly; the upper bound is the budget.
9.1 Extra exercise: report a budget with a percentile
Problem (about 20 minutes): exercises/data/ttft_samples.json holds 20 TTFT measurements (invented
numbers) from two sites: office and branch, as in Scenario 2 of section 7. Budget: "TTFT p95 below 1.0 seconds".
Tasks:
- Copy
exercises/test_l04_extra_percentile.pyintotests/. - Write
nearest_rank(samples, p)with the method of section 4.4 (sort a copy, take the value at the rank p / 100 × n rounded up, counting ranks from 1). - Write
verdict(samples, budget_s):"pass"if the p95 is strictly below the budget, else"fail". - Run
python -m pytest tests/test_l04_extra_percentile.py, then write one sentence: which site meets the budget, and what is the mean of the site that does not.
Acceptance criteria: untouched, 8 failed with a TODO message; when done, 8 passed.
Hint: check your function on the 10-measurement example of section 4.4 first. Three shortcuts fail: using the mean instead of the p95, forgetting to sort, and a rank that is off by one.
9.2 Real-world scenario: the speaking tutor goes silent mid-sentence
Context (fictional): LinguaBot's "speaking tutor" reads the answer aloud as soon as the first chunk arrives (Scenario 1, section 7). Users report that the tutor sometimes reads half a sentence and then goes silent, while the screen still shows the "speaking" icon. The team has no streaming tests beyond the happy path.
Your task: write a list of test cases (at least 6) for this feature's streaming flow, each with: the condition the fake creates, the expected behaviour, and how to assert it. End with one question the product owner has to decide.
A good answer has:
- an error mid-stream after some chunks (an
errorevent), and an error before the first chunk; - a stream that ends with
max_tokens(a cut-off sentence), and a stream with no text chunk (ttft_sisNone); - one latency case: a first chunk slower than the budget, or a long silence between two chunks;
- concrete expected behaviour for the user (what is said, what is shown, the "speaking" icon turns off);
- every case assertable with the fake (
stream_events, anerrorevent,first_delay,gap), and a question for the product owner about the part of the answer already read aloud.
10. Knowledge check
0/18 done · Results are kept in this browser only.
P02 · True or false
P03 · Short answer
How does TTFT differ from total time? How does the user experience each metric?
P04 · Short answer
Why can a test with the fake API not measure the latency of the real model? What can it verify?
P05 · Short answer
(Scenario) A report says "TTFT = 0.7 seconds". List three questions you need to ask before you trust this figure.
P06 · Fill in the blank
P07 · Multiple choice
P08 · Spot the bug
The function below is copied from lab/streaming.py but has one defect. Find it.
def stream_with_timing(client, learner_text, model="claude-opus-5-5", max_tokens=300, clock=time.perf_counter):
start = clock()
first = None
chunks = []
with client.messages.stream(model=model, max_tokens=max_tokens,
messages=[{"role": "user", "content": learner_text}]) as stream:
for text in stream.text_stream:
if first is None:
first = clock()
chunks.append(text)
final = stream.get_final_message()
end = clock()
return {
"text": "".join(chunks), "chunks": len(chunks), "stop_reason": final.stop_reason,
"output_tokens": final.usage.output_tokens,
"ttft_s": None if first is None else end - start, "total_s": end - start,
}P09 · True or false
P10 · Multiple choice
P11 · Recall
Lesson: L1-M03-L03P13 · Multiple choice
P14 · Fill in the blank
P15 · True or false
P16 · True or false
P17 · Apply now
In code-labs/l1-m03, run the code from the worked example of §5.1. Then change the fake clock to iter([5.0, 5.3, 6.5]) and run it again; finally try iter([10.0, 10.4]) (only two values).
P18 · Apply now
In code-labs/l1-m03, do the extra exercise in §9.1: copy exercises/test_l04_extra_percentile.py into tests/ and run python -m pytest tests/test_l04_extra_percentile.py.
11. Summary
- Concepts: SSE and the order of events; cumulative usage in
message_delta; TTFT and total time; errors after HTTP 200; measuring latency as a distribution. - Skills: streaming with the SDK; measuring TTFT; creating a fake stream with a known delay; testing mid-stream errors.
- Traps: measuring once; using the average instead of a percentile; ignoring the stop reason at the end of the stream; treating 200 as success.
- You can now: test a streaming feature and plan latency measurements.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Streaming messages | Anthropic | https://platform.claude.com/docs/en/build-with-claude/streaming | 2026-10-31 | Event order; cumulative usage; the error event |
| R2 | Glossary (TTFT) | Anthropic | https://platform.claude.com/docs/en/about-claude/glossary | 2026-10-31 | Definition of time to first token |
| R3 | Claude API errors (streaming, long requests) | Anthropic | https://platform.claude.com/docs/en/api/errors | 2026-10-31 | Errors after HTTP 200; using streaming for long requests |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Streaming | Gửi câu trả lời từng phần |
| Server-sent events (SSE) | Sự kiện do server gửi qua một kết nối HTTP |
| Chunk / delta | Một mảnh output trong stream |
| Time to first token (TTFT) | Thời gian tới token đầu tiên |
| Latency budget | Ngưỡng độ trễ cho phép |
| Percentile (p95) | Giá trị mà 95% số lần đo nằm dưới |
| Median | Trung vị |