An agent without a hard limit does not fail safe when something goes wrong. It fails open — it keeps calling, keeps spending, keeps acting, right up until a human notices the bill or the audit trail.
Most of the governance written about agentic AI is about what an agent is allowed to decide. That matters, but it assumes the agent’s own logic behaves. The harder failure is the one where the logic does not behave: a planning loop that never terminates, a tool call that triggers a hundred more, a retry that compounds cost every time it fires. You cannot reason your way out of that with a better prompt. You need a limit that sits outside the agent, that the agent cannot see or argue with, and that stops the run when a budget is spent. That limit belongs at the gateway — the one chokepoint every model call and every tool call has to pass through.
Three budgets, not one
“Budget” usually means money, and money is the one people notice last, because the invoice arrives at the end of the month. By then the damage is done. Effective bounding means three separate meters, each of which can independently stop the agent:
Free · 4 minutes
Do you know what could take the business down — and have you priced it?
Fourteen questions on concentration, third-party dependence, resilience, and incident readiness — the exposures a board is accountable for whether or not it can see them. Banded finding on screen, full sheet by email.
- A token budget. The total model tokens an agent may consume in a session or a day. This is the meter that catches a reasoning loop before it becomes expensive, because runaway loops burn tokens long before they burn anything else.
- An action-rate limit. How many calls per second the agent may make. This bounds the blast radius of a tight loop and protects the downstream systems the agent talks to — your own APIs, third-party services, a database — from being hammered by an agent that has lost the plot.
- A monetary cap. A hard ceiling in real money, per agent, per window. Model tokens are not the only cost — a tool call that places an order, provisions infrastructure, or hits a metered API spends money that no token count captures.
These are different meters because they catch different failures. A cheap model in a fast loop blows the rate limit and the token budget long before the monetary cap. An agent calling one expensive external action per minute blows the monetary cap while barely touching the other two. Collapse them into a single number and you lose the failure you were trying to catch.
The OWASP Top 10 for LLM Applications names this directly: Unbounded Consumption and Excessive Agency are two of its ten risks, and the newer OWASP list for agentic applications carries the same theme forward. The point of a budget is to make unbounded consumption structurally impossible rather than something you hope the model avoids.
Where the enforcement has to live
The instinct is to put the limit inside the agent — a counter in the harness, a check in the planning loop. Do not. Enforcement inside the thing being limited is enforcement the thing can bypass, forget, or be prompted out of. If the budget check is code the agent orchestrates, a confused or adversarial agent can route around it. The check has to sit in front of the agent’s reach, not inside it.
A gateway is the natural place. If every model call and every tool call already flows through one proxy — and if it does not, that is the first thing to fix — then the budget check is a piece of middleware every call passes on the way out. The agent asks the gateway to do something; the gateway checks the budget before it does it; if the budget is spent, the request is denied and nothing happens. The agent never gets to act, because acting requires the gateway’s cooperation and the gateway has withdrawn it. This is the same discipline as hardening an MCP server with auth, scoping and rate limits: the control lives at the boundary the agent cannot move.
The middleware
The rate limit is a token bucket — a well-worn algorithm that refills at a fixed rate up to a cap, so an agent can burst a little but not sustain a flood. The token and money ceilings are running counters checked cumulatively against a per-window limit. All three are checked before the call is allowed to proceed, and the estimate is reserved up front, then reconciled against the real cost once the call returns.
"""Agent gateway budget middleware.
Every agent call passes through check() before it reaches a model or a
tool. If any limit is exceeded the call is denied — the gateway fails
closed rather than letting the agent run on.
"""
import time
from dataclasses import dataclass
from threading import Lock
@dataclass
class Budget:
# Action-rate limit (token bucket).
rate_per_sec: float # bucket refill rate, actions per second
burst: float # bucket capacity, the most it can spend at once
# Cumulative ceilings, checked per window (per session or per day).
max_llm_tokens: int # model tokens the agent may consume
max_spend_pence: int # monetary cap, in pence, to avoid float money
@dataclass
class _State:
tokens: float # current action allowance in the bucket
last_refill: float
llm_tokens_used: int = 0
spend_pence: int = 0
class BudgetExceeded(Exception):
def __init__(self, agent_id: str, reason: str):
self.agent_id = agent_id
self.reason = reason
super().__init__(f"agent {agent_id}: {reason}")
class GatewayBudget:
"""Per-agent enforcement. One instance per gateway process; back the
state with Redis if you run more than one gateway replica."""
def __init__(self, budgets: "dict[str, Budget]"):
self._budgets = budgets
self._state: "dict[str, _State]" = {}
self._lock = Lock()
def _refill(self, s: _State, b: Budget, now: float) -> None:
elapsed = now - s.last_refill
s.tokens = min(b.burst, s.tokens + elapsed * b.rate_per_sec)
s.last_refill = now
def check(self, agent_id: str, est_tokens: int, est_pence: int) -> None:
"""Call once before every agent action. Raises BudgetExceeded,
which the gateway must turn into a denial — never a retry loop."""
b = self._budgets.get(agent_id)
if b is None:
# Unknown agent: deny by default, never wave it through.
raise BudgetExceeded(agent_id, "no budget defined")
now = time.monotonic()
with self._lock:
s = self._state.setdefault(
agent_id, _State(tokens=b.burst, last_refill=now)
)
self._refill(s, b, now)
if s.tokens < 1.0:
raise BudgetExceeded(agent_id, "action-rate limit hit")
if s.llm_tokens_used + est_tokens > b.max_llm_tokens:
raise BudgetExceeded(agent_id, "token budget exhausted")
if s.spend_pence + est_pence > b.max_spend_pence:
raise BudgetExceeded(agent_id, "spend cap reached")
# Reserve the estimate now; reconcile the actuals afterwards.
s.tokens -= 1.0
s.llm_tokens_used += est_tokens
s.spend_pence += est_pence
def reconcile(self, agent_id: str, d_tokens: int, d_pence: int) -> None:
"""Fold the difference between estimate and actual back in once the
real cost of the call is known."""
with self._lock:
s = self._state[agent_id]
s.llm_tokens_used += d_tokens
s.spend_pence += d_pence
The reserve-then-reconcile shape matters. You check against an estimate before the call, because you do not know the true token count or cost until the response comes back. Reserving the estimate stops a burst of concurrent calls from each individually passing a check they would collectively fail. Reconciling afterwards keeps the meter honest. Hold the reservation and you under-count; skip it and you race.
Denial has to be graceful, and it has to be final
Two failure modes turn a good limit into a bad one. The first is denial that reads as a transient error. If the gateway returns something the agent interprets as “try again,” the agent will try again — and a rate-limit denial that triggers a retry is a loop that spends its way around the very limit meant to stop it. A budget denial must be terminal and legible: a distinct signal that says stopped by policy, not temporarily unavailable. The exception in the code above carries a reason for exactly that purpose, and the layer above it must not wrap a budget denial in a retry.
The second is the unknown agent. If a call arrives for an agent with no budget defined, the safe answer is to deny it, not to wave it through. Fail-closed means the absence of a rule is itself a stop. An agent that has not been given a budget is an agent nobody has decided how much to trust, and undeclared trust is the failure that budgets exist to prevent. This is the enforcement counterpart to defining what an agent is allowed to decide and to encoding autonomy tiers as an approval matrix — the scope defines what the agent may attempt; the budget bounds how much it may consume attempting it.
What the board actually gets from this
The value of a central budget is not that it saves money, though it does. It is that it converts an open-ended question — “what is the worst this agent can do?” — into a bounded one you can put in a sentence. The worst this agent can do is spend N tokens, make M calls a second, and cost X pounds, per window, and then it stops, whatever its own logic thinks it should do next. That is a number a risk committee can sign off. “We trust the model not to loop” is not.
Put the budget where the agent cannot reach it, meter the three things that actually run away, and make the denial mean stop. An agent that fails closed at a known limit is one you can deploy. An agent that fails open is one you are lending your chequebook to and hoping it behaves.
Build and rescue work
Hands-on delivery of this kind is handled by Sixteen Pillars Studio.
Free interactive tool
Interactive deadline calculator
Check which regulations apply to you and when
Regulation across the EU, UK, US and Asia-Pacific has moved considerably in the past eighteen months, and several headline dates have shifted more than once. Twelve questions, about three minutes.
Results are shown on screen — no email required. A dated summary is available to download, and can be sent on if that's more useful. What we do with your answers.
Governance is what happens when nobody is watching.
Policies are easy. Consistent decision-making is harder. Understand where governance exists and where it has quietly become assumed.
Full Governance by Sixteen Pillars
Govern your business. Prove your compliance.
A board assurance cockpit for EU-regulated financial firms — tamper-evident, hash-chained proof of governance across DORA, GDPR, NIS2, ISO 27001, the EU AI Act and MiCA. In development.
See what's coming