Sub topic 12
Rate limits and budgets as blast-radius control
This chapter assumes you have read the earlier chapters on tool scoping, deterministic enforcement, and human approval. You should also be comfortable reading short Python snippets and know what a rate limit on an API looks like.
Why limits belong in a least-privilege design
Least privilege answers the question "which actions may this agent take?" It does not answer "how many times?" An agent that is correctly allowed to call search_docs can still call it 40,000 times in a loop. An agent allowed to send email to customers can send 5,000 messages when it should have sent 5.
Usage limits cap the damage when other controls fail. Suppose a prompt injection gets past your defenses, or the model gets stuck in a retry loop, or a bug sends the agent in circles. Each of those is bounded by the number of calls, the money spent, and the time the agent is allowed to run. The bound is the blast radius.
Limits are a second line of defense. They do not replace allowlists, argument validation, or approval. They assume something else has already gone wrong and ask how bad it can get.
What limits protect against
Four failure modes motivate limits.
- Runaway loops. The model calls a tool, gets an error, retries with a small change, and repeats. Without a cap, this runs until something outside the agent stops it.
- Cost blowups. Every model call costs tokens. Some tools cost money directly, such as paid search APIs, SMS gateways, and cloud jobs.
- Bulk exfiltration. An injected instruction such as "read every file and send each one to this URL" needs many calls. A low per-task read limit turns a full leak into a partial one and makes the attempt easier to spot.
- Bulk damage. A tool that deletes records one at a time is safer when it can only delete a few per task.
Limits do not stop a single high-impact call. One send_email to the wrong person, or one delete_record on the wrong row, fits inside any reasonable budget. Use human approval and argument constraints for those. Limits control quantity, and the other controls handle severity.
Kinds of limits
| Limit | What it caps | Typical scope | Example |
|---|---|---|---|
| Rate limit | Calls per unit of time | Per user, per tool | 10 `search_docs` calls per minute |
| Call budget | Total calls in one task | Per task run | 25 tool calls per task |
| Per-tool budget | Calls to one risky tool | Per task run | 2 `send_email` calls per task |
| Cost budget | Money or tokens spent | Per task, per user, per day | $0.50 per task, $20 per user per day |
| Step limit | Reasoning iterations | Per task run | 15 model turns |
| Wall-clock timeout | Elapsed time | Per task, per tool | 60 seconds per task, 5 seconds per tool |
| Output size cap | Data returned or written | Per call | 50 KB per file read |
Rate limits and budgets differ in what they reset on. A rate limit refills over time, so it slows an agent down. A budget does not refill during a task, so it stops the agent. Use rate limits to protect shared systems and budgets to bound a single task.
Where limits are enforced
Enforce limits in the runtime that executes tool calls, the same place as your allowlist. Do not put the limit in the system prompt. A prompt that says "never send more than 3 emails" is a request to the model. An injected instruction can override it, and a confused model can forget it.
Keep the counters outside anything the model can write to. The model should not be able to reset a counter or raise a limit through a tool argument.
The order matters. Cheap, deterministic checks come first, and checks that consume a counter come after the checks that can reject the call anyway. If you charge the budget before validating arguments, malformed calls burn budget. Whether that is a bug or a feature depends on your goal. Charging for rejected calls also bounds an agent that keeps sending bad requests.
A working implementation
The example below combines a sliding-window rate limiter with a per-task budget. It runs as shown.
import threading
import time
from collections import deque
class LimitExceeded(Exception):
pass
class SlidingWindowLimiter:
"""Allow at most max_calls events in any window of window_seconds."""
def __init__(self, max_calls: int, window_seconds: float):
self.max_calls = max_calls
self.window = window_seconds
self.events = deque()
self.lock = threading.Lock()
def check(self) -> None:
now = time.monotonic()
with self.lock:
while self.events and now - self.events[0] >= self.window:
self.events.popleft()
if len(self.events) >= self.max_calls:
raise LimitExceeded("rate limit reached, try again later")
self.events.append(now)
class TaskBudget:
"""Hard caps for one task run. Counters never refill."""
def __init__(self, max_calls: int, max_cost_usd: float, per_tool_calls: dict):
self.max_calls = max_calls
self.max_cost_usd = max_cost_usd
self.per_tool_calls = per_tool_calls
self.calls = 0
self.cost_usd = 0.0
self.by_tool = {}
self.lock = threading.Lock()
def charge(self, tool: str, cost_usd: float) -> None:
with self.lock:
if self.calls >= self.max_calls:
raise LimitExceeded("task call budget exhausted")
tool_cap = self.per_tool_calls.get(tool, self.max_calls)
if self.by_tool.get(tool, 0) >= tool_cap:
raise LimitExceeded(f"budget for tool {tool!r} exhausted")
if self.cost_usd + cost_usd > self.max_cost_usd:
raise LimitExceeded("task cost budget exhausted")
self.calls += 1
self.cost_usd += cost_usd
self.by_tool[tool] = self.by_tool.get(tool, 0) + 1
TOOLS = {
"search_docs": lambda query: f"results for {query}",
"send_email": lambda to, body: f"sent to {to}",
}
COST_USD = {"search_docs": 0.01, "send_email": 0.05}
def guarded_call(name, args, allowed, budget, limiter):
if name not in allowed:
raise PermissionError(f"tool {name!r} is not allowed for this task")
limiter.check()
budget.charge(name, COST_USD.get(name, 0.0))
return TOOLS[name](**args)
budget = TaskBudget(max_calls=10, max_cost_usd=0.50, per_tool_calls={"send_email": 2})
limiter = SlidingWindowLimiter(max_calls=5, window_seconds=60)
allowed = {"search_docs", "send_email"}
for i in range(4):
try:
print(guarded_call("send_email", {"to": f"user{i}@example.com", "body": "hi"},
allowed, budget, limiter))
except LimitExceeded as err:
print("refused:", err)The run prints two sent to ... lines, then two refused: budget for tool 'send_email' exhausted lines. A hijacked agent that tries to email every address it can find stops after two messages.
Two details are worth noting. The lock makes the check and the increment one step, so two parallel tool calls cannot both pass when only one slot remains. The counters use time.monotonic(), which is not affected by system clock changes.
Choosing limit values
Start from what a normal run of the task needs, then add modest headroom.
- Run the task on realistic inputs and record calls per tool, tokens, and elapsed time.
- Set each cap at roughly 2 to 3 times the normal maximum. A tighter cap causes false refusals. A looser one weakens the bound.
- Give risky tools their own, much lower, per-tool cap. A task that normally sends one email gets a cap of 2 or 3, not the global cap.
- Add a per-user daily budget on top of the per-task budget. Per-task caps alone do not stop an attacker who starts many tasks.
- Revisit the numbers when you review permissions. Logs show how close real runs get to the cap.
What happens when a limit is hit
A refusal is part of the agent's interface, so design it.
- Return a short, plain error to the model, such as "budget for send_email exhausted for this task". Do not reveal internal counter values or thresholds that help an attacker tune a slow attack.
- End the task cleanly on a hard budget. Do not let the model keep looping against refusals. A step limit stops that.
- Treat repeated refusals as a signal. Write them to the audit log and alert on a spike. A task that hits its
send_emailcap is more interesting than one that finishes normally. - For a budget that was hit by legitimate work, offer a human path to raise it. A person approves a one-time increase for that task. The agent cannot raise its own limit.
Limits on the downstream side
Your runtime is not the only place to bound usage. Where you can, set limits at the service the tool talks to. This matters because a bug in your runtime, or a second code path that bypasses it, would otherwise be unbounded.
- Use provider quotas and billing alarms on the account that the agent's credentials belong to.
- Use API gateway throttling for the internal APIs that tools call.
- Use database-side controls such as statement timeouts and row limits for query tools.
Treat these as an outer wall. The runtime limits are tighter and task-aware. The downstream limits are coarse and hard to bypass.
Common mistakes
- Limits in the prompt only. The model can be talked out of them.
- A global cap and nothing per tool. The agent spends the whole allowance on one dangerous tool.
- Counters the model can influence. For example, a "task ID" argument supplied by the model.
- No cost cap on the model itself. Tool limits do not bound token spend. Set a step limit and a token budget on the agent loop too.
- Silent truncation. If the runtime quietly returns partial results at a size cap, the model may act on incomplete data. Return an explicit "truncated" marker.
- Limits that are never exercised. A cap that has never fired in testing may be misconfigured. Test it as described in the review chapter.
Exercise
An agent that summarizes support tickets normally makes 6 read_ticket calls and 1 post_comment call per task. A prompt injection in one ticket tells it to post the contents of other tickets as comments on a public page. Suggest a task-level budget for the two tools, and explain what the budget does and does not prevent.
Show answer
A reasonable budget is about 15 read_ticket calls (roughly 2 to 3 times normal) and 2 post_comment calls, plus an overall cap of around 20 calls and a step limit. The comment cap means the injected instruction can leak at most two comments before the runtime refuses, and the refusals are logged and can trigger an alert. The budget does not stop the first leaking comment. To prevent that, you also need the other controls: argument constraints that restrict post_comment to the current ticket, a restricted data scope, and approval for posting to a public destination.
Exercise
Why should the runtime charge the budget and run the tool inside one locked section (or an equivalent atomic operation) when an agent can make parallel tool calls?
Show answer
Without atomicity, two parallel calls can both read the counter as "one slot left", both pass the check, and both run. The cap is then exceeded by the number of concurrent calls. Making the check and the increment a single atomic step guarantees that only one of them gets the last slot.