AI in Production: War Stories — Scenario #3. One real 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.

Canonical: the full version lives on PrepStack.

The incident

This alert didn't come from finance. It came from product analytics: 14% of our AI copilot's runs ended with the user closing the panel before the answer arrived. They'd ask "why did conversions dip in EMEA last week?", stare at a spinner, and leave.

p95 time-to-answer was 4.2s. But the stat that explained the abandonment: time-to-first-visible-anything was identical to time-to-answer, because we rendered nothing until the whole run finished. Perceived latency equalled total latency, every run.

A feature can survive being slow. It cannot survive looking dead.

Where the seconds went

Five turns of ~800ms each. No single component was scandalous — it was the shape:

  • L1 — Dead air. Nothing rendered until the entire run finished. Perceived == total.
  • L2 — Serial tools. One tool call per turn, every turn serial. Independent tools still ran one after another.
  • L3 — Cold prefix. TTFT ~450ms per turn: the prompt prefix was re-processed from scratch every call.
  • L4 — Blocking loop. Model waits on tool, tool waits on model, nothing overlaps.
  • L5 — Verbose finale. The final answer was generated at full verbosity with no output contract — a quarter of the run spent typing.

Triage: the dead ends

  1. "More instances." p95 moved ~50ms. This was serial time inside each run, not queueing in front of runs. Scaling out fixes contention; we had none.
  2. "Move closer to the model." ~40ms/call. Across five turns, 200ms — real but nowhere near the seconds we needed. Network wasn't the story.
  3. "Shorten the prompt." A blanket cut dropped eval 0.92 → 0.88, below our 0.90 floor, because the agent started skipping the segment-comparison step the deleted rules enforced. Reverted. Context reduction is surgery, not a haircut.
  4. Span timing — the real signal. We rendered a few hundred runs as waterfalls. At p95: ~58% model time across serial turns, ~22% serial tool time, ~20% final-answer generation. And time-to-first-rendered-byte was 100% of total, because we streamed nothing.

Root cause, plainly: answer latency = serial turns × (TTFT + generation + tool time), and perceived latency = time until the user sees signs of life — and we were maximizing both.

The broken run — a POC you can feel

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. def run(question, tools, execute_tool): 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': return next(b.text for b in response.content if b.type=='text') # [L1] 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}) messages.append({'role':'user','content':results}) 

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, two different budgets: actual latency (serial turns, serial tools, cold prefixes, verbose output) and perceived latency (dead air).

# fast_agent.py - the production loop (abridged). Python 3.11+ client = anthropic.AsyncAnthropic(max_retries=2, timeout=30.0) 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 async def run(question, run_id, execute_tool, tools): messages = [{'role':'user','content':question}] wrap_up_sent = False while True: # Streaming + a byte-stable cached prefix: the two TTFT levers. async with client.messages.stream( model='claude-sonnet-5-5', 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': yield {'event':'answer_delta','text':event.delta.text} response = await stream.get_final_message() messages.append({'role':'assistant','content':response.content}) if response.stop_reason != 'tool_use': yield {'event':'done'}; 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 calls from one turn run concurrently. results = await asyncio.gather( *(run_tool(execute_tool, b) for b in tool_blocks)) messages.append({'role':'user','content':list(results)}) if (elapsed() > SOFT_DEADLINE_S) and not wrap_up_sent: messages.append({'role':'system','content':WRAP_UP}) wrap_up_sent = True 

The decisions that matter:

  • Streaming is a UX decision enforced in the transport. The loop is an async generator yielding answer_delta and tool_started events over SSE. 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.gather runs them concurrently. Three 130ms lookups cost ~140ms, not ~390ms. No dependency planner — the model signals independence by emitting multiple tool calls in a turn.
  • The cache lever was already paid for. A byte-stable system+tools prefix (adopted for cost) is also the TTFT fix: a cache hit skips re-processing the 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 — not a silent truncation. Hard caps still exist underneath.
  • 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

# Case Symptom in telemetry Control
1 Dead air time-to-first-byte == total run time Stream deltas + tool-progress over SSE
2 Cache-miss TTFT bleed TTFT high every turn; cache_read_input_tokens ~0 Byte-stable system/tool prefix
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 as intents
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 guardrails held

  • Quality (0.90 eval floor): streaming, parallelism and caching are quality-neutral by construction — same tokens, same answers, different schedule. The output contract held at 0.92 (tight findings scored as well as essays). The blanket prompt cut 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 and rejected it: it buys tail latency by roughly doubling spend, and our tail was loop-shaped, not variance-shaped. Cost per run stayed at $0.12.

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, 3-lookup turn ~390ms ~140ms
Model turns per run (p50) 5 3
Runs abandoned before answer 14% 2%
Eval score (0.90 floor) 0.92 0.92
Cost per run $0.12 $0.12

In the interview

Five follow-ups you'll get:

  1. "Why not a faster model?" — We partly did: tiering put the worker on the mid-tier (also lower-latency) model. Going smaller failed the eval gate. Model choice is one term in turns × (TTFT + generation + tools); the structural terms were worth 2x.
  2. "Parallelize without a dependency graph?" — Let the model express it: calls in the same turn are independent, calls across turns are ordered. asyncio.gather within a turn captures the win with none of the planner complexity.
  3. "Streaming is cosmetic — did anything get faster?" — Both, measured. Actual p95 4.2→1.8s from caching, parallelism, fewer turns, output contract. Streaming moved first-visible-token to ~300ms — and abandonment tracked perceived latency.
  4. "Hedged requests for tail latency?" — Evaluated, rejected. Hedging pays ~double to beat variance; our tail was loop-shaped, which budgets fix and hedging doesn't.
  5. "How does the soft deadline not produce garbage?" — It triggers conclude-with-caveats, not truncation. Budgeted partials are labeled and ticketed.

Pitfalls

  • Rendering nothing until the run completes. Perceived latency is a product metric with its own SLO.
  • Scaling out to fix serial latency. Instances fix queueing. A single run's critical path doesn't care how many replicas watched it happen.
  • Blanket prompt cuts. Trimming context without an eval gate converts a latency problem into a quality incident with a delay fuse.
  • Letting one slow tool set the pace of the batch. Parallel execution without per-tool timeouts just moves the bottleneck.
  • Measuring only averages. Latency work lives at p95/p99 and in the abandonment funnel, or it isn't real.

This is a condensed version. The full playbook — the complete runnable loop, the OpenTelemetry span accounting, every code block, and the senior-interview STAR version — is on PrepStack:

→ Users Were Abandoning Our AI Copilot at p95 4.2s — the Streaming Fix That Took It to 1.8s

Part of the AI in Production: War Stories series — #1 RAG hallucinations · #2 the $0.90-per-run bill.