Latency Engineering for a Claude Agent Loop: Time to First Token vs Total, Streaming, Parallel Tools, the Cache and Effort
A SupportDesk agent shows nothing for 5,624 ms, then everything at once. Stream each call, run the two tools together, cache the system prompt and hold effort at low: the first word lands at 1,560 ms and the answer finishes at 2,600 ms, inside both targets once the cache is warm.
What you will learn
- Measure time to first token and total latency as two separate clocks on one agent request
- Stream every call and stamp the first word when it arrives
- Run independent tool calls together so the slowest one sets the wait
- Use a cached system prompt and one fixed effort level, and see what a cold cache costs
Before you start
- Claude tool use and the agent loop
- Claude streaming basics
- Prompt caching basics
Picture a support chat. A customer asks about a refund, and then nothing happens. The agent is working, but the screen stays blank.
In this article we tune that agent loop with four levers: streaming, parallel tools, the cache and effort. The catch is that they don't all move the same clock.
Two clocks on one request
Think of a restaurant. A guest cares about two moments: when the bread reaches the table, and when the last plate is served. The first is the time to first token (first word on screen). The second is the total latency (the answer is done).
- Bring bread while the kitchen is still cooking: streaming.
- Use two cooks at once: run independent tools in parallel.
- Have the station already set up: a cached prefix.
- Cook a simpler dish: a lower effort level.
The chat shows nothing for five seconds
Ticket T-301 asks: Where is my refund, and which return policy applies? The agent calls the model, runs two tools (lookup_customer and search_help), and calls the model again. Four stages in a row.
The demo targets: the first word within 2,000 ms, the whole answer within 3,000 ms. The project runs on a stand-in model (the Anthropic SDK on an httpx mock transport) with a virtual clock, so no API key is needed, the replies are test replies, and every time below is a made-up virtual millisecond.
baseline.py: plain calls, tools in a row
"""The before version: plain calls, tools in a row, no cache."""
import stand_in
from stand_in import PRIMARY
from tools import SYSTEM, TOOLS, run_tool
def handle(ticket, client, prof):
msgs = [{"role": "user", "content": ticket["text"]}]
for _ in range(4):
r = client.messages.create(
model=PRIMARY, max_tokens=1024, system=SYSTEM,
tools=TOOLS, messages=msgs)
if r.stop_reason != "tool_use":
prof.first_token() # nothing is shown until the end
return "".join(
b.text for b in r.content if b.type == "text")
msgs.append({"role": "assistant", "content": r.content})
results = []
for block in (b for b in r.content
if b.type == "tool_use"):
out, ms = run_tool(block)
stand_in.advance(ms) # one tool, then the next
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": str(out)})
msgs.append({"role": "user", "content": results})
raise RuntimeError("the agent used up its calls")
- A plain
createcall waits for every token. No cache mark, no effort setting. - The first word is stamped only when the whole answer is back.
- The two tools are independent reads, but the loop runs them one after the other: 300 ms, then 500 ms.
tuned.py: stream, run together, cache, one effort
"""The tuned version: stream, parallel tools, cache, one effort."""
from concurrent.futures import ThreadPoolExecutor
import stand_in
from stand_in import PRIMARY
from tools import SYSTEM, TOOLS, run_tool
CACHED = [{"type": "text", "text": SYSTEM,
"cache_control": {"type": "ephemeral"}}]
EFFORT = {"effort": "low"} # one level for every call
def handle(ticket, client, prof):
msgs = [{"role": "user", "content": ticket["text"]}]
for _ in range(4):
with client.messages.stream(
model=PRIMARY, max_tokens=1024, system=CACHED,
tools=TOOLS, messages=msgs,
output_config=EFFORT) as stream:
shown = []
for text in stream.text_stream:
prof.first_token() # first word, as it arrives
shown.append(text)
r = stream.get_final_message()
if r.stop_reason != "tool_use":
return "".join(shown)
msgs.append({"role": "assistant", "content": r.content})
calls = [b for b in r.content if b.type == "tool_use"]
with ThreadPoolExecutor() as pool: # run them together
done = list(pool.map(run_tool, calls))
stand_in.advance(max(ms for _, ms in done)) # slowest wins
msgs.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": b.id,
"content": str(out)}
for b, (out, _) in zip(calls, done)]})
raise RuntimeError("the agent used up its calls")
- Cache: the system prompt carries a
cache_controlmark, so that stable prefix can be read from the cache next time (see prompt cache breakpoints). - Effort: set once, to
low, inoutput_config, and every call in the loop uses that same level. Lower effort means fewer tokens (see adaptive thinking and effort). - Streaming: every call uses
messages.stream, and the first word is stamped the moment it arrives, so the number you measure is what the customer feels. - Parallel tools: the two tools are independent reads, so they run together. The slowest one sets the wait.
When are tools safe to run together? When neither needs the other's result and neither changes anything. Two reads qualify. A lookup followed by a refund that uses the lookup's answer does not.
One ticket, three runs
target: first token <= 2000 ms, total <= 3000 ms (virtual ms)
baseline first 5624 | total 5624 | over target
model 2144 + tools 800 + model 2680 | cache read 0
tuned, cold cache first 2208 | total 3248 | over target
model 1444 + tools 500 + model 1304 | cache read 1800
tuned, warm cache first 1560 | total 2600 | within target
model 796 + tools 500 + model 1304 | cache read 3600
- Baseline: 2,144 ms for the first call, 800 ms of tools in a row, 2,680 ms for the second call. The first word and the total are both 5,624 ms. The customer stares at a blank chat, then gets everything at once.
- Tuned, warm cache: 796 ms, then 500 ms for both tools together, then 1,304 ms. The first word shows at 1,560 ms, while the second call is still streaming, and the answer is done at 2,600 ms. Inside both targets.
- The tools: 800 ms in a row became 500 ms together, the time of the slowest one.
- The cache: 3,600 cached tokens read across the two calls on the warm run.
Keep the prefix warm, hold one effort
Look at the middle run. With a cold cache, the first call writes the prefix and only the second reads it (1,800 cached tokens instead of 3,600). The first call takes 1,444 ms instead of 796, the first word lands at 2,208 ms and the total at 3,248 ms. Still over target. Warming the cache ahead of traffic removes that penalty.
And effort: a new top-level effort value on the next request can invalidate the cached prefix. That is why the tuned loop sets EFFORT once and keeps it for every call. Switch effort between calls and you can lose the cache hit that was making the first word fast.
Common mistakes
- Moving to a larger model when users say it feels slow. Larger models are usually slower.
- Setting effort to max. It thinks longer before the first word.
- Lowering
max_tokens. That only cuts answers off. - Expecting streaming to cut the total. It moves the first marker. It can't move the end. If the total is in target but users still wait, stream; if the total is over, look at tools, cache and effort.
- Stamping the first token after the call returns. Then you are measuring the total twice and calling one of them TTFT.
- Running dependent tools in parallel. Only independent reads can go together.
For the streaming events themselves see Claude streaming events, and for finding which line of a slow request to cut first, cutting p95 and cost.
Quick recap
| Lever | Clock it moves | In this run |
|---|---|---|
| Streaming | First token only | first word before the answer ends |
| Parallel tools | Total (and first token, when tools come first) | 800 ms to 500 ms |
| Cached prefix | Both: less work before the first word | first call 1,444 to 796 ms |
| Effort, held at one level | Both: fewer tokens | low on every call |
Try it yourself
Add a third independent tool that takes 900 ms. Predict the tuned total with the cache warm before you run it: does it grow by 900, by 400, or by nothing? Then make the third tool depend on the CRM lookup's result and decide how the loop should change.
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
