Cost control for long running agent loops: budgets, caps and a conductor
How to keep an agent that runs for hours from quietly spending a week of budget
Cost control for long running agent loops comes down to four hard limits set outside the model: a token budget, a step cap, a wall-clock timeout and a retry ceiling per loop. Anthropic's own guidance on managing Claude Code costs makes the same point from the user side: spend tracks how much context the agent carries and how many turns it takes, so the way to control it is to bound both.
Key Takeaways
- •An agent loop re-sends its accumulated context on every iteration, so cost grows faster than the number of steps.
- •Every loop needs four limits enforced by the runtime, not by the prompt: tokens, steps, wall-clock time and retries.
- •Prompt caching reduces the cost of repeated context, but it does not replace a budget. See the prompt caching docs for how it is priced.
- •Most runaway loops are retry loops: the agent keeps repeating a failing action with slightly different input.
- •Read-only by default, with writes behind approval, is also a cost control, because it stops an agent from acting on a bad guess at scale.
Cost control for long running agent loops starts with a budget per loop
A single prompt has a predictable cost: input tokens plus output tokens. A loop does not. Each iteration appends tool results and reasoning to the context, and the next call pays for all of it again. A loop that runs forty steps does not cost forty times one step. It costs closer to the sum of an ever-growing series. That is why a job that looks cheap in a ten-minute test can be expensive when it runs overnight.
The first decision is therefore not which model to use. It is what this loop is allowed to spend before a human hears about it. We recommend writing that number down per loop, the same way a team writes down a warehouse credit quota per workload. If nobody can state the ceiling for a loop, the loop does not have one.
Where the money actually goes
Before adding limits, it helps to know which part of the loop is expensive. In our experience with data workloads, the spend concentrates in a few places, and these are our observations, not a benchmark.
- •Repeated context: schemas, lineage and prior tool output that get re-sent on every step.
- •Large tool results: an unbounded query result or a full table description pasted into the context.
- •Retries: the agent hits an error, tries again, and carries the failed attempt forward in context.
- •Exploration: the agent searches broadly when the question was narrow.
- •Compute behind the tools: the queries the agent runs against the warehouse cost money independently of the model tokens.
The last item is easy to miss. In data work, the model bill is often smaller than the warehouse bill the loop creates. An agent that re-runs a heavy scan on each iteration is spending in two places at once.
The four limits every loop needs
| Limit | What it caps | Failure it prevents |
|---|---|---|
| Token budget | Total input and output tokens for the loop | Context growth that makes late steps expensive |
| Step cap | Number of model turns or tool calls | A loop that never decides it is finished |
| Wall-clock timeout | Elapsed time for the whole run | Slow, stuck tool calls that hold a loop open |
| Retry ceiling | Attempts at the same action | The agent repeating one failing call with small variations |
The important design rule is that these limits live in the runtime, not in the system prompt. A prompt that says "stop after 20 steps" is a request. A harness that terminates the loop at step 20 is a control. When a limit trips, the loop should stop, write down where it got to, and hand off to a person or a cheaper fallback path instead of silently continuing.
Keep the context small on purpose
Context discipline is the largest lever after the hard limits. Three habits matter most. First, return summaries from tools, not raw output: row counts, column names and the top few values rather than the full result. Second, put stable material, such as the schema and the task definition, at the start of the context so it can be cached. The prompt caching documentation describes how cached prefix reads are priced differently from fresh input. Third, checkpoint and restart: when a loop has done a large chunk of work, carry forward a short state summary into a fresh context instead of dragging the whole history along.
Caching helps, but it rewards a stable prefix. A loop that edits the top of its own context on every step defeats it. Design the context so the unchanging part comes first and the changing part comes last.
Treat retries as the main risk
When we look at loops that overspent, the cause is usually not a hard problem. It is an easy failure repeated. The agent calls a tool, gets a permissions error or a schema mismatch, and tries again with a small change. Each attempt adds to the context and the next call costs more.
Two rules help. Cap retries per action, and make the second attempt different in kind: if the same call fails twice with the same class of error, escalate instead of rephrasing. Classifying errors as retryable (a timeout) or not retryable (a missing permission) is cheap to build and removes most of the pathological cases.
Put a cost check inside the loop, not after it
A monthly bill tells you a loop was expensive after the money is gone. The useful signal is spend per run, visible while the run is in progress. At minimum, log tokens used, tool calls made and warehouse cost for each loop run, and compare the running total against the budget on every step. A loop that has used 80 percent of its budget with the task half done should be flagged, not left to finish.
On the warehouse side, our Cost Agent looks at the compute the loop causes: idle warehouses, oversized queries and repeated scans. It answers questions like "How much are we spending on Snowflake this month?" and "What's causing the warehouse queue to spike?", which lets you separate model spend from the data-platform spend an agent triggers. We covered how agents chain with observability and usage data in a separate post on how the swarm shares context.
Use autonomy as a cost control
Autonomy level is a spending decision. An agent that can only read can waste tokens, but it cannot trigger a rebuild of a large table or kick off a backfill on a wrong assumption. Our open-source edition is read-only by default for this reason, and Pro adds writes behind approval workflows and audit trails.
This is how the Autonomous Data Conductor is built: a per-domain autonomy dial. A domain such as cost reporting can run fully autonomously because the worst case is a wasted query. A domain such as production schema changes stays behind approval. Each domain gets its own budget and its own autonomy setting, so a loop in a low-risk area can run for hours while a loop in a high-risk area stops early and asks. The goal is that data operations take zero human effort where the risk is low, and the dial keeps humans in the path where it is not.
A practical setup for a data team
- •Write a budget for each loop: maximum tokens, maximum steps, maximum minutes and maximum retries per action.
- •Enforce those limits in the harness and make a tripped limit produce a handoff note, not a silent stop.
- •Cap tool output size and return summaries by default.
- •Put stable context first so caching applies, and checkpoint long runs into a fresh context.
- •Log spend per run, including the warehouse queries the loop triggered.
- •Start every new loop read-only, then grant writes one domain at a time.
Because each of our agents is an MCP server, these limits can sit at the client where your engineers already work, whether that is Claude Code, Cursor or another MCP client. The Model Context Protocol defines how tools are exposed, and a harness that wraps tool calls can count and cap them in one place.
Frequently Asked Questions
How do I stop an agent loop from running up a large bill? Set four limits in the runtime: a token budget, a step cap, a wall-clock timeout and a retry ceiling per action. Enforce them in the harness rather than the prompt, and make a tripped limit stop the loop and hand off to a person.
Does prompt caching solve cost control for long running agent loops? No. Caching lowers the price of repeated context when the prefix is stable, but it does not limit how many steps the loop takes or how many retries it makes. Treat it as an optimization on top of a budget, not a substitute for one.
Why do long agent loops get more expensive per step as they run? Each step sends the accumulated context again, including earlier tool results and failed attempts. Total cost therefore grows faster than the step count. Summarizing tool output and restarting from a short state summary keeps late steps from becoming the most expensive ones.
Should the agent decide when it has spent enough? We do not recommend it. A model can estimate its own progress, but the stop condition should come from code that counts tokens, steps and time. The model can report that it is close to a limit, but it should not be the one enforcing it.
What costs more for data agents, the model or the warehouse? It depends on the workload, so measure both for your own loops. In data work, an agent that repeatedly runs heavy queries can create more spend in the warehouse than in tokens, which is why we track the two together.