Users Were Abandoning Our AI Copilot at p95 4.2s — Dead Air, Serial Tools, and the Streaming Fix That Took It to 1.8s
p95 was 4.2s and nothing rendered until the run finished — users left. Streaming, parallel tools, caching, and the fix that took it to 1.8s.
- Author
- Randhir Jassal
- Published
- Reading time
- 22 min read
- Views
- 5 views
AI in Production: War Stories, Scenario #3. One real production incident per post: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — then how to tell it in a senior interview, with the follow-ups you'll actually get. Scenario #1 was the hallucination incident; Scenario #2 was the $0.90-per-run bill. This one is about seconds.
The incident
This time the alert didn't come from finance. It came from product analytics: a funnel chart showing that 14% of Mattrx Insights runs ended with the user closing the panel before the answer arrived. Users would ask "why did conversions dip in the EMEA segment last week?", stare at a spinner, and leave. The session recordings were brutal to watch — three seconds of a pulsing dot is an eternity when the competing tab is a dashboard the user already knows how to read.
The numbers: p95 time-to-answer was 4.2 seconds, p50 was 2.9s, and — the stat that actually explained the abandonment — time-to-first-visible-anything was identical to time-to-answer, because we rendered nothing until the run finished. The 30-second monster runs from Scenario #2's runaway loops were abandoned essentially 100% of the time. A feature can survive being slow. It cannot survive looking dead.
One note on timelines, because Scenario #2 and this incident overlap: the 4.2s p95 was measured in the same "before" era as the $0.90 runs. The cost work — compaction, budgets, fewer iterations — had already pulled p95 down to roughly 3.1s as a side effect by the time we started the latency war proper. This post is about the rest of the distance, and the full before/after arc is 4.2s to 1.8s.
Architecture: where the seconds went
MATTRX INSIGHTS - ONE AGENT RUN, AS A TIMELINE (BEFORE)
t=0 t=4.2s
|-----------------------------------------------------------|
user asks answer appears
what the user saw: [............ spinner ............] [L1]
what actually ran:
turn 1 [ TTFT ~450ms ][ generate ][ tool A 130ms ]
turn 2 [ TTFT ~450ms ][ generate ][ tool B 130ms ] [L2]
turn 3 [ TTFT ~450ms ][ generate ][ tool C 130ms ]
turn 4 [ TTFT ~450ms ][ generate ][ tool D 130ms ]
turn 5 [ TTFT ~450ms ][ long final answer ~1.2s ] [L5]
^ ^
[L3] [L4]
[L1] Dead air: nothing rendered until the entire run finished.
Perceived latency == total latency, every single run.
[L2] One tool call per turn, every turn serial. Tools that did
not depend on each other still ran one after another.
[L3] TTFT ~450ms per turn: the prompt prefix was re-processed
from scratch every call (the cache-miss bleed confessed in
Scenario #2 hurt latency before we ever noticed the cost).
[L4] Each tool call blocks the loop: model waits on tool, tool
waits on model, nothing overlaps.
[L5] The final answer was generated at full verbosity with no
output contract -- a quarter of the run spent typing.
Five turns of roughly 800ms each. No single component was scandalous — 450ms TTFT is ordinary for an uncached prefix, 130ms is our analytics read-tool p95, generation speed was normal. The latency wasn't in any box; it was in the shape: everything serial, nothing streamed, nothing cached.
Triage: what we checked first (including the dead ends)
- "We need more instances." Dead end. The reflex from classic web-perf incidents. We doubled the burst pool; p95 moved by ~50ms. Of course it did: this latency was serial time inside each run, not queueing in front of runs. Scaling out fixes contention, and we didn't have contention.
- "It's the provider — move the AI service closer." Dead end. We benchmarked the same calls from the AI service's region and from a VM colocated as close to the model endpoint as we could get: ~40ms per call difference. Across five turns, 200ms — real but nowhere near the seconds we needed. Network was not the story.
- "Shorten the prompt" — the blanket cut that failed the gate. Someone trimmed the system prompt aggressively, including two of the investigation rules. TTFT improved a little. The eval score dropped from 0.92 to 0.88 — below our 0.90 floor — because the agent started skipping the segment-comparison step the deleted rules enforced. Reverted. Lesson that foreshadows Scenario #4: context reduction works, but it's surgery, not a haircut.
- Span timing per run — the real signal. We already had per-call token telemetry from Scenario #2; we added wall-clock spans per stage (model TTFT, model generation, tool execution) and rendered a few hundred runs as waterfalls. The decomposition at p95: ~58% model time spread across serial turns, ~22% serial tool time, ~20% final-answer generation. And one number that reframed everything: time-to-first-rendered-byte was 100% of total, because we streamed nothing.
Root cause, stated plainly: answer latency = serial turns x (TTFT + generation + tool time), and perceived latency = time until the user sees signs of life — and we were maximizing both. No caching (every turn paid full prefix processing), no parallelism (independent tools ran serially), no batching pressure (one tool per turn), no streaming (perceived == total). Scenario #2's bill and this incident were the same loop, measured in different units.
The broken run — a POC you can feel
Run this and watch the timestamps. The point isn't that it's wrong; it's that it's the obvious way to write it.
# slow_agent.py - the latency anti-pattern. Every quickstart looks like this.
import time
import anthropic
client = anthropic.Anthropic()
def run(question: str, tools: list[dict], execute_tool) -> str:
t0 = time.perf_counter()
messages = [{"role": "user", "content": question}]
while True:
response = client.messages.create( # [L3] cold prefix, every turn
model="claude-sonnet-5-5",
max_tokens=4096, # [L5] no output contract
tools=tools,
messages=messages, # blocks until FULLY generated
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
answer = next(b.text for b in response.content if b.type == "text")
print(f"[{time.perf_counter()-t0:5.2f}s] user sees ANYTHING") # [L1]
return answer
results = []
for block in response.content: # [L2][L4] strictly serial
if block.type == "tool_use":
out = execute_tool(block.name, block.input) # model idles here
results.append({"type": "tool_result",
"tool_use_id": block.id, "content": out})
print(f"[{time.perf_counter()-t0:5.2f}s] ran {block.name}")
messages.append({"role": "user", "content": results})
The print statements are the indictment: tools finish at 0.8s, 1.6s, 2.4s... and the first line the user sees arrives after everything. Four seconds of work, four seconds of silence.
The fix: attack both latencies
Two different problems, so two different budgets: actual latency (serial turns, serial tools, cold prefixes, verbose output) and perceived latency (dead air). The production loop fixes both.
# fast_agent.py - the production loop. Python 3.11+, pip install anthropic
import asyncio
import json
import logging
import time
from dataclasses import dataclass, field
import anthropic
log = logging.getLogger("mattrx.insights.agent")
client = anthropic.AsyncAnthropic(max_retries=2, timeout=30.0)
MODEL_WORKER = "claude-sonnet-5-5" # tiering from Scenario #2 stays; the
# mid-tier model is also the faster one.
TOOL_TIMEOUT_S = 1.5 # p95 for our read tools is 120ms; 1.5s is generous
SOFT_DEADLINE_S = 3.0 # past this, instruct the agent to conclude
MAX_ANSWER_TOKENS = 700 # the output contract: findings are tight, not essays
SYSTEM = ("You are Mattrx Insights, an analytics investigation agent. "
"Plan first, then request ALL independent lookups in a single "
"turn as multiple tool calls. Write findings as a short headline "
"plus 3-5 tight bullets; never pad.")
WRAP_UP = ("Deadline notice: conclude now from the evidence you already "
"have, stating any caveats. Do not request more tools.")
@dataclass
class Spans:
"""Wall-clock accounting per stage - the waterfall we triage with.
Exported to OpenTelemetry; kept here as plain floats for clarity."""
t0: float = field(default_factory=time.perf_counter)
first_token_at: float | None = None
model_s: float = 0.0
tool_s: float = 0.0
turns: int = 0
def mark_first_token(self) -> None:
if self.first_token_at is None:
self.first_token_at = time.perf_counter() - self.t0
async def run_tool(execute_tool, block, spans: Spans) -> dict:
"""One tool call: bounded by a timeout, degraded on breach.
A slow tool costs ITS budget, never the whole run's."""
t = time.perf_counter()
try:
out = await asyncio.wait_for(
execute_tool(block.name, block.input), timeout=TOOL_TIMEOUT_S)
return {"type": "tool_result", "tool_use_id": block.id, "content": out}
except asyncio.TimeoutError:
log.warning("tool_timeout", extra={"tool": block.name})
return {"type": "tool_result", "tool_use_id": block.id,
"is_error": True,
"content": "Tool timed out. Proceed without this data and "
"state the gap in your finding."}
finally:
spans.tool_s += time.perf_counter() - t
async def run(question: str, run_id: str, execute_tool, tools: list[dict]):
"""Async generator: yields UI events the panel renders over SSE.
The user sees life at first token, progress at every tool call."""
spans = Spans()
messages: list[dict] = [{"role": "user", "content": question}]
wrap_up_sent = False
while True:
spans.turns += 1
t_model = time.perf_counter()
# Streaming + a byte-stable cached prefix: the two TTFT levers.
# System and tools never change between turns or runs; history
# grows after the cache breakpoint. (Scenario #2, case 6: one
# volatile byte up top and this entire lever silently vanishes.)
async with client.messages.stream(
model=MODEL_WORKER,
max_tokens=MAX_ANSWER_TOKENS,
system=[{"type": "text", "text": SYSTEM,
"cache_control": {"type": "ephemeral"}}],
tools=tools,
messages=messages,
) as stream:
async for event in stream:
if event.type == "content_block_delta" and \
event.delta.type == "text_delta":
spans.mark_first_token()
yield {"event": "answer_delta", "text": event.delta.text}
response = await stream.get_final_message()
spans.model_s += time.perf_counter() - t_model
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
yield {"event": "done",
"spans": {"total_s": round(time.perf_counter() - spans.t0, 2),
"first_token_s": round(spans.first_token_at or 0, 2),
"model_s": round(spans.model_s, 2),
"tool_s": round(spans.tool_s, 2),
"turns": spans.turns}}
return
tool_blocks = [b for b in response.content if b.type == "tool_use"]
for b in tool_blocks:
yield {"event": "tool_started", "tool": b.name} # visible progress
# THE parallelism lever: independent tool calls from one turn
# run concurrently. Three 130ms lookups cost ~140ms, not ~390ms.
results = await asyncio.gather(
*(run_tool(execute_tool, b, spans) for b in tool_blocks))
messages.append({"role": "user", "content": list(results)})
if (time.perf_counter() - spans.t0) > SOFT_DEADLINE_S and not wrap_up_sent:
messages.append({"role": "system", "content": WRAP_UP})
wrap_up_sent = True
The design decisions that matter:
- Streaming is a UX decision enforced in the transport. The loop is an async generator yielding
answer_deltaandtool_startedevents over SSE; the panel renders tokens as they arrive and names the lookup it's waiting on. Perceived latency collapsed from "the whole run" to first token — p95 ~300ms — and "is it stuck?" tickets stopped. - Parallelism follows the model's own batching. The system prompt demands all independent lookups in one turn;
asyncio.gatherruns them concurrently. We did not build a dependency planner — the model already expresses independence by emitting multipletool_useblocks in a single turn, and tool-level timeouts keep one slow call from dragging the batch. - The cache lever was already paid for. Scenario #2's byte-stable prefix, adopted for cost, is also the TTFT fix: a cache hit skips re-processing the system-plus-tools prefix, and per-turn TTFT fell from ~450ms to ~180ms. One mechanism, two line items.
- The deadline is soft and honest. Past 3 seconds the agent is told to conclude with caveats — same graceful-wrap-up pattern as Scenario #2's cost budget, in seconds instead of dollars. Hard caps still exist underneath; the soft deadline is what users experience.
- The output contract is part of latency. Findings are a headline plus 3-5 bullets,
max_tokens=700. A quarter of the old p95 was the model typing an essay nobody wanted.
Every latency case — and which control catches it
Agent latency shows up in six distinguishable shapes. Diagnose from the waterfall; each has its own fix:
| # | Case | Symptom in telemetry | Control that catches it |
|---|---|---|---|
| 1 | Dead air | time-to-first-byte == total run time | Stream deltas + tool-progress events over SSE |
| 2 | Cache-miss TTFT bleed | TTFT high on every turn; cache_read_input_tokens ~0 | Byte-stable system/tool prefix (same fix as the cost case) |
| 3 | Serial independent tools | tool wall-time == sum of per-tool times | One-turn batching prompt + asyncio.gather |
| 4 | Chatty loop | many turns, one tool each | Plan-first instruction + tools designed as intents, not endpoints |
| 5 | Slow-tool outlier | one span dominates the waterfall | Per-tool timeout + degraded result that names the gap |
| 6 | Verbose finale | long final generation span | Output contract + right-sized max_tokens |
The case-2 confession from Scenario #2 is worth repeating from the latency side: our first caching attempt had a timestamp in the system prompt. We found it because the bill looked wrong. The latency waterfall had been showing the same 450ms TTFT on every turn for weeks — we just hadn't yet learned to read that as a symptom.
What it cost to fix — and the guardrails
Latency work has two classic failure modes: buying speed with quality, or buying speed with money. Both gates were already standing from the previous incidents, and every change ran through them:
- Quality (eval gate, 0.90 floor): streaming, parallelism, and caching are quality-neutral by construction — same tokens, same answers, different schedule. The two changes that could move quality were measured: the output contract held at 0.92 (tight findings scored as well as essays — relevance actually benefits), and the blanket prompt cut from triage is the counterexample that failed at 0.88 and was reverted.
- Cost (the Scenario #2 meter): parallel tools and streaming are free — same calls, rearranged. We evaluated request hedging (fire a duplicate model call, keep the faster) and rejected it: it buys tail latency by roughly doubling spend on hedged turns, and our tail was loop-shaped, not variance-shaped. Cost per run stayed at $0.12, now protected by the meter and the latency dashboard watching each other.
- Engineering cost: about two weeks for one engineer, most of it the SSE path through the gateway and the panel rendering states — the agent-loop changes themselves were the smaller half.
Results
| Metric | Before | After |
|---|---|---|
| Time to full answer (p95) | 4.2s | 1.8s |
| Time to full answer (p50) | 2.9s | 1.1s |
| Time to first visible token (p95) | == full answer | ~300ms |
| TTFT per model call (p95) | ~450ms | ~180ms (cache hit) |
| Wall time for a 3-lookup turn | ~390ms | ~140ms |
| Model turns per run (p50) | 5 | 3 |
| Runs abandoned before answer | 14% | 2% |
| Eval score (gate: 0.90 floor) | 0.92 | 0.92 |
| Cost per run | $0.12 | $0.12 |
The 2% that still abandon are mostly budgeted partial answers on genuinely hard questions — tracked, ticketed, and a context problem more than a latency one. Which is foreshadowing: the next war is the context window itself.
In the interview
The 60-second STAR version: "Our agentic analytics copilot had a p95 time-to-answer of 4.2 seconds with nothing rendered until completion, and product analytics showed 14% of runs abandoned before the answer arrived (Situation). I owned getting latency to a shippable level without regressing quality — gated by a golden-set eval with a 0.90 floor — or cost, which we'd just fought down in a previous incident (Task). I instrumented per-stage spans and found the latency was structural: serial turns times TTFT plus serial tool time, with perceived latency equal to total because nothing streamed. I attacked both kinds: SSE streaming with tool-progress events for perceived latency; and for actual latency, prompt caching to cut per-turn TTFT, parallel execution of independent tool calls, one-turn batching pressure in the system prompt, per-tool timeouts with degraded results, and a tight output contract (Action). p95 fell from 4.2s to 1.8s, first visible token to ~300ms, abandonment from 14% to 2%, with the eval score and the $0.12 cost per run both unchanged (Result)."
The five follow-ups you will get — and senior answers:
- "Why not just use a faster model?" — We partly did: Scenario #2's tiering put the worker on the mid-tier model, which is also the lower-latency one, and that's where the baseline already stood. Going smaller still failed the eval gate on complex investigations. Model choice is one term in
turns x (TTFT + generation + tools); the structural terms were worth 2x, the model term wasn't. - "How do you parallelize tools without a dependency graph?" — Let the model express the graph: tool calls emitted in the same turn are independent by construction, calls across turns are ordered.
asyncio.gatherwithin a turn captures almost all the win with none of the planner complexity. The system prompt applies the batching pressure. - "Streaming is cosmetic — did anything actually get faster?" — Both matter and we measured both. Actual p95 fell 4.2s to 1.8s from caching, parallelism, fewer turns, and the output contract. Streaming moved first-visible-token from 'the whole run' to ~300ms, and abandonment — the business metric that triggered the incident — tracked perceived latency, not actual.
- "What about hedged requests for tail latency?" — Evaluated, rejected, kept the analysis. Hedging pays roughly double on hedged calls to beat variance, and our p99 tail was loop-shaped — extra turns on hard questions — which hedging doesn't touch but budgets do. Know which tail you have before buying the industry's favorite fix for the other one.
- "How does the soft deadline not produce garbage answers?" — It triggers a conclude-with-caveats instruction, not a truncation: the agent writes its best supported finding and names what it didn't check. Budgeted partials are labeled in the product and ticketed, same discipline as the cost budget. The alternative — silent truncation — is how you fail the eval gate.
Senior signals in this story: you separated perceived from actual latency and fixed both with different tools, you decomposed latency into a structural formula before touching anything, your levers were schedule changes (cache, parallelize, stream) before capability changes, you rejected a fashionable fix (hedging) with a measured argument, and the quality and cost gates from previous incidents constrained this one — the system keeps its own promises.
Pitfalls
- Rendering nothing until the run completes. Perceived latency is a product metric with its own SLO. If your first byte arrives with your last byte, users will call a working agent broken.
- Scaling out to fix serial latency. Instances fix queueing. A single run's critical path doesn't care how many replicas watched it happen. Read the waterfall before the autoscaler config.
- Blanket prompt cuts. Trimming context without an eval gate converts a latency problem into a quality incident with a delay fuse. Surgical reduction is a different discipline — it gets its own war story.
- Letting one slow tool set the pace of the batch. Parallel execution without per-tool timeouts just moves the bottleneck. Bound each call and teach the model to work around a named gap.
- Measuring only averages. The p50 improved 2.6x and would have told a lovely story while 14% of users stared at a spinner at the tail. Latency work lives at p95/p99 and in the abandonment funnel, or it isn't real.
Continue the series
This is Scenario #3 of AI in Production: War Stories:
- Scenario #1: Our AI Support Bot Invented a Refund Policy — RAG Hallucinations From 18% to 3%
- Scenario #2: The Morning Our AI Agent Cost $0.90 Per Run
- Next, Scenario #4: the context window that ate itself — 14k tokens of prompt for questions that needed 3.5k.
The deep-dive question banks this series pairs with:
- Generative AI Interview Questions for Senior Engineers — 55 Deep Answers
- AI Agents Interview Questions — 50 Deep Answers on Agentic Workflows, Multi-Agent & MCP
- Build Reliable AI Agents: Loop, Planning, Tools, Memory, Guardrails
Further reading
- Anthropic's streaming documentation — the event types behind the
answer_deltaloop above - Anthropic's prompt-caching documentation — TTFT is the latency half of the same prefix-stability rules
- Your own tracing stack's waterfall view — latency work starts the day you can see one run as spans
Fighting a spinner of your own? Email me your latency waterfall at randhir.jassal@gmail.com — I read everything.
Get the next issue
A short, curated email with the newest posts and questions.