Cost and latency budgets

Study time
≈ 2 h (estimate)
Needs
L3-M06-L03
Updated
2026-11-05

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M06 · Duration: ~110 minutes (estimate, including the independent exercise) · Previous: L03 (reliability across repeated trials) · Next: L05

1. Introduction

L02 showed that retries save many runs, and L03 measured how many. Both have a price. Every retry of a tool costs extra cost units; every time the model is asked again after a broken output costs extra tokens; every wait for backoff, for Retry-After or for a timeout is time the student spends standing at the desk. A "reliable" agent that takes ten seconds for a question like "is this book available?" is still a broken agent, just broken in a different way.

This lesson turns cost and latency into checkable assertions per task: a budget made of a token cap and a cost cap for each run, and p50 and p95 latency thresholds over the runs of that task. L2-M07-L03 taught why to read percentiles instead of the mean and how to compute a nearest-rank percentile; L3-M04-L04 measured wasted cost against a reference path. Here is the next step: budgets set beforehand, measured on a simulated clock, with an explicitly stated percentile method, and applied under injected faults too.

What the lesson produces: lab/budget.py (percentile with two methods, check_budget, breakdown), the budget table of five tasks under four conditions, and in §9 a set of budgets you set yourself, which both pass the clean run and flag exactly the tasks slowed down by a slow tool.

2. Learning objectives

  1. Distinguish per-run caps (tokens, cost) from percentile thresholds over runs (p50, p95), and state when to use which. Read: §4.1.
  2. Show where the time and cost of an agent run go: model, tools, timeouts, backoff. Read: §4.2. Practice: §8.2 (part C).
  3. Compute p50 and p95 with the nearest-rank method and with NIST's interpolation method, and explain why a report must state the method. Read: §5.1. Practice: §8.2 (parts A, C), §8.3, §9 (TODO 1).
  4. Set a budget per task from a clean run, and check it under faults with check_budget. Read: §5.2, §6.1. Practice: §9 (TODO 2).

3. Prerequisites and tools

  • L2-M07-L03 (the three axes of quality, cost and latency; nearest-rank percentiles), L3-M04-L04 (wasted cost, ticks), L3-M01-L02 (the stop reason budget), and L01-L03 of this module. Code lab code-labs/l3-m06.
  • Keep the meanings apart. A budget in this lesson is a tester's threshold, checked after the runs; it differs from the loop budget of L3-M01-L02, which the agent checks itself during the run in order to stop (reason budget). cu is the lab's fake cost unit (as in L3-M02-L04), not any provider's money. Latency is the time on SimClock from the start to the end of a run.
  • The token counts, cost units and milliseconds are the lab's numbers (formulas in the docstring of lab/agent.py), not the price or speed of any model.

4. Concept explanation

4.1 A budget per task: caps and percentiles

Google's SRE book describes a service level objective (SLO) as a target value for a measured indicator, with the natural form "SLI ≤ target" [R1]. A lab task budget has exactly that form, with four indicators:

Field What it checks Kind
max_tokens tokens (in + out) of each run ≤ cap cap: one run over is over
max_cost cu of each run ≤ cap cap
p50_ms p50 latency of the task's runs ≤ threshold percentile: the typical run
p95_ms p95 latency ≤ threshold percentile: the slow tail

Why is cost a cap while latency is a percentile? A run that uses 3 times the normal tokens is a specific, nameable incident (a loop, a re-ask that never stops); you want to see each such run. Latency always has a tail: the SRE book writes that averaging latency "obscures an important detail", that it is entirely possible for most requests to be fast while a "long tail" is much slower, and that high percentiles such as p99 or p99.9 show a "plausible worst-case" value, while p50 (the median) speaks to the typical case [R1]. A hard cap on latency would go red because of a single run that hit the tail; a p95 threshold says "no more than 5% of runs are slower than this".

This is the lab's choice, not a law. A team may set a p95 for tokens, or a hard cap on the latency of a step with a legal deadline. What must not be dropped is stating the kind of each threshold. Anthropic's article notes that once you have an eval suite, latency, token usage, cost per task and error rates "can be tracked on a static bank of tasks" [R3]: a fixed set of tasks is what makes budgets comparable across versions.

4.2 Where the time and cost of an agent run go

A lab run adds up four kinds of time, recorded in run["waits"] and read with budget.breakdown(run); their sum is exactly latency_ms:

  • model: each model call takes 400 + 4 × output tokens + noise in [0, 300) ms, and 5% of calls add 1800 ms (a seeded slow tail).
  • tool: the time of each tool attempt (fixed per tool, or the delay_ms of a timeout fault).
  • timeout: when an attempt exceeds timeout_ms, the clock advances only timeout_ms (the caller stops waiting).
  • backoff: the waits between attempts, including waits for Retry-After.

Cost has three sources: the cu of each tool attempt (except rate-limited attempts: 0 cu), the input tokens of each model call (the task's prompt, plus 60 tokens for each earlier tool result, plus 40 when it is a re-ask), and the output tokens. A checkable consequence: retrying a tool costs only cu, no model tokens (the test test_retries_and_re_asks_cost_more_than_the_clean_run); asking the model again after a broken output costs a whole model call, so it pushes tokens up noticeably.

Budgets and the retry policy must be read together. The AWS article chooses the timeout from the latency percentile of the downstream service (for example p99.9 for a false-timeout rate of 0.1%) and warns that retries "can amplify the load on a dependent system" [R4]. A timeout_ms of 3000 with four attempts means one operation can take up to 4 × 3000 ms plus backoff; if the task's p95 is 5200 ms, that policy alone can break the budget.

5. Technical deep dive

5.1 percentile: two methods, two numbers

budget.percentile(values, p) uses nearest-rank by default, as in L2-M07-L03: sort, take the value at rank ⌈p/100 × N⌉. The result is always a real observation. p is read exactly as the decimal number written: p99.9 of 1000 values is rank ⌈999⌉ = 999, not 1000 as when computing with the binary float 99.90000000000000568… (the test test_nearest_rank_reads_p_as_the_decimal_written). method="nist" uses the NIST handbook's default method: set p(N+1) = k + d (k an integer, 0 ≤ d < 1), then interpolate Y[k] + d(Y[k+1] − Y[k]) between two sorted values, with both ends clamped to the smallest and largest value [R2]. NIST also says plainly that there is no single interpolation method that everyone accepts as standard, and that every method they list is used in practice [R2].

Part A of the demo shows the difference on ten values: p50 is 2420 (nearest-rank) against 2450.0 (NIST); p90 is 2700 against 4140.0, because p(N+1) = 9.9 sits close to the largest value 4300. Part C, on 20 real runs of t01, gives a p95 of 5530 against 7126.95. Same data, same "p95", a difference of 1597 ms: a report that does not state its method cannot be compared with another report.

One consequence of nearest-rank to remember: with N < 20, ⌈0.95N⌉ = N, so p95 is the largest value (the test test_with_fewer_than_20_values_nearest_rank_p95_is_the_maximum). percentile raises ValueError on an empty list, a value that is not a finite number (including True, NaN, infinity), p outside (0, 100] or an unknown method.

5.2 check_budget: a row per task, problems and warnings

check_budget(runs, budgets) returns three main parts (together with the method and budgets used, so that the L05 report can recompute them) and never raises:

  • rows: for each task that has runs, runs, tokens_max, cost_max, p50, p95 and over, a list of the codes OVER_TOKENS, OVER_COST, OVER_P50, OVER_P95. Equal to the budget is within budget.
  • problems: errors that make the table untrustworthy: BAD_METHOD, NO_RUNS, BAD_RUN (a missing field or a wrong type, for example a latency that is a string; tokens, cost and latency must be finite numbers ≥ 0, so NaN, infinity and negative numbers are caught), RUN_IDENTITY (a run_id that is not <task>-<config>-s<seed>-t<trial>, for example a t01 run labelled t04), UNFINISHED_RUN, DUPLICATE_RUN_ID, NO_BUDGET:<task>, BAD_BUDGET:<task> (not a dict, a missing or extra field, a value that is not a positive integer). An unfinished run is left out of the rows and reported here, not silently counted.
  • warnings: P95_IS_MAX:<task> when the task has fewer than 20 runs (§5.1). A warning is not an error, but it must go into the report.

Part B of the demo runs five tasks, 20 runs per task, under four conditions with data/budgets.json. safe without faults: nothing over. safe with slow_search (15% of search_books calls answer after 2500 ms, still under the 3000 ms timeout, so the caller sees no error at all: classify calls those runs not_observed, and this fault only adds latency): t01 and t04, the two tasks that search, go OVER_P95; p50 does not change (t01) or only edges up (t04, from 2146 to 2194). safe with flaky: nothing over, even though t01's tokens_max rises to 2670 (one model re-ask) against 2130 when clean: the lab's token budget already leaves room for one re-ask. retry_new_key with flaky: nothing over either. The budget does not see duplicate effects; that is L02's job. A green budget table says nothing about correctness.

6. QA perspective

6.1 Set the budget, then let it flag

A procedure for setting a budget per task:

  1. Run clean first. The same configuration, the same seed, no faults, enough runs for p95 to mean something (at least 20 with nearest-rank). Record tokens_max, cost_max, p50, p95 for each task.
  2. Leave headroom with a reason. A factor (the lab uses 1.25 in the exercise) or a specific allowance ("enough for one model re-ask"). Write the reason next to the number. A budget so wide that it never goes red is a budget that does not exist.
  3. Run under known faults and check that the budget flags exactly the affected tasks, and only those. Part B (slow_search) is an example: the two tasks that search are red at p95, the other three are green.
  4. Do not loosen the budget after seeing the results. Loosening is a human decision, recorded, like changing a threshold in L2-M07-L04.

Three things a budget does not tell you. It does not say the run was correct (an agent that does nothing is cheap and fast; L3-M04-L04 gave the same warning for efficiency). It does not say anything about load: the lab runs one run at a time, with no queue, so the "queuing effects" that make the tail heavier under high load, which the SRE book mentions [R1], are not present here. And for latency, the simulated clock only knows what the lab's latency model tells it; the real latency of a model depends on many things the lab does not simulate.

7. Real-world scenarios

Scenario 1 (fictional): "p95 got better after we changed dashboards". After a switch of monitoring tool, the assistant's p95 drops by 20% without anyone fixing anything. The tester reads the documentation of the two tools: the old tool uses nearest-rank, the new one interpolates. On the same exported data, the two methods give two numbers, as in part C of the demo. From then on, the report states the method next to every percentile.

Scenario 2 (fictional): "Retries broke the budget". A fix adds retries to send_notice with a 3000 ms timeout and four attempts. Errors go down, but the p95 of the "return a book and notify" task goes over budget on days when the notification service is slow. The tester splits the latency with breakdown and sees that most of it is timeout: the client waits the full 3000 ms on every attempt. The team lowers the timeout for that tool based on its own measured p99.9, the way the AWS article describes [R4], and then reruns the table.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m06
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 145 passed

8.2 Run the demo

python -m lab.demo l04

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; both versions gave identical output). Every run is simulated:

A. ten latencies (ms): [2100, 2250, 2310, 2400, 2420, 2480, 2550, 2600, 2700, 4300]
   p50: nearest_rank=2420 nist=2450.0
   p90: nearest_rank=2700 nist=4140.0
   p95: nearest_rank=4300 nist=4300
B. budgets (data/budgets.json): {'max_tokens': 2800, 'max_cost': 44, 'p50_ms': 3300, 'p95_ms': 5200} ... five tasks
   safe / none: problems=[] warnings=[]
      t01: tokens_max=2130 cost_max=30 p50=2975 p95=4697 over=[]
      t02: tokens_max=1390 cost_max=22 p50=2304 p95=4110 over=[]
      t03: tokens_max=1600 cost_max=24 p50=2314 p95=3878 over=[]
      t04: tokens_max=1330 cost_max=18 p50=2146 p95=4105 over=[]
      t05: tokens_max=1660 cost_max=25 p50=2392 p95=2752 over=[]
   safe / slow_search: problems=[] warnings=[]
      t01: tokens_max=2130 cost_max=30 p50=2975 p95=5530 over=['OVER_P95']
      t02: tokens_max=1390 cost_max=22 p50=2304 p95=4110 over=[]
      t03: tokens_max=1600 cost_max=24 p50=2314 p95=3878 over=[]
      t04: tokens_max=1330 cost_max=18 p50=2194 p95=4485 over=['OVER_P95']
      t05: tokens_max=1660 cost_max=25 p50=2392 p95=2752 over=[]
   safe / flaky: problems=[] warnings=[]
      t01: tokens_max=2670 cost_max=42 p50=3053 p95=4697 over=[]
      t02: tokens_max=1890 cost_max=29 p50=2442 p95=4110 over=[]
      t03: tokens_max=2170 cost_max=36 p50=2420 p95=3878 over=[]
      t04: tokens_max=1810 cost_max=24 p50=2194 p95=4105 over=[]
      t05: tokens_max=2250 cost_max=38 p50=2604 p95=3978 over=[]
   retry_new_key / flaky: problems=[] warnings=[]
      t01: tokens_max=2130 cost_max=33 p50=2975 p95=4697 over=[]
      t02: tokens_max=1390 cost_max=24 p50=2391 p95=4110 over=[]
      t03: tokens_max=1600 cost_max=27 p50=2414 p95=3878 over=[]
      t04: tokens_max=1330 cost_max=18 p50=2146 p95=4105 over=[]
      t05: tokens_max=1660 cost_max=28 p50=2667 p95=3202 over=[]
C. t01 under slow_search, 20 runs: p95 nearest_rank=5530 nist=7126.95
   t01-safe-s0-t13: latency=7211 breakdown={'model': 4381, 'tool': 2830, 'timeout': 0, 'backoff': 0} slow searches=1
   t01-safe-s0-t9: latency=5530 breakdown={'model': 2700, 'tool': 2830, 'timeout': 0, 'backoff': 0} slow searches=1
   t01-safe-s0-t11: latency=4697 breakdown={'model': 4247, 'tool': 450, 'timeout': 0, 'backoff': 0} slow searches=0
D. only 10 runs of t01: p95=5530 (the largest of the 10) warnings=['P95_IS_MAX:t01']
E. malformed input: unfinished run ['UNFINISHED_RUN']; no budget for t01 ['NO_BUDGET:t01']; budget as a string ['BAD_BUDGET:t01']

Reading the output: parts A and C: §5.1. Part B: §5.2; the first line prints t01's budget as a sample. Part C also lists the three slowest runs of t01 under slow_search: the first two have exactly one slow search (tool 2830 ms = 2500 for the slow search + 80 + 250), the third has none and is still slow because of the model (model 4247 ms: the model's slow tail). Not every slow run is caused by the fault you injected. Part D: with only 10 runs, p95 is the slowest run, and the warning P95_IS_MAX:t01 says so. Part E: three kinds of malformed input, one code each, no exception.

8.3 Try it yourself

Save this as try_l04.py in the lab's root folder, run python try_l04.py, then delete the file:

from lab import budget as B, data, trials as T

lat = [900, 950, 980, 1000, 1010, 1040, 1100, 1150, 1200, 1300, 1450, 1600, 2100, 3900, 4000]
print([B.percentile(lat, p) for p in (50, 90, 95)], [B.percentile(lat, p, "nist") for p in (50, 90, 95)])
runs = T.run_trials(["t04"], "safe", 20, seed=5, plan=data.plan("slow_search"))["runs"]
budget = {"t04": {"max_tokens": 1400, "max_cost": 20, "p50_ms": 2300, "p95_ms": 3600}}
print(B.check_budget(runs, budget))

Output (Python 3.14.6 and 3.12.3, Linux, identical):

[1150, 3900, 4000] [1150.0, 3940.0, 4000]
{'rows': {'t04': {'runs': 20, 'tokens_max': 1330, 'cost_max': 18, 'p50': 2175, 'p95': 6299, 'over': ['OVER_P95']}}, 'problems': [], 'warnings': [], 'method': 'nearest_rank', 'budgets': {'t04': {'max_tokens': 1400, 'max_cost': 20, 'p50_ms': 2300, 'p95_ms': 3600}}}

Reading: line 1: fifteen latencies; with nearest-rank, p90 is rank ⌈13.5⌉ = 14 (3900) and p95 is rank 15 (4000, the largest value); NIST interpolates p90 to 3940.0. Line 2: t04 under slow_search with seed 5 and a budget of your own: p95 6299 is over 3600, while tokens, cost and p50 are within budget; no problems, no warnings (20 runs); the last two fields record the method and the budgets used.

8.4 Run the lesson's tests

python -m pytest tests/test_l04_budgets.py -v

Result: 26 passed. Read test_nearest_rank_is_always_an_observed_value_and_matches_its_definition, test_budget_table_of_the_lesson and test_latency_is_the_sum_of_model_tool_timeout_and_backoff.

8.5 Troubleshooting

Symptom Cause Fix
problems contains NO_BUDGET:t0x A task's runs have no budget Add a budget for every task that has runs
BAD_BUDGET although the numbers look right A value is a string, a float, 0, or there is an unknown field such as p99_ms Exactly four fields, positive integers
BAD_RUN with a numeric latency NaN, infinity or a negative number (for example read from JSON containing NaN) Fix the data source; do not filter silently
p95 equals the slowest run Fewer than 20 runs (P95_IS_MAX) Run enough times, chosen beforehand
p95 differs from another tool's number A different percentile method State the method; compare with the same method

9. Independent exercise

Problem: The configuration safe, seed 3, 20 runs per task (exercises/ex_budget_l04.json). The exercise's fault plan makes borrow_book answer after 3500 ms on 20% of calls (still writing), that is, past the client's 3000 ms timeout.

Requirements: complete exercises/test_l04_budgets.py:

  1. TODO 1: P50_P95: the nearest-rank (p50, p95) of the five tasks under that fault plan.
  2. TODO 2: BUDGETS: budgets for the five tasks such that (a) the same runs without faults pass every budget; (b) under the fault plan, check_budget flags exactly OVER_P95 for t01, t03, t05 and nothing else; (c) no field exceeds 1.25 times the value measured in the clean run (rounded up). data/budgets.json does not satisfy (c).

Test data: exercises/ex_budget_l04.json.

Deliverable: the two variables above, in the file exercises/test_l04_budgets.py itself.

Acceptance criteria: python -m pytest exercises/test_l04_budgets.py passes (2 tests).

Hints: run both conditions and print check_budget(...)["rows"] for each before setting any number. For each field, the budget must lie between the clean value and the value under faults (when it needs to flag) or above both (when it does not). Think about which field other than latency a retry after a timeout increases.

10. Knowledge check

0/10 done · Results are kept in this browser only.

P02 · True or false

With the nearest-rank method, the p95 of 12 runs is always the slowest run.

P03 · Fill in the blank

A lab run has waits = {"model": 2210, "tool": 3080, "timeout": 3000, "backoff": 412}; its latency is ___ ms. A rate-limited attempt costs ___ cu.

P04 · Select all that apply

Select everything that increases the cost (cu or tokens) of a run in the lab.

P05 · Put in order

Put the procedure for setting and checking a budget per task in order.

  1. Run clean enough times (at least 20) with the chosen configuration and seed
  2. Run under a known fault and check that exactly the affected tasks are flagged
  3. Record tokens_max, cost_max, p50, p95 and the percentile method for each task
  4. Set the budget with headroom and a written reason
  5. Put the budget table and every warning into the report, without loosening numbers after looking

P06 · Match

Match each entry in the result of check_budget to its meaning.

P07 · Spot the bug

This percentile function is used for p95 on a dashboard. Find the bug.

def p95(values):
    ys = sorted(values)
    return ys[int(0.95 * len(ys)) - 1]

P08 · Essay

Two reports of the same agent, on the same data, give p95 values 1597 ms apart. Write three to five sentences explaining how this can happen and what a report should record to avoid it.

P10 · Recall

Lesson: L2-M07-L03

According to L2-M07-L03, with ten latencies whose mean is 318.5 ms, why does the lesson read p50 and p95 instead of the mean?

11. Summary

  • Concepts: per-task budgets of the form "indicator ≤ target" [R1]; per-run caps and percentiles over runs; percentiles instead of the mean because of the tail [R1]; two percentile methods give two numbers [R2]; tracking on a fixed set of tasks [R3]; timeouts and retries affect latency [R4].
  • Skills: split latency into model, tools, timeouts, backoff; set budgets from a clean run with headroom; check that a budget flags exactly the right tasks under faults.
  • Traps: not stating the percentile method; the p95 of fewer than 20 runs; a budget so wide it never goes red; loosening a budget after looking; treating a green budget table as evidence of correctness.
  • You can now: write cost and latency assertions for each task of an agent, and say where the time of a slow run went.

12. References

ID Title Publisher URL Accessed Relevance
R1 Service Level Objectives (Site Reliability Engineering, ch. 4) Google https://sre.google/sre-book/service-level-objectives/ 2026-11-05 SLOs of the form SLI ≤ target; the mean hides the tail; high percentiles and the median; queuing effects
R2 NIST/SEMATECH e-Handbook of Statistical Methods, §7.2.6.2 Percentiles NIST https://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm 2026-11-05 Definition of a percentile; estimate at p(N+1) with interpolation; no single standard interpolation method
R3 Demystifying evals for AI agents Anthropic https://www.anthropic.com/research/demystifying-evals-for-ai-agents 2026-11-05 Latency, tokens, cost per task and error rates tracked on a fixed set of tasks
R4 Timeouts, retries, and backoff with jitter Amazon Builders' Library (AWS Builder Center) https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/ 2026-11-05 Choosing timeouts from downstream latency percentiles; retries amplify load

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
Task budget Ngân sách tác vụ: trần token và chi phí mỗi lần chạy, ngưỡng p50 và p95 độ trễ; ngưỡng của tester, khác ngân sách vòng lặp của L3-M01-L02
Hard cap / percentile threshold Trần (một lần chạy vượt là vượt) / ngưỡng phân vị (trên các lần chạy)
Percentile method (nearest-rank / interpolated) Phương pháp phân vị (hạng gần nhất / nội suy kiểu NIST tại p(N+1))
Latency breakdown Tách độ trễ: model, tool, timeout, backoff
Headroom Khoảng chừa: phần ngân sách trên giá trị đo được, có ghi lý do