Runtime Budget Enforcement for AI Agents: Tracking Tokens, Tool Calls, and Time Before Graceful Degradation or Shutdown
Table of contents
An AI agent can plan, call a tool, inspect the result, and decide to try again. That loop makes agents useful for open-ended work. It also gives them an unusually flexible way to exhaust resources. Consider two failure scenarios: a misrouted request spends $40 on model calls in three minutes, while another agent retries a slow service for 25 minutes and occupies a worker the entire time. A token cap alone would not prevent both. Production agents need a budget for the whole run, enforced before each step and updated as the run proceeds. The goal is predictable resource use and a useful outcome when the agent runs out of runway.
Why Agent Runs Exceed Their Budgets#
A conventional endpoint usually follows a known sequence of operations. An agent chooses its next operation from what it has just observed. A failed search may prompt a broader search; that result may prompt several file reads; an ambiguous tool error may trigger another attempt. Each choice can be reasonable in isolation while the combined run becomes expensive or unbounded. Three limits matter most:
- Tokens: input and output tokens across every model call, including tool results sent back to the model.
- Tool calls: attempted calls, retries, and fan-out to external services or local processes.
- Time: the elapsed time from request start to completion, including queues, network waits, and tool execution. These limits constrain different failures. A model can consume many tokens in few calls. A short-response tool can be called hundreds of times. A single stalled call can exceed the deadline without using many tokens at all.
Give Every Run a Defined Runway#
Create a budget when the request starts. For example, an interactive research task might receive 30,000 total tokens, 20 tool attempts, and a 120-second deadline. It may also have a maximum estimated spend of $2. Those figures are policy choices, not universal defaults; they should reflect the task, user expectations, and measured operating costs. Store the budget with the run, alongside counters for actual usage and reservations for work already in flight. Before a model call, reserve an estimate for its input and maximum permitted output. Before a tool call, reserve one attempt and check that enough time remains for its timeout. If the reservation would cross a hard limit, choose a cheaper action or stop before launching the work. Afterward, replace estimates with actual usage when available. Token counts reported by the model provider are preferable to local estimates, but estimates remain necessary before the call. Keep reservations until concurrent calls settle; otherwise, five parallel calls could each see the same remaining allowance and collectively overspend it. A simplified admission rule is:
allow next step only if
actual usage + in-flight reservations + proposed reservation
fits within every hard limit
The deadline needs its own treatment. Use a monotonic clock to measure elapsed time, and pass a timeout no longer than the run’s remaining time to each model or tool call. Checking the clock only between calls leaves a stalled call free to overrun the budget.
Count the Work That Actually Happens#
Budget accounting should follow execution, not just successful results. A tool attempt that times out still consumed time and may have incurred an external charge. A model call that fails after receiving a response may still be billable. Retries belong to the same parent run budget. Record enough detail to explain a run later: model input and output tokens, tool name, attempt number, duration, estimated and final cost, and the reason a step was admitted or rejected. Keep the per-run counters in a place that survives worker restarts if runs can be resumed. A process-local counter is insufficient when a task can move between workers. Child agents and parallel branches need explicit allocations. A parent with ten tool calls remaining cannot safely give each of three children a ten-call allowance. Reserve a share for each child, then return unused capacity when it finishes. The parent’s hard limit must remain authoritative across the entire task tree. Retries also need their own ceiling. A run with 20 tool calls should not spend all 20 on one failing endpoint. For example, permit at most two retries for that endpoint, apply backoff within the run deadline, and surface the failure to the agent so it can take another path.
Degrade Before the Hard Stop#
A hard limit protects the system; a soft threshold gives the agent time to finish well. The runtime can expose a small, structured budget status to the agent after each step: remaining tokens, calls, and seconds, plus whether it must begin wrapping up. The runtime still makes the final admission decision; a prompt asking the agent to “be brief” is not enforcement. A practical policy could use two stages:
At 70% usage: conserve#
Ask the agent to narrow its plan. It might summarize a large tool result before adding it to context, avoid optional searches, or choose one promising lead instead of exploring several. Token, tool, and time thresholds should be checked independently: plenty of tokens do not compensate for five seconds left on the clock.
At 90% usage: conclude or hand off#
Stop admitting exploratory work. Reserve enough tokens and time for a final response that states what was completed, what remains uncertain, and the next useful action. If the task can resume, save a compact checkpoint containing verified findings, relevant references, unfinished steps, and the budget state. A resumed run should receive a newly authorized budget, not silently reset the old one. For the 30,000-token, 20-call, 120-second example, the agent might begin conserving at 21,000 tokens, 14 calls, or 84 seconds—whichever occurs first. At 27,000 tokens, 18 calls, or 108 seconds, it should wrap up. The hard limits remain at 30,000, 20, and 120. Thresholds should be tuned from observed runs so the final-response reserve is large enough to be useful.
Shut Down Safely When No Runway Remains#
Some work must stop immediately. A user may cancel, a deadline may expire during a tool call, or a hard limit may be reached without enough room for another model response. The runtime should cancel in-flight work where supported, release reservations, and mark the run with a specific termination reason. Do not present a partial answer as though the requested task were completed. Side-effecting tools require particular care. If an agent is about to deploy code, send a message, or modify data, check the budget before starting that action. Once started, a timeout does not prove that the action failed: the remote service may have completed it before the connection closed. Use operation identifiers and idempotency where available, then verify the outcome before retrying or reporting it. A useful final state distinguishes “completed,” “completed with reduced scope,” “paused for handoff,” “cancelled,” and “stopped by budget.” That distinction helps users decide what to do next and helps operators diagnose repeated failures.
Make Budget Enforcement an Operational Control#
Measure how often runs reach soft and hard thresholds, where they spend tokens and time, which tools trigger retries, and whether degraded answers remain useful. Review those measurements by task type. A high rate of budget stops may mean the limits are too small, but it may also reveal poor tool results, oversized context, or an agent repeatedly pursuing the same failed plan. Runtime budgets are not simply a way to make agents cheaper. They establish a predictable boundary around autonomous work. When the boundary is visible throughout the run, an agent can spend its remaining runway on a concise answer, a reliable handoff, or a clean stop instead of ending in an uncontrolled loop.