# How Do You Track Latency and Cost in Evals?

> How to log speed, tokens and cost for every eval case, compare p95 and cost per passed case, and count the judge's bill apart, for your AI interview.

**In short:** Log the time and the tokens for every case in an eval run, next to the pass or fail. Turn tokens into cost with a dated price table, then compare the slow end (p95) and the cost per passed case between versions.

AI and LLM interview question Q272, Evaluation and observability. Intermediate, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-track-latency-and-cost-in-evals

## Say it in 30 seconds

I log time and tokens for every eval case, on the same row as the pass or fail. Tokens become cost through a dated price table. I compare versions on the median, the p95 and cost per passed case. The judge model's bill is counted apart. A change that wins a point but breaks the cost budget goes to review.

## Say it in 2 minutes

Every eval run should answer three questions: did the answer pass, how long did the user wait, and what did it cost. Quality is only half the score. An agent that passes 95 percent of cases but takes twenty seconds and costs five times as much is a different product. So I log the numbers for each case as the run happens: time to first token, total time, input, cache-write, cached and output tokens, and the number of calls and retries.

Tokens turn into cost through a price table. I keep the table dated and in config, because a stale price quietly ruins a comparison. The judge model that grades the answers has its own tokens and its own bill, so I count it separately. That way a cheap agent with an expensive grader does not look cheap. Cache writes and cached input get their own counts too, since a rerun often reads the cache and looks cheaper than the first run.

Then I compare versions on summaries, never single runs. I look at the median and the 95th percentile, because the median hides the slow tail users notice. I divide total cost by the passed cases, so a version that fails more pays for its failures. I set a gate: a change that lifts quality but breaks the latency or cost budget goes to review. And I say clearly that timings from my own test harness are a guide to production speed, because a harness that runs cases in parallel can queue them.

## What does tracking latency and cost in evals mean, in plain words?

An eval is a fixed set of test cases that you run against your AI app, so you can see how it behaves before users do. Tracking latency and cost means writing down, for every case, how long the answer took and how many tokens it used. Then you add those numbers up next to the pass or fail. Tokens are the small pieces of text a model reads and writes, and providers usually bill by them.

OpenAI's guide defines the term in one line: "Evaluations (often called evals) test model outputs to ensure they meet style and content criteria that you specify." That covers quality. Latency and cost are the two other questions a real team asks about the same run.

Think of a claims desk manager. She checks each decision for accuracy, but she also times each claim and counts the forms it used. A correct decision that takes forty minutes and three reprints costs the insurer money and the customer patience. An AI agent that triages insurance claims faces the same test: it has to be right, fast enough, and affordable at the volume the insurer really sends.

- **Latency:** How long the user waits, from asking to getting the full answer.
- **Time to first token:** How long until the first word appears. It decides how fast a reply feels.
- **Token:** A small piece of text, a few letters or a word, counted on the way in and out.
- **p95:** The time that 95 out of 100 cases beat. It shows the slow tail.
- **Judge model:** A second model that grades the answers, and uses tokens too.

## What should each eval case record?

Write the numbers down on the same row as the pass or fail. If you keep only the final score, you cannot later say why a version got slower or dearer. Each row needs the time to first token, the total time, and the input, cache-write, cached and output token counts. Also count the model calls and retries, since one case that retries three times costs three times as much.

> "Once evals exist, you get baselines and regression tests for free: latency, token usage, cost per task, and error rates can be tracked on a static bank of tasks." (Anthropic, on agent evals)
>
> "Record input, cached input, and output tokens alongside the timings." (OpenAI, latency guide)

Keep the two kinds of time apart. Total time is the full wait a user sees. Time to first token is how long until text starts to appear. A streamed reply can feel quick with a fast first word and still be slow overall, so log both.

*Diagram, What one eval case records: Each case runs the agent, and the run is timed and counted as it happens, retries included. The row it leaves behind feeds the report that compares versions.*
1. Each case goes to the agent with its right answer kept aside.
2. The run is timed and counted as it happens.
3. Every row feeds the report, so versions compare fairly.

## How do you turn tokens into cost?

Cost is simple arithmetic: tokens times the price of each kind, added up. The hard part is keeping the prices right. Keep the price table in config with a date on it, and update it when a provider changes prices. Otherwise two runs look different when only the price changed.

Caching changes the sums, and it cuts both ways. Anthropic's prompt caching page says: "Cache write tokens with a 5-minute TTL are 1.25 times the base input tokens price." Reads are the good side: "Cache reads cost significantly less than uncached input tokens, so reaching the minimum can reduce costs for frequently reused prompts." An eval suite that repeats the same long instructions shows a lower bill on the second run. Log cache writes and cached tokens so you can explain that drop instead of blaming the new prompt.

Anthropic's usage and cost reports list cost reconciliation as a use: matching your records with billing, for finance teams. They group usage into fixed time buckets, so use them to check totals, not single eval cases.

*Diagram, How tokens become cost: Each kind of token has its own rate in one dated table. Tokens from the run are multiplied by their rate and added up to give the cost of one case.*
1. Input tokens are priced at the input rate.
2. Cache writes are billed above the input rate.
3. Cached input uses its own lower rate from the same table.
4. Output tokens use the output rate from the same table.
5. Each kind of token times its rate, added up, gives the cost of the case.

## What does a small eval report look like?

Here is a made-up run of 20 cases from a claims triage agent, which sorts incoming insurance claims. The prices are made up too. The data is fixed, so the output is the same every time the script runs.

```python
# Made-up eval run: 20 cases from a claims triage agent. Prices are made up too.
PRICE_IN = 2.00   # USD per million input tokens (made up)
PRICE_OUT = 8.00  # USD per million output tokens (made up)
JUDGE_IN, JUDGE_OUT = 1500, 60  # the judge model's tokens per case, counted apart

def nearest_rank(values, p):
    # Nearest rank: the smallest value that at least p% of the cases reach.
    ordered = sorted(values)
    k = -(-len(ordered) * p // 100)  # ceiling of n * p / 100
    return ordered[k - 1]
runs = []
for i in range(20):
    passed = i % 5 != 0  # 16 of 20 pass
    inp = 3000 + (i * 211) % 900
    out = 150 + (i * 37) % 120
    ms = 1500 + (i * 137) % 2000 + (4000 if i in (2, 9, 15) else 0)  # three slow runs
    runs.append((passed, inp, out, ms))

def cost(inp, out):
    return (inp * PRICE_IN + out * PRICE_OUT) / 1_000_000

agent_cost = sum(cost(inp, out) for _, inp, out, _ in runs)
judge_cost = len(runs) * cost(JUDGE_IN, JUDGE_OUT)
passed = sum(1 for r in runs if r[0])
latency = [r[3] for r in runs]

print("cases:", len(runs), "passed:", passed)
print("p50 ms:", nearest_rank(latency, 50), "p95 ms:", nearest_rank(latency, 95))
print(f"agent cost: ${agent_cost:.4f}, judge cost: ${judge_cost:.4f}")
print(f"cost per passed case: ${(agent_cost + judge_cost) / passed:.4f}")
```

Output:

```text
cases: 20 passed: 16
p50 ms: 2322 p95 ms: 5774
agent cost: $0.1704, judge cost: $0.0696
cost per passed case: $0.0150
```

Read the report from the bottom. The judge's bill is more than a third of the agent's bill, and it is easy to forget a grader's spend. The median is 2322 ms, but the p95 is 5774 ms, more than twice as slow. The number to compare between versions is cost per passed case, because it counts the failures too.

## Which numbers do you compare between versions?

Compare versions on summaries, never on a single run. Use the median and the 95th percentile, because an average hides the slow tail. OpenAI's latency guide says it plainly:

> "Compare the median (p50) and the 95th percentile (p95) on representative traffic." (OpenAI, latency guide)

p95 is the time that 95 out of 100 cases beat, so one case in twenty is slower than it. Cost per passed case divides the whole bill by the number of passes. A version that fails more pays for its failures there, while total cost alone can look fine when the new version simply does less work.

Be honest about what timings mean. A harness that runs cases in parallel can queue them, so its timings may not match what a user sees. Treat offline timings as a guide, and measure real speed from live traffic.

> **Tip:** Turn the numbers into a gate. Set a budget for p95 latency and cost per passed case, and fail the run when a change breaks it.

### How would you stop a prompt change that raises the bill?

A teammate adds eight worked examples to the triage prompt. On a 300-case suite, quality rises from 91 to 93 percent. The cost per passed case rises by about 60 percent, and the p95 latency goes up by 900 milliseconds. Made-up numbers, for practice.

- **Quality only: Ship it.** Two more points look good on the scorecard. Nobody checked the bill or the wait.
- **With a gate: Hold for review.** The budget fails the run. The team asks whether two points are worth 60 percent more per pass.

Prompt caching may cut the cost of the repeated examples. Rerun the suite with caching on, log the cached tokens, and decide with both numbers in front of you.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Log time, tokens and pass or fail for every case, on the same row.
- [ ] Turn tokens into cost with a dated price table, and count the judge model apart.
- [ ] Compare p50 and p95, never one average.
- [ ] Use cost per passed case, so failures cost something on the scorecard.
- [ ] Gate releases on the budget, and measure production speed from live traffic.

**Common traps**

- Trap: "We only track accuracy; speed and cost are someone else's problem." Better: Quality and cost move together. Log both on the same row, so the bill is never a surprise.
- Trap: "The average latency is fine." Better: An average blends the slow cases into the rest. Report the median and p95 instead.
- Trap: "The provider bill tells me everything." Better: A provider bill shows totals, not which case or which change caused them. Log tokens per case so you can see which change moved it.

## Can you spot the problem?

**Spot the weak tracking:** Which line is the weakest way to report speed in an eval?

A. avg_latency_ms = sum(latency) / len(latency)
B. p95_ms = nearest_rank(latency, 95)
C. ttft_ms = first_token_at - started_at
D. row = {passed, tokens_in, tokens_written, tokens_cached, tokens_out, ms}

**Answer:** A. A mean blends a few very slow cases into the rest, so the slow tail disappears from view. Report the median and p95 instead, so one slow case in twenty shows up.

**Quick check:** A prompt change lifts quality by one point and raises cost per passed case by half. What should happen next?

A. Ship it, since quality went up.
B. Hold it for review against the cost budget, and ask whether the point is worth the money.
C. Count the judge's tokens as zero, then ship.
D. Wait a month and average the cost before deciding.

**Answer:** B. Quality and cost move together, so the budget decides. Dropping the judge's tokens or averaging over a month hides the rise, and one point of quality says nothing about the bill.

## Can you answer these from memory?

**Flash cards**

- **What is p95?** The time that 95 out of 100 cases beat. It shows the slow tail.
- **What must each eval row log?** Pass or fail, time to first token, total time, and input, cache-write, cached and output tokens.
- **Why keep the judge's tokens apart?** A cheap agent with an expensive grader can look cheap. Separate counts show the real bill.
- **Why use cost per passed case?** It counts the failures too. A version that fails more pays for them.
- **Why are offline timings not production?** Parallel runs can add waiting time. Measure real speed from live traffic.
- **What makes a release gate?** A budget for p95 and cost per passed case. The run fails when a change breaks it.

## Likely follow-up questions

- Q273 Which guardrail metrics should you track? https://designervenkat.online/interview/ai/which-guardrail-metrics-should-you-track
- Q274 What eval and observability tools exist? https://designervenkat.online/interview/ai/what-eval-and-observability-tools-exist
- Q316 TTFT vs tokens/sec vs total latency? https://designervenkat.online/interview/ai/ttft-vs-tokens-per-second-vs-latency
- Q324 How do you estimate token cost for a feature? https://designervenkat.online/interview/ai/how-to-estimate-token-cost
- Q344 What is a p95/p99 latency budget? https://designervenkat.online/interview/ai/what-is-a-p95-p99-latency-budget
- Q190 How do you trace and debug an agent run? https://designervenkat.online/interview/ai/how-do-you-trace-and-debug-an-agent-run

## Learn it in depth

- [Watching cost and speed](https://designervenkat.online/learn/ai-engineering/cost-latency-monitoring)
- [Seeing inside your AI app](https://designervenkat.online/learn/ai-engineering/llm-observability)
