Agent in Production
ResilienceLong read

Enforcing Hard Spend Limits Before a Coding Agent Session Resumes Not After It Ends

Reserve budget before each agent action, not after it finishes.

· 9 min read
Cover illustration for “Enforcing Hard Spend Limits Before a Coding Agent Session Resumes Not After It Ends”
Resilience · October 26, 2026 · 9 min read · 1,946 words

Hard spend limits for AI coding agents require an execution gate that reserves budget before each costly action and revalidates authority before a paused session resumes. Dashboards and post-session alerts cannot make that promise. Effective enforcement combines atomic reservations, layered budget limits, and graceful shutdown with checkpointed state, so an agent cannot resume spending against stale permissions or an obsolete balance.

Why coding agents create unbounded economic exposure, not just elevated spend

Coding agents run in loops that go beyond a single request. Each step can spawn tool calls, sub-agent branches, retries, and reasoning expansions, so the initial request does not bound the work that follows. Cycles’s cost enforcement reference describes an agent encountering an ambiguous error, retrying with increasingly verbose prompts, and branching across sub-agents for hours. A failed attempt can therefore increase both the number and the size of subsequent calls.

Session length also changes the cost of execution. Each LLM request includes the full conversation history, so the number of tokens it uses grows nonlinearly as that history grows. By step twenty, inputs may be orders-of-magnitude larger than those at the start. Uber exhausted its entire 2026 AI budget in four months, by April 2026, after rolling Claude Code out to thousands of engineers. Its technology chief described spending roughly $1,200 in a single two-hour session, while power users orchestrating parallel agents ran costs far above the average.

Financial exposure is only part of the risk. An agent may also write database records, start deployments, or call external APIs as it spends. Those actions change how systems run, whatever the final bill comes to. Cutting off the budget after execution cannot undo side effects that have already happened.

Why the controls most teams already have cannot stop a runaway session

Dashboards report consumption that has already occurred. For an autonomous agent running overnight or in a CI pipeline, there may be nobody watching. The Cycles reference distinguishes notification from prevention precisely. An alert asks a human to intervene but does not block the next action.

Provider caps can stop usage, but at a broader scope. Anthropic’s hard monthly tier spend caps and OpenAI’s hard monthly limits, shipped July 23, 2026, operate at account or project level. A project cap cannot account for spending against other vendors, search APIs, or paid tools. Rate limits address a different dimension again. They limit how fast spending can grow, but the total can keep rising throughout a long session.

Application-level token counters appear closer to the problem, yet in-memory counters are lost on crashes and process restarts. When check and spend are separate operations, concurrent workers can also read the same available balance and go ahead. The failure is structural. An overnight retry loop can continue spending and committing side effects while an alert waits for a response, because nothing in that path requires permission for the next action.

What pre-execution enforcement actually means and how the reserve-execute-commit pattern implements it

Hard budget control has three defining properties. It is pre-execution, so the decision precedes the model call or side effect. The availability check and deduction from available budget happen in a single atomic database operation. It is cumulative, tracking reservations and settlements across steps, retries, and concurrent workers. Two workers cannot both read “budget available” and independently claim the same funds.

The reserve-execute-commit pattern implements these properties. Before an expensive operation, the agent requests a reservation for its estimated cost, and the budget manager atomically checks and locks that amount. If funds are insufficient, the reservation is rejected and the protected path does not execute. Execution requires a successful reservation before it begins. Afterward, the agent commits actual usage and returns any reserved amount it did not use to the pool. Payment systems use this same pattern of reservation and settlement.

Cancellation and failure need distinct treatment. If execution never starts, the agent explicitly releases the reservation. If it starts and fails, the agent commits the best-known actual usage. TTL expiry can recover an abandoned hold, but it cannot accurately charge work that began before a crash.

A central budget manager backed by Redis or Postgres makes this state durable across worker restarts. Each retry needs another reservation, and atomic operations keep concurrent workers from spending the same available balance. The budget is now an execution constraint. It is no longer billing metadata reconciled after the work has finished.

The six budget dimensions a session must enforce before it acts

A monetary cap alone can intervene too late. Before total spending reaches it, an agent may already have wasted calls, exhausted useful retries, or filled its context with degraded state. Production enforcement therefore needs layered limits over model calls, tool calls, tokens, monetary cost, retries, and task feasibility. These dimensions constrain different ways a session can fail, and they apply at run, step, and tool level.

Model-call limits cap total LLM invocations per run, bounding planning loops that do not converge. Tool-call limits distinguish tools by cost and risk. Illustrative limits might permit five web searches and two database writes, with each allowance calibrated to the workload. Token budgets constrain consumption as the conversation grows. Monetary controls then track both what the work is expected to cost and what it actually costs, counting outstanding reservations along with settled usage.

Retry budgets distinguish failure classes. Transient failures receive limited retries, validation errors receive none, and individual tools have their own retry limits to prevent storms. Feasibility checks address whether the remaining resources can realistically finish the task before another step begins. A step can be affordable yet unproductive. If the remaining budget cannot support completion, ending cleanly avoids starting work that will be interrupted mid-execution.

Dynamic downgrade rules that preserve continuity before a hard stop is required

Stopping multi-file feature work abruptly can leave a partially completed state whose repair costs more than the overspend would have. Graceful termination with checkpointed state addresses that risk without allowing unlimited execution. Enforcement need not jump directly from full capability to shutdown. Enforcement can scale back what the agent is allowed to do before shutdown, while there are still enough resources for a useful result.

Illustrative downgrade rules begin by moving routine planning from a large model to a smaller fallback after a majority of the budget has been consumed. The expensive model remains available for steps that require it. Around half the budget remaining, context compression can summarize prior steps and drop low-value messages to reduce per-call token costs. When around a third is left, tool gating can turn off web search and then non-critical retrieval expansion while keeping the database reads the task needs. These thresholds describe a pattern to adapt.

Each downgrade still needs a feasibility check. A cheaper path is useful only if it retains a realistic chance of finishing the job. Otherwise, graceful termination returns the work done so far, a reason for stopping, and the cheapest safe way to continue. Checkpointed state lets a person or another system pick up the task without reconstructing its context from scratch.

Why the resume moment is the specific gap most enforcement systems miss

A paused session looks safe because it is inactive. Its checkpoint preserves task state. Other tasks may have consumed capacity, accounting periods may have reset, and rate limits may have changed. Credentials may also have expired or been revoked. Resuming against the checkpoint’s assumptions can therefore authorize new work with stale information.

Resume is an authorization boundary. The initial phase begins read-only, loading the task, inspecting artifacts, querying external state, rechecking authority and budgets, and classifying uncertainty. Only after those reads agree may the agent produce another side effect. The next cost estimate must also reflect the current token state. Accumulated context can make that first resumed call substantially more expensive.

Accounting must survive the same transition. Restarting a worker, resuming a task, or moving work to another API key must not silently reset a daily cap. Late usage belongs to the reservation’s original accounting period, and in-flight commitments must remain visible across a reset. Otherwise, a lifecycle event becomes a way around the budget.

At SaaSNext, an autonomous agent spent tens of thousands of dollars in nine hours during a recursive tool-call loop. It subsequently deployed a token budget enforcer with task, session, and daily controls, real-time token tracking, and automatic circuit breakers. That layered accounting addresses runaway consumption, but safe resumption also requires renewed authority. The revalidation contract must check current capabilities, date gates, rate budgets, spend budgets, and active blockers before a resumed session acts.

How audit trails and governance requirements make enforcement logs non-optional

An enforcement gate also produces evidence of governance. A separate observer can report what happened, but retrospective logs alone cannot establish that a required pre-action decision controlled execution. The record must connect policy to the action. For regulated deployments and enterprise governance, that connection supports both operational investigation and accountability for delegated authority.

HIPAA Technical Safeguards require hardware, software, and/or procedural mechanisms that record and examine activity in information systems containing or using ePHI. HHS leaves the specific scope and granularity flexible, so this requirement should not be described as a mandate for evidence of every individual access attempt. Written policy alone cannot take the place of audit controls. The U.S. Treasury’s Financial Services AI Risk Management Framework, by contrast, is voluntary, non-binding guidance and creates no new legal obligations.

For agent governance, each action should have a structured record. Its fields should include the unique agent identifier and version, delegated permissions, the specific tool or API invoked, the permit-or-deny policy decision, and the reasoning step generated before acting. The decision record explains more than an activity log. Knowing that an agent deleted a file differs from understanding why it believed deletion was appropriate.

CAISI launched its AI Agent Standards Initiative on February 17, 2026, covering industry-led standards, open-source interoperability protocols, and research into agent security and identity. Singapore’s Model AI Governance Framework for Agentic AI, released in 2026, is the world’s first governance framework specifically designed for autonomous agentic systems. These initiatives place identity, authority, and accountable action within the broader governance requirements that enforcement infrastructure must support.

The infrastructure design that makes pre-session enforcement structurally enforced rather than opt-in

Separating the model client from its tools makes enforcement harder to bypass. The “brain,” which talks to the model API, runs outside the sandbox and holds the API key. The “hands,” including the shell, test runner, file edits, and package manager, run inside a locked-down container without secrets and with restricted networking. The agent cannot mint its own credentials or escape its budget scope.

Declarative configuration makes the policy inspectable before execution. YAML-driven environments put agent behavior, budget limits, tool permissions, and model routing rules in the repository, where changes can be reviewed like code. Policy becomes version-controlled, diffable, and attributable to a person or trigger. Session isolation then gives that policy a lifecycle boundary. Credentials are minted fresh for each session and revoked on completion, preventing a resumed session from simply inheriting its prior credential scope.

Hard caps must be controllable at session, developer, and time-period level, while every tool call, diff, and token remains logged and attributable. A spending dashboard does not satisfy these criteria. A hard account cap also falls short of these criteria if it leaves session-level authority unchecked.

Teams building it themselves retain responsibility for atomic reservations, layered budgets, resume revalidation, and audit records. A managed platform must supply those mechanisms by default to remove that burden. The decisive test is whether a paused agent can execute its next costly action without renewed permission. If it can, the budget is still advisory at the moment it most needs to bind.

Sources

  1. Token Budgets: An Empirical Catalog of 63 LLM-Agent Budget-Overrun Incidents, with an Affine-Typed Rust Mitigation as a Case Study
Filed underResilience

More in Resilience