CCDV-P Study Guide
Free study guide for the Claude Certified Developer - Professional (CCDV-P) exam: 25 lessons, one per official skill, on running Claude systems in production. One chapter per exam domain, one page per lesson, in the order the official exam guide lists them.
6. Domain 6: Cost and Latency Optimization at Scale
6.2. 6.2 Latency engineering: TTFT, streaming, parallel tools, caching and effort
CCDV-P · Domain 6 · Lesson 6.2 · 21 min read
Decompose a Claude agent's wait against a p95 target, tell time to first token from total latency, and apply streaming, parallel tools, caching and effort.
Why a fast model still keeps a stranded passenger waiting 11 seconds
A winter storm closes Saltmarsh Air's hub for four hours. A hundred and sixty flights are cancelled, and twenty thousand passengers reach for their phones at the gate. In the mobile app each of them taps "Rebook me", and a Claude agent reads the booking, searches alternative flights, checks which fare rules the storm waiver relaxes, and offers up to three options. On a quiet day the first option appears in about three seconds. Today a spinner turns for eleven, and every passenger who gives up joins a call-centre queue that is already two hours long.
Teodora, the site reliability engineer who owns the rebooking service, has a product target to defend: the first rebooking option on screen within 4 seconds for 95% of taps. Her manager's first instinct is that the model is slow. It is not. Her traces show the model writing tokens about as fast on a storm day as on a quiet one. What changed is how many times the agent asks it to, what it waits for in between, and how much it writes.
Latency engineering is the practice of splitting one user's wait into its components, finding the component that dominates at the percentile you are judged on, and applying the lever that shrinks THAT component. Claude decides which tools to call and how much to write; your code decides how calls are batched, cached, streamed and run.
Decompose the wait before you touch it
Here is the question that trips up experienced engineers: if a request takes 11 seconds, which second do you cut first? Without a breakdown you cannot answer, and teams end up tuning whatever is easiest to change. A trace with one span per step (each model call and each tool call, joined by one trace id) turns the single number into a list you can reason about.
Every model call has the same anatomy. The API first processes the input: the system prompt, tool definitions and conversation so far. The model may then think, and thinking tokens are output tokens, generated before the answer starts. Then it writes the answer at a roughly steady rate, so its duration grows with the number of tokens it emits. An agent repeats that whole anatomy once per round trip, and between round trips your code runs tools.
Here is the trace Teodora pulled for a request at the 95th percentile during the storm. Look at how few seconds belong to any single model call, and how many belong to the number of calls.
| Step | Duration | Component |
|---|---|---|
| Phone to backend and back | 0.3 s | Network |
| Waiting for a worker, plus one retried 429 | 0.9 s | Queueing |
Turn 1: read a 15,000-token prompt, request get_booking |
1.4 s | Input processing, short output |
get_booking |
0.4 s | Tool |
Turn 2: request search_alternative_flights |
1.3 s | Extra round trip |
search_alternative_flights |
1.6 s | Tool |
Turn 3: request check_fare_rules |
1.2 s | Extra round trip |
check_fare_rules |
0.5 s | Tool |
| Turn 4: think, then write a 430-token answer | 3.6 s | Thinking plus output tokens |
| Total | 11.2 s |
Four model calls account for 7.5 seconds, tools for 2.5 and transport and queueing for 1.2. Two of the four calls exist only because the agent asked for one tool at a time, and the last is the slowest because it writes the most. Neither problem is the model's speed.
Where one rebooking request spends its time
Targets are percentiles: fix the tail you are measured on
Why does the same service feel fine to one passenger and broken to another? Because latency is a distribution, not a number. The p50 (median) is the time half of all requests finish within; the p95 is the time 95% finish within, so it describes the slowest one request in twenty. Saltmarsh's target is a p95, and on a storm day the gap between the two is wide: p50 is 6.1 seconds, p95 is 11.2.
An average hides that gap completely. Worse, the requests in the tail are usually slow for different reasons than the typical one. Teodora compared a p50 trace with the p95 trace. The median passenger had a single-leg booking, the agent made three calls, no retry happened and the inventory search took 0.9 seconds. The tail passenger had a two-leg booking with a connection, the agent made four calls, a rate-limit error (HTTP 429) was retried, the search took 1.6 seconds under load and the answer was long.
The SDK retries a 429 or an overload error (HTTP 529) up to two times by default, waiting as long as a retry-after header says or backing off exponentially, and every retry lands on the passenger's clock. Complex cases trigger more round trips and longer explanations. Each component in a sequence adds its own tail, so a request that strings five slow-ish steps together is far more likely to land at p95 than one with two steps.
Which number tells Teodora whether the target is met
Two measurement rules follow. Measure where the user feels it: the phone's clock includes mobile network time that the backend never sees. And measure during the conditions the target covers: a load test on a quiet afternoon will happily report 3.4 seconds while the storm-day tail sits at 11.
Which wait the passenger feels: TTFT versus total
Here is the distinction the exam returns to most often. Time to first token (TTFT) is how long it takes from sending a request until the first token of the response arrives. Total latency is how long until the last one arrives. For a single call the difference is the output: tokens divided by the generation rate. A user who watches text appear feels mostly the first number; a backend job that needs the full JSON feels only the second.
Streaming is what makes TTFT visible. With "stream": true, or the SDK's stream() helper, the API sends server-sent events as the response is produced. A stream opens with message_start; each content block then sends a content_block_start, a series of content_block_delta events and a content_block_stop; message_delta and message_stop close it. Text arrives in text_delta events, which your backend forwards to the phone as they come. Without streaming, the passenger sees nothing until the last token, so their TTFT equals the total.
Think of a kitchen that sends out each dish as it is ready instead of holding the order until dessert is plated: the meal takes as long, but nobody stares at an empty table. Streaming changes when the user sees output, not how much work the model does.
The function below times one model call both ways. Look at the line that records the first text_delta, which is what the passenger feels, and the line after the stream ends, which is what the turn costs.
import time
import anthropic
client = anthropic.Anthropic()
def timed_turn(system, messages, tools, send_to_app):
start = time.monotonic()
first_text = None
with client.messages.stream(model=MODEL, max_tokens=4096, system=system,
messages=messages, tools=tools) as stream:
for event in stream:
if event.type == "content_block_delta" and event.delta.type == "text_delta":
if first_text is None:
first_text = time.monotonic() - start # what the passenger feels
send_to_app(event.delta.text) # forward each chunk at once
message = stream.get_final_message()
total = time.monotonic() - start # what the turn costs
return message, first_text, total
Now the catch for agents. In a tool-using agent, the passenger's TTFT is not the TTFT of one call. It is everything before the first visible text of the final turn: all earlier round trips, all tool time, and any thinking the final call does before it writes. Teodora streamed turn 4 and the first option appeared at 8.3 seconds instead of 11.2. A real gain, and still double the target.
What the passenger sees with and without streaming
Not streamed
Final turn streamed
Fewer, overlapping round trips: parallel tools and prefetch
The trace showed two round trips that existed only to ask for one tool at a time. Parallel tool use removes them: Claude can return several tool_use blocks in one response, and the docs say Claude 4 and later models do so by default when a request benefits from several tools. Your code then decides how to run them. The API does not prescribe an order, so independent, read-only lookups can run at the same time.
Two rules keep parallelism working. Return one tool_result per tool_use, all together in the next user message, matched by tool_use_id and placed before any text. Sending each result in its own message teaches the model to stop calling tools in parallel. And run concurrently only what is safe: tools with side effects, shared state or ordering requirements belong in sequence. At Saltmarsh, search_alternative_flights and check_fare_rules both need only the booking, so they can overlap. confirm_rebooking, which changes the ticket, never runs alongside anything and only after the passenger taps an option.
Look at the gather line, which runs the lookups at the same time, and the return, which puts every result in one message.
async def run_lookups(tool_uses):
# Read-only and independent, so run them concurrently
outputs = await asyncio.gather(*(LOOKUPS[t.name](**t.input) for t in tool_uses))
return {"role": "user", "content": [ # ALL results, ONE message
{"type": "tool_result", "tool_use_id": t.id, "content": json.dumps(out)}
for t, out in zip(tool_uses, outputs)]}
Concurrency changes the arithmetic. Sequential tools add up; concurrent tools cost as much as the slowest one. The 1.6-second search and the 0.5-second fare check now take 1.6 seconds together, and turn 3 disappears with its 1.2 seconds.
The cheapest round trip is the one that never happens. The first call in every rebooking asks for get_booking, and the app already knows which booking the storm hit. So the app now loads the booking when the passenger opens the trip, before they tap, and sends it in the first request. Turn 1 and its tool leave the passenger's clock entirely. If parallel calls are rare, the docs suggest telling Claude to invoke all relevant tools simultaneously when operations are independent.
Four round trips become two
Before: one tool per trip
get_bookingsearch_alternative_flightscheck_fare_rulesAfter: prefetch and parallel
Cheaper round trips: cache, effort and output length
Two trips remain. Three levers make each one cheaper, each aimed at a different component of a model call.
Cache checkpoints cut input processing. Every Saltmarsh request starts with the same tool definitions and a long system prompt that now includes the storm waiver policy, about 12,000 tokens identical for every passenger. Prompt caching lets the API reuse that processed prefix. You mark a cache breakpoint with cache_control: {"type": "ephemeral"} on the last block whose prefix stays identical; the prefix runs in the order tools, then system, then messages, and a request can carry up to four breakpoints. The docs describe the effect as improved time to first token for long documents. Content that changes per request, such as the passenger's booking or the current disruption notice, goes AFTER the breakpoint. A timestamp at the top of the system prompt would turn every request into a cache write and never a read.
Effort and thinking shape what is generated before the answer. The output_config.effort parameter (low, medium, high, and on some models xhigh and max) tells Claude how many tokens to spend across the whole response: text, tool calls and thinking. Claude Opus 4.5 and the 4.6 and later models accept it, and omitting it runs the model's default, high on most models and medium on Claude Opus 5.5 and Claude Haiku 5.5. Lower effort means less thinking, fewer and terser tool calls, and less wait before the first visible word. Choosing options from a policy is well specified, so Teodora tests low against the eval set before shipping it.
On current models with adaptive thinking, effort is the dial for thinking depth. A fixed thinking budget (budget_tokens with thinking: {"type": "enabled"}) is a deprecated legacy feature: the docs say Claude 4.7 and later models reject it with a 400 error.
Output length decides generation time. The final call wrote 430 tokens: an apology, a paragraph of policy, then three options in full prose. The app needs up to three options, one line each, and one sentence on the waiver. Prompting for that shape cut the answer to about 120 tokens. Ask for a format, not a word count, and leave max_tokens as a ceiling with room for thinking, since a response that hits it is cut off mid-sentence.
| Lever | Component it shrinks | What it costs or risks |
|---|---|---|
| Cache breakpoint on the static prefix | Input processing on every call | A write premium on misses; dynamic content must sit after the breakpoint |
Lower effort |
Thinking and tool-call tokens before the answer | Some capability on hard cases; validate on your eval first |
| Shorter output format | Generation time of the final call | Less explanation; a prompt change to test |
Low max_tokens as a length control |
Nothing reliable | Truncated answers mid-sentence |
Memorise the first three rows as the levers and the fourth as the trap. Teodora's final p95 trace: network 0.3 s, queueing 0.2 s once capacity was raised, a cached trip at low effort 1.0 s, both tools 1.6 s, and 0.6 s to the first streamed word. The first option appears at 3.7 seconds; the last finishes at about 4.7. The target measures the first, and it is met.
The exam traps
- ✗ Report the average or p50 against a p95 target. ✓ Measure the percentile the target names, from production traces under the conditions it covers, because tail requests are slow for reasons the median never hits.
- ✗ Turn on streaming and declare the agent fast. ✓ Streaming moves the first visible token to the start of the final turn; in an agent, earlier round trips and tool time still count, so cut trips too.
- ✗ Swap in a smaller model as the first move. ✓ Find the dominant component first. Extra round trips, long output and high effort usually cost more than model speed, and a smaller model must pass the same eval.
- ✗ Set
max_tokenslow to make answers shorter. ✓ Prompt for a compact format;max_tokensis a hard ceiling that truncates mid-sentence and, with thinking on, also limits thinking. - ✗ Run every requested tool concurrently. ✓ Run independent, read-only lookups concurrently and return all results in one message; keep tools with side effects, such as
confirm_rebooking, in sequence. - ✗ Put a timestamp or per-user data at the top of the system prompt. ✓ Keep static content first and place the cache breakpoint after it, with dynamic content later, or every request pays full input processing.
Put it together: bring an agent's p95 under target
You now have every piece. A latency model splits the wait into its components across round trips, and the target names a percentile. Streaming serves the TTFT the user feels. Parallel tools and prefetch remove trips, and cache breakpoints, effort and output format make the remaining trips cheaper.
The same habits carry across the domain. Cost architecture (6.1) reads the same usage records for spend rather than seconds, and a cached prefix often wins both. Scale and throughput management (2.2) decides how much queueing and retrying a surge adds before latency engineering even starts.
Key takeaways
- ✓ Latency is a sum of network, queueing and, for each round trip, input processing, thinking, output tokens and sequential tool time; decompose it from a trace before fixing anything.
- ✓ Targets are percentiles, and the p95 tail is made of extra trips, retries, slow tools and long outputs that averages and the median hide.
- ✓ Time to first token is what a reading user feels and total latency is what a waiting process feels; streaming exposes the first without shrinking the second.
- ✓ In an agent, every earlier round trip sits before the first visible token, so removing trips with parallel tool calls and prefetching is often the biggest lever.
- ✓ Run only independent, read-only tools concurrently and return every result in one user message.
- ✓ Cache breakpoints after the static prefix cut input processing, lower effort cuts thinking and tool-call tokens, and a compact output format cuts generation, each validated on an eval.
Practise this
Practice questions for CCDV-P are being written and are not in this course yet. Read this lesson on the web to answer its check questions, with every option explained: https://claude.termidy.com/learn/ccdv-p/cost-latency-optimization/latency-engineering/.