
Your Agent Works. Can You Afford It? (token economics + cost control)
Your agent passes every eval and the bill still doubles. A practical guide to the unit economics of agentic systems on AWS: cost per resolved task, the four failure modes that quietly inflate spend, prompt caching and model tiering done properly, and a cost gate you can run in CI.
Five articles ago we put an agent on the factory floor for predictive maintenance . Then we took it from demos to deployments with production-grade MCP patterns, wrapped it in a guardrail playbook before it touched production, and last time built an evaluation harness so that "does it actually work" could be answered with a number instead of a feeling.
That last piece drew more comments than anything else I have written here, and a surprising number of them were variations on the same follow-up.
Fine. It works. What is it costing me?
This is the question that quietly kills agent programmes. Not the security review, not the accuracy argument. It is a finance conversation in month three, where somebody puts an invoice on the table and asks why an assistant that answers questions about pump vibration now costs more per month than the technician who used to do it. If you cannot decompose that number, the project does not survive its next budget cycle.
So this one is about unit economics. Not the pricing page, which you can read yourself, but the structural reasons agents are expensive in ways their builders do not anticipate, and what to do about it.
Why agent cost is not model cost
A single model call has a cost you can predict. Tokens in, tokens out, arithmetic. An agent breaks that prediction in four specific ways.
The call count is emergent, not designed. You do not decide how many model calls a trajectory takes. The agent decides, at runtime, based on the input it received. Your median might be four calls. Your p99 is forty. Capacity planning built on the median will be wrong by an order of magnitude on exactly the traffic that matters.
Context grows quadratically inside a trajectory. Every step resends the accumulated history, so step ten pays again for steps one through nine. A ten-step trajectory does not cost ten times a single call. Without compaction it lands nearer fifty times, because cumulative token volume grows with the square of the step count.
Failure costs the same as success. A trajectory that burns thirty thousand tokens across eight steps and then gives up bills identically to one that closes the ticket. Your spend dashboard shows the total. It does not show that a third of it bought nothing.
The cost is spread across services. Model tokens are the headline, but the invoice also carries AgentCore runtime seconds and Gateway operations, vector store capacity that does not scale to zero, CloudWatch ingestion for all the tracing you added when you productionised, and data transfer. Teams optimise the token line, achieve a real reduction on it, and are then baffled that the bill barely moves.
The only metric worth reporting
Cost per thousand tokens is a rate card, not a metric. Cost per request is actively misleading, because one request may be a trajectory of thirty calls. The number to put in front of a business owner is cost per resolved task.
CPRT = total spend in the window / tasks resolved to standard in the windowTotal spend means everything: successful trajectories, failed trajectories, retries, evaluation runs, retrieval, runtime, logging. Resolved to standard means the outcome passed the criteria you defined in your eval harness, not merely that the agent produced fluent text.
Write it out and something useful falls out. Take ten thousand trajectories in a month, eight thousand resolved, four thousand dollars of spend. CPRT is fifty cents. Now improve resolution from eighty percent to ninety percent and change nothing whatsoever about tokens, models or context. Spend stays at four thousand, resolved tasks become nine thousand, CPRT drops to forty-four cents. An eleven percent cost reduction with zero optimisation work.
That is the part most cost programmes miss. Accuracy is a cost lever, and usually the cheapest one available. The harness from the previous article is not a quality tool sitting adjacent to your cost work. It is the first item in your cost work, and it is also the thing that stops every subsequent lever from silently degrading the product.
The four ways the bill inflates
In every agent system I have looked at, the overspend traces back to one of four patterns. None of them show up in a demo.
1. The context snowball. Nothing is ever removed from the conversation. Tool results, intermediate reasoning, retrieved documents and prior turns all accumulate and are resent at full price on every step. This is the single largest source of avoidable spend, and it is invisible at low step counts, which is exactly why it survives the pilot.
2. The reflection loop. The agent reasons about its own previous reasoning without any new information entering the context. Self-critique with no stopping condition, plan revision that revises the revision. These steps feel like sophistication and they are pure cost. The diagnostic is simple: flag any step where no tool was called and no external data arrived. If those steps are more than a small fraction of your trajectories, you are paying the model to talk to itself.
3. Retrieval and tool fan-out. Top-k set to twenty because twenty felt safer than five. Tools returning entire JSON payloads when the agent uses three fields. An expensive model-backed tool invoked before the cheap deterministic lookup that would have answered the question outright. Every one of these inflates input tokens on the current step and, because of the snowball, on every step after it.
4. The silent retry. A tool times out, the framework retries the step, the full context is resent. On a normal day this is noise. On a day when an upstream system is degraded, it is most of your bill, and you will not find it unless your accounting is per step rather than per session.
Instrument before you optimise
You cannot manage what you do not attribute. The smallest useful piece of engineering here is a wrapper that records token usage per step and enforces a hard budget on the trajectory, so a runaway loop fails loudly instead of billing quietly.
import time
from dataclasses import dataclass, field
import boto3
# Fill these from the Bedrock pricing page for YOUR region and model IDs.
# Keep them in config, not in code, and re-baseline them on every model upgrade:
# a new model version can change the tokenizer, which changes billable volume
# for identical text.
RATES = {
"small": {"in": 0.0, "out": 0.0, "cache_read": 0.0, "cache_write": 0.0},
"large": {"in": 0.0, "out": 0.0, "cache_read": 0.0, "cache_write": 0.0},
}
class BudgetExceeded(Exception):
pass
@dataclass
class TrajectoryLedger:
trajectory_id: str
max_steps: int = 12
max_usd: float = 0.25
steps: list = field(default_factory=list)
@property
def spend(self) -> float:
return sum(s["usd"] for s in self.steps)
def record(self, tier, usage, latency, tool_called, new_data):
r = RATES[tier]
usd = (
usage.get("inputTokens", 0) / 1000 * r["in"]
+ usage.get("outputTokens", 0) / 1000 * r["out"]
+ usage.get("cacheReadInputTokens", 0) / 1000 * r["cache_read"]
+ usage.get("cacheWriteInputTokens", 0) / 1000 * r["cache_write"]
)
self.steps.append(
{
"step": len(self.steps) + 1,
"tier": tier,
"usd": usd,
"latency_s": latency,
"tool_called": tool_called,
# a step with no tool call and no new data is a reflection step
"reflection": (not tool_called) and (not new_data),
**usage,
}
)
if len(self.steps) > self.max_steps:
raise BudgetExceeded(f"{self.trajectory_id}: step cap hit")
if self.spend > self.max_usd:
raise BudgetExceeded(f"{self.trajectory_id}: {self.spend:.4f} USD")
client = boto3.client("bedrock-runtime")
def call(ledger, tier, model_id, messages, system, tools=None):
started = time.time()
resp = client.converse(
modelId=model_id,
messages=messages,
# Cache checkpoint placement is the whole game. Static content first:
# instructions, tool schemas, reference documents. Volatile content last.
system=system,
**({"toolConfig": {"tools": tools}} if tools else {}),
)
tool_called = resp.get("stopReason") == "tool_use"
ledger.record(
tier=tier,
usage=resp.get("usage", {}),
latency=time.time() - started,
tool_called=tool_called,
new_data=tool_called,
)
return respThree fields in that ledger earn their keep immediately: the reflection flag, the per-step spend, and the cache read and write counts. If cache reads are zero across a multi-step trajectory, your prefix is not stable and you are paying full price for content that never changes. That is usually a five-line fix worth a large fraction of your input spend.
Emit the ledger as a single structured log line per trajectory, with tenant, use case and agent version as dimensions. That log is what makes cost attribution possible later, and no amount of account-level tagging will reconstruct it after the fact.
The levers, in order of return
Work top down. The order matters more than the list, because the cheap levers are also the ones with the least quality risk.
Lever | Where it hits | Effort | Quality risk |
|---|---|---|---|
Fix accuracy first | Failed trajectories that bought nothing | Medium | None, it improves |
Prompt caching with a stable prefix | Repeated input tokens | Low | None |
Tool output discipline | Input tokens, compounding | Low | Low |
Context compaction | Input tokens, compounding | Medium | Medium |
Step and spend budgets | The expensive tail | Low | Low, degrades gracefully |
Model tiering | Everything | Medium | High, needs the harness |
Batch or flex tier for offline work | The non-interactive slice | Low | None |
Distillation for the repetitive step | The highest-volume step | High | Medium |
A few notes where the detail decides whether the lever works.
Prompt caching rewards prompt architecture, not prompt cleverness. Cached reads are billed at a small fraction of the input rate while cache writes carry a premium, so the economics only work if the prefix genuinely repeats. Put the invariant material first, in this order: system instructions, tool schemas, reference documents, then the cache checkpoint, then the volatile conversation. One dynamic token near the top, a timestamp or a session id, invalidates everything after it and turns a saving into a surcharge. Check your cache hit rate before you claim the benefit.
Model tiering is the largest single win and the most dangerous. Most trajectories contain one genuinely hard step and several trivial ones: intent classification, field extraction, formatting, routing. Those belong on a small model. The reasoning step does not. Do this only behind the eval harness, per step, with the gate from the last article, because the failure mode is a quality regression that shows up in production three weeks later as a support ticket rather than as an alarm.
Step budgets are the only lever that protects the tail rather than the mean. A hard cap with a graceful handoff, escalate to a human with the work so far attached, converts an unbounded cost incident into a bounded one. Every agent in production should have one.
Batch and flex pricing applies to more of your workload than you think. Overnight enrichment, back-population, evaluation runs and report generation do not need interactive latency, and moving them off on-demand is the least intellectually interesting cost win available. Take it anyway.
Put cost in the gate
Last time we gated merges on quality. Cost belongs in the same gate, evaluated on the same reference task set, because a prompt change that improves accuracy by two points and triples token spend is not an improvement and should not merge unnoticed.
# runs on every change to prompts, tools, models, or retrieval config
gate:
quality:
outcome_score: { min: 0.90 }
tool_precision: { min: 0.85 }
cost:
usd_per_resolved: { max: 0.55 } # the metric that matters
p50_steps: { max: 5 }
p95_steps: { max: 12 } # the tail, not the mean
cache_hit_rate: { min: 0.70 } # is the prefix actually stable
reflection_step_rate: { max: 0.15 } # model talking to itself
p95_usd_trajectory: { max: 0.90 } # runaway protectionTwo of those thresholds do the unglamorous work. The cache hit rate catches the prefix breakage that a refactor introduces without anyone noticing. The reflection step rate catches the prompt edit that turns a decisive agent into a deliberative one, which reads as better behaviour in review and costs forty percent more in production.
Attribution, so the number survives contact with finance
Cost per resolved task is only defensible if you can show where it comes from.
Tag everything at creation, not later: agent name, version, use case, tenant, environment. Enable model invocation logging so token counts land somewhere queryable rather than living only in application logs. Publish the ledger as custom CloudWatch metrics with the same dimensions, then reconcile your application-side estimate against Cost Explorer and the Cost and Usage Report weekly. The two will differ. The gap is where you find the vector store capacity, the log ingestion and the runtime seconds that your token maths ignored.
Set an AWS Budgets alert per agent, not per account. An account-level alert tells you that something is wrong in the middle of the month. A per-agent alert tells you which one.
What this looks like on the shop floor
The industrial version of this conversation is more concrete than the software one, and more useful for it. A plant manager does not ask about tokens. They ask what it costs to triage one alarm, raise one work order, or close out one inspection, and they compare it against a technician-hour, because that is the alternative they are being asked to give up.
That comparison is winnable, and it is winnable by a wide margin. But it is only winnable if you can state the number, show the trend, and explain the tail. "Roughly fifteen cents per alarm triaged, ninety-two percent resolved without escalation, worst case capped at two dollars" is a sentence that gets a budget renewed. "It uses Bedrock" is not.
Where this leaves the series
Six articles in, we have taken an agent from an idea on the factory floor through deployment, security, observability, proof that it works, and now proof that it is worth what it costs. Those last two belong together. Quality without cost control is a pilot that never scales. Cost control without a quality gate is a cheaper agent that is worse at its job, which is the most expensive outcome of all.
If you are running agents on AWS today and cannot state your cost per resolved task, start with the ledger. One structured log line per trajectory, with per-step tokens and cache counts. Within a week you will know which of the four failure modes you have, and it will almost certainly be the context snowball.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article