Cruxly › AI engineering › Agentic Systems
Agent Cost and Latency Budgets: Making a Loop Affordable
the cost of a loop hides in re-sent context, retries and big tool outputs, and the right stop returns a partial result
Open the interactive lessonPrompt: "Our research agent averages 8 steps per task and the finance team says it costs too much and takes too long. Product wants it faster and cheaper without getting worse. How do you set a budget, find where the money goes, and bring the cost down?"
30 minutes first. Pick one made-up price list and use it consistently on the whiteboard. The point is the method, so say out loud that the prices are illustrative.
Set the budget first: tokens, dollars and a latency target per step
A budget is a number the loop can check, not a hope. Without one, the only feedback is the monthly invoice, which arrives after the money is spent. Three budgets, each enforced in code:
- A token budget per task. For example 100,000 input plus 10,000 output tokens. It is a count the loop can keep exactly, because the API reports usage on every response.
- A dollar budget per task. The token budget turned into money using the current price list, so you can compare with what the task is worth. If a task saves a person 10 minutes (worth, say, Rs 100) it cannot cost Rs 80.
- A latency budget per step, and per task. For example 8 seconds per step and 90 seconds per task. A user waiting for an answer has a patience limit that is not the same as your token limit.
Where the numbers come from: work backwards from value. What is a successful task worth, what share of that are you willing to spend, and what does a typical run cost today? Set the hard cap well above the typical run (for example 3x the median) so it catches runaways without cutting normal work, and set a soft threshold lower (for example 80 percent of the cap) that triggers the wrap-up behaviour described later.
Use one made-up price list for every calculation. Real prices differ by vendor, model and date, so do not quote them from memory in an interview. Say "for example" and pick round numbers. This lesson uses these:
| Model | Input per 1M tokens | Output per 1M tokens | Cached input read per 1M |
|---|---|---|---|
| Large model (example) | $3.00 | $15.00 | $0.30 |
| Small model (example) | $0.30 | $1.50 | $0.03 |
Output tokens cost more than input tokens and are also slower, because they are generated one at a time. So a rambling chain of thought or a long final answer costs in both dollars and seconds, which is why "be concise, return only the fields" is a budget instruction as well as a style one.
Spread the budget across the run, not just the total. A step budget alone lets step 1 spend everything, and a total alone hides one step eating most of it. Track both the running total and the largest single step so you can see which step is the offender.
A worked example: where the cost hides
Take one task and price it, using the example prices from the table. The agent has a 4,000-token stable prefix (system prompt and tool definitions). Each step adds 1,500 tokens to the transcript (a tool result plus the model's message), and the model writes 300 output tokens per step. The run takes 8 steps.
Step k sends 4,000 + 1,500 x (k - 1) input tokens. Summed over 8 steps:
input = 8 x 4,000 + 1,500 x (0+1+2+3+4+5+6+7) = 32,000 + 42,000 = 74,000 tokens
output = 8 x 300 = 2,400 tokens
cost = 74,000 x $3 / 1M + 2,400 x $15 / 1M
= $0.222 + $0.036 = $0.258 per run
Notice what dominates: 86 percent of the cost is input, and most of the input is old content being sent again. The model wrote only 2,400 tokens in the whole run. That is the first lesson: the bill is mostly context, not answers, so squeezing the answers barely helps.
Now see the four places the cost hides, each with a number.
| Hidden cost | Illustration | Effect on the $0.258 run |
|---|---|---|
| Large tool output | At step 3 a tool returns a 20,000-token page that stays in the transcript. It is re-sent in steps 4 to 8 | 5 x 20,000 = 100,000 extra input tokens, about +$0.30, more than doubling the run |
| Retries | 15 percent of steps need one retry (a failed call plus a repeat) | roughly +15 percent, about +$0.04, and more time |
| Reflection loop | A critique pass plus a rewrite after every step: about 600 extra output tokens per step and a longer input | Output cost goes up roughly 3x, input grows with the critique text, so perhaps +$0.10 to +$0.15 |
| Re-sent context | Every step carries every earlier step | Already the 86 percent above, and it is quadratic in steps |
The 20,000-token tool result is the one to remember: a single un-capped output was bigger than everything else in the run. The cheapest control is at the tool boundary. Truncate or page the output (return the first 2,000 tokens plus "3 more pages available"), return only the fields asked for, and trim it from the transcript once used, as described in Context Engineering for Long-Horizon Agents.
:::warn Reflection is not free Critique-and-revise loops buy quality and cost output tokens, latency, and extra input on every later step. Add one only where a measured quality gain pays for it, and cap it at one round unless a test or a validator says another round is needed. :::
Levers: route to a smaller model, cache the prefix, cap what comes in
Three levers, each with a number from the same example.
1. Route easy steps to a smaller model. Not every step needs the strongest model. Classifying the ticket, extracting fields, formatting the final answer and choosing between two known tools are easy. Planning and judgement calls are not. A router (a rule in code or a cheap classifier call) sends each step to the cheaper model when it can.
Suppose 5 of the 8 steps are easy and carry about their share of the tokens (5/8). The small model costs a tenth of the large one in the example. Then the cost is about $0.258 x (3/8 + 5/8 x 0.1) = $0.258 x 0.4375, about $0.11, less than half. The catch is quality: the small model errs more, so measure task success after routing, since an extra retry or a wrong answer can erase the saving. Start with the steps where errors are cheap to detect.
2. Cache the stable prefix. Many APIs let you mark a repeated prefix so later requests read it at a fraction of the input price. In the example a cached read is a tenth of the input price.
- Cache only the 4,000-token system prefix: 32,000 of the 74,000 input tokens become cache reads. Input cost becomes
42,000 x $3/1M + 32,000 x $0.30/1M = $0.126 + $0.0096 = $0.136, so the run costs about $0.17, ignoring any one-time write surcharge. - Cache the whole append-only transcript too: each step's earlier tokens are a prefix of the next request, so only the newest 1,500 tokens (and the first 4,000) are billed at the full rate. That is 14,500 full-price tokens and 59,500 cached reads:
14,500 x $3/1M + 59,500 x $0.30/1M = $0.0435 + $0.0179 = $0.0614of input, so about $0.10 per run.
The condition is that the prefix stays byte-identical. Put the stable things first (instructions, tool definitions), the changing things last, and do not edit earlier turns, because any change breaks the cache from that point on. Caches also expire after a short idle time, so a slow agent can lose its cache between steps.
3. Cap and shape what comes in. Limit tool output size, paginate, and request only needed fields. This is the biggest single lever when a tool can return a large payload, since the saving repeats on every later step.
Latency follows the same levers. A smaller model answers faster, a cached prefix is processed faster, a shorter output finishes sooner, and independent tool calls can run in parallel instead of one after another. Streaming the final answer makes the wait feel shorter even when the total time is unchanged. For the step budget, a rough model is model time + tool time: if each step is 3 seconds of model plus 1 second of tool, 8 steps take about 32 seconds, and parallelising two independent lookups in one step saves a second or two, which is small beside dropping a step.
The cheapest step is the one you do not take. If the path is predictable, a workflow with fewer model calls beats a clever loop (see The Agent Loop in Depth).
Hard stops, graceful partial results, and cost per successful task
A hard stop that throws an error wastes the money already spent. A graceful stop returns what it has. Design two thresholds.
- Soft limit (for example 80 percent of budget): the loop stops exploring. It disables further tool calls except the ones needed to finish, and the next model call is a wrap-up: "Summarise what has been found, what is not yet known, and what you would do next. Do not call more tools."
- Hard limit (100 percent, or the max step count, or the time limit): the loop does not make another model call. Code assembles the partial result from the notes and tool results it already holds.
Return the partial result as a labelled state, not as a normal answer. The response carries status: "partial", a reason (budget_tokens, budget_time, max_steps), what was completed, what was not, and whether it is safe to resume. Otherwise a half-finished answer looks finished, and a user acts on it. If the task has side effects, a hard stop in the middle needs the care described in Reliable Agents: Retries, Idempotency, Checkpoints and Sagas: stop at a step boundary, not between a refund and its ledger entry.
Measure the right unit: cost per successful task, not cost per run. Failed and partial runs cost money and produce nothing, so averaging only over the good ones flatters you. Illustrative numbers: 100 runs cost $25.80 in total and 80 succeed.
cost per run = $25.80 / 100 = $0.258
cost per successful task = $25.80 / 80 = $0.3225
The second number is 25 percent higher, and it moves for reasons the first one hides. If routing to a small model cuts the run cost by half but drops success from 80 to 60 percent, the total becomes $12.90 and the cost per success becomes $12.90 / 60 = $0.215. Cheaper per success still, but only by about a third, not half, and the users now get 20 fewer good answers per 100. Always report cost, success rate and latency together, and break cost down by step type so you can see the offender.
- Alert on the tail, not just the mean. One task in a hundred that runs to the hard cap can dominate the bill. Track p95 cost and p95 latency per task.
- Log usage per step with the step type, the model and the tokens (input, output, cached), so every claim above can be checked from data.
- Budget the budget: the wrap-up call itself needs room, so the soft limit has to leave enough tokens for it.
Follow-ups they will ask
"What do you cut first?" Cap and trim tool outputs, since it is the largest and least risky saving. Then cache the stable prefix, then try routing, with a success-rate check on each change.
"How do you pick the hard cap?" Look at the distribution of cost per task from real runs. Set it above the p95 of successful tasks, so it stops runaways without clipping normal work, and revisit it as the agent changes.
"Can you predict cost before running?" Roughly, yes, from the formula: steps x (prefix + growing transcript) x input price, plus steps x output tokens x output price. It tells you which input to change. It will be wrong when the number of steps varies, so treat it as an estimate and check against logged usage.
"Does a smaller model hurt quality?" It can, on the hard steps. That is why you route by step type and measure task success, rather than switching the whole loop.
"What about latency, not cost?" Many levers are shared: smaller model, shorter output, a cached prefix, fewer steps. Parallelise independent tool calls, stream the answer, and set a per-step timeout so one slow tool does not consume the task budget.
"How do you stop a user or a bug running up a huge bill?" Per-task hard caps, per-user and per-day quotas, rate limits, and an alert on spend rate. The cap is the safety net for any single task, and the quota covers the aggregate.
"Why not just always use the cheapest model?" Because cost per successful task is what counts, and a model that fails more often can cost more per success even at a lower price per token.
How to say it in the interview
"I would set a budget per task in tokens and in dollars, and a latency budget per step, and make the loop check them in code before every model call. Then I would find where the cost really is, because it is rarely the model answers: it is the transcript being re-sent every step, retries, one huge tool output carried for the rest of the run, and reflection loops that double the output. The levers are routing easy steps to a smaller model, caching the stable prefix, and capping tool output. If the budget runs out the agent does not crash, it switches to a wrap-up step and returns what it has, labelled partial. And I would report cost per successful task, not per run, because failed runs are paid for too, and that is the number finance should see."
Checklist
- Set a token budget, a dollar budget and a per-step latency target, enforced in code before each model call rather than in the prompt.
- Use one clearly illustrative price list and say 'for example' instead of quoting vendor prices from memory.
- Price a run with a formula: steps times growing input, plus output, and show that most of the bill is re-sent context.
- Name the four hidden costs: re-sent context, retries, uncapped tool output and reflection loops, and fix the tool output first.
- Route easy steps to a smaller model and verify task success afterwards.
- Cache the stable prefix, put stable content first, and keep earlier turns byte-identical.
- Use a soft limit that triggers a wrap-up call and a hard limit that returns a labelled partial result, never a bare error.
- Report cost per successful task alongside success rate and p95, not just average cost per run.
Related lessons
- The Agent Loop in Depth: ReAct, Plan-and-Execute, Reflection and Stop Conditions
- Designing Tools an Agent Can Actually Use
- Agent Memory: Working, Episodic, Semantic and Procedural, Without the Rot
- Context Engineering for Long-Horizon Agents
- Frameworks, Protocols and Durable Execution: MCP, A2A and Long-Running Agents
- Reliable Agents: Retries, Idempotency, Checkpoints and Sagas