Module 07 · Lesson 7.5
Budget Limits, Rate Limits and Runaway Execution Controls
On this page
- What you will learn
- Why AI agents run away: loops, retries and big contexts
- Limits for one run: steps, model calls and size
- Rate limits: how many runs per minute?
- Fail closed with a clear message
- A budget and a rate limiter in Python
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Picture a tap left running in an empty flat. Nothing breaks for a while. Then the bill arrives, and the neighbours below are knocking on the door. Nobody wanted the water to flow, but nobody built anything to turn it off.
An AI agent can leave a tap running in the same way. A loop that never ends, a failing call that is retried again and again, or one visitor sending a thousand requests can all cost real money. This lesson shows how to add shut-off valves: budgets for one run and rate limits for many runs. Most of it needs no coding, and a short Python example makes the ideas concrete.
What you will learn
- Name the common causes of runaway agent runs: loops, retries and very large contexts.
- Set caps for steps, model calls, rough size and runs per minute.
- Explain how a fixed-window rate limiter works in plain words.
- Run a Python budget and rate limiter that fail closed with a clear message.
Before you start
- Module 3 and Module 5, especially Tool Errors, Retries, Timeouts and Idempotency and ReAct-Style Reasoning and Acting Patterns.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
Why AI agents run away: loops, retries and big contexts
A normal program does the same number of steps each time. An agent chooses its own steps, so nobody can say in advance how many it will take. Most runs are short. A few are not, and those few can cost more than all the others together.
A runaway run is a run that keeps going far past what the task needs. Here are the usual causes:
| Cause | What happens | Quillfeather example |
|---|---|---|
| A loop | The model keeps asking for one more tool call. | It searches the help centre again and again with slightly different words. |
| Retries | A failing call is tried over and over. | The order lookup times out, and the agent retries without a limit. |
| Growing context | Each step adds text, so each model call is larger than the last. | Ten search results are pasted in before every new question. |
| Too many callers | One user or one script sends a flood of requests. | A script asks "Where is QF-1042?" three thousand times in a minute. |
| Agents calling agents | Two agents pass the same case back and forth. | See Avoiding Infinite Loops and Unnecessary Agent Handoffs. |
That last point matters for security. Sending huge inputs or many requests to drain a service's budget is an attack. OWASP lists it as LLM10:2025 Unbounded Consumption (opens in a new tab). Costs can also climb by accident, as described in How to Reduce AI Token Costs When Coding with Claude or ChatGPT.
Limits for one run: steps, model calls and size
A budget is a fixed allowance for one run. When the allowance is used up, the run stops. You can set several budgets at once, and the first one reached ends the run.
| Limit | What it counts | Quillfeather value |
|---|---|---|
MAX_ROUNDS | Steps of the agent loop, as in the earlier labs | A small number, for example 5 |
MAX_MODEL_CALLS_PER_RUN | Every call to the model, including retries and checks | 6 |
| Input size limit | Characters or rough tokens in what the user sends | A few thousand characters |
| Time limit | Seconds one run may take in total | Set by your service |
| Spend limit | Money one run, one user or one day may use | Set from a real budget |
Steps and model calls are not the same
You already know MAX_ROUNDS from How Tool Calling Works. It counts trips round the agent loop. A budget on model calls is stricter, because one round can hide several model calls: a retry after a failed check, a grounding check, or a helper model. Counting every call to the model closes that gap.
Tokens: a rough guide
A token is a small piece of text, often a short word or part of a word. Models are billed and limited by tokens, not characters. You do not need an exact count. A rough size cap, such as a maximum number of characters sent per call, already stops the worst cases. Managing Context Windows and Conversation History shows how to keep the context small in the first place.
Rate limits: how many runs per minute?
A budget limits one run. A rate limit limits how often runs start. It is like a doorman at a small cafe who lets in ten people a minute. The eleventh waits outside, however polite they are.
Quillfeather's limit is MAX_RUNS_PER_MINUTE = 10. Keep the count per user, or per address if you have no users, so one noisy caller cannot use up the allowance of everyone else.
The fixed-window method
The simplest method is the fixed window. Cut time into one-minute slots. Count the runs in the current slot. If the count reaches the limit, refuse. When a new minute starts, the count starts again from zero.
- Run arrives
Which minute is it?
- Read the count
Runs so far for this user and minute
- Under the limit?
Yes: add one and allow. No: refuse.
- New minute
The count starts again at zero
Each minute is a new window with a new count.
A fixed window has one weakness. A caller can send ten requests at the end of one minute and ten more at the start of the next, so twenty arrive within a few seconds. For many agents this is fine. If it is not, look up the sliding window and token bucket methods, which smooth this out.
Fail closed with a clear message
What should the agent do when a limit is reached? Fail closed: stop the risky activity and do nothing more. The opposite, failing open, would be to let the run continue because "it is probably fine". A door that locks when the power fails is failing closed.
- Stop at once. Make no more model calls and no more tool calls in this run.
- Say why, kindly. For a refused request: "We are getting a lot of questions right now. Please try again in a minute." For a stopped run: pass the case to a person with the safe handover reply from the Module 4 lab.
- Do not leave half-done work. If a write step was in progress, apply the approval and idempotency rules from earlier lessons, so nothing happens twice.
- Log the stop. Record which limit was reached, the run id and the time. Leave out personal data. See Data Privacy, Sensitive Information and Secure Logging.
Limits also need watching. If many runs hit the cap, the cap may be too low, or something upstream is broken. Monitoring Quality, Failures, Latency and Cost shows how to track this.
A budget and a rate limiter in Python
The script below has two small classes. Budget counts model calls for one run and stops it at 6. RateLimiter allows at most 10 runs per user per minute. To keep the output the same every time, the limiter does not read a clock. The times are passed in as plain numbers, as if they were seconds on a clock.
MAX_MODEL_CALLS_PER_RUN = 6
MAX_RUNS_PER_MINUTE = 10
class BudgetExceeded(Exception):
pass
class Budget:
def __init__(self, max_calls=MAX_MODEL_CALLS_PER_RUN):
self.max_calls = max_calls
self.calls = 0
def count_call(self):
if self.calls >= self.max_calls:
raise BudgetExceeded(f"stopped after {self.calls} model calls")
self.calls += 1
class RateLimiter:
def __init__(self, limit=MAX_RUNS_PER_MINUTE):
self.limit = limit
self.counts = {} # (user, minute number) -> runs so far
def allow(self, user, now_seconds):
key = (user, now_seconds // 60)
if self.counts.get(key, 0) >= self.limit:
return False
self.counts[key] = self.counts.get(key, 0) + 1
return True
budget = Budget()
try:
while True: # a runaway loop: the model keeps asking for one more search
budget.count_call()
except BudgetExceeded as problem:
print("Run 1:", problem, "-> hand over")
limiter = RateLimiter()
answers = [limiter.allow("user-7", second) for second in range(12)]
print("Seconds 0-11:", answers.count(True), "allowed,", answers.count(False), "refused")
print("Second 61:", limiter.allow("user-7", 61))
print("Other user, second 5:", limiter.allow("user-8", 5))Runs offline with any Python 3.10 or later. Save it and run python budget.py.
What each part does
MAX_MODEL_CALLS_PER_RUNandMAX_RUNS_PER_MINUTEare the two limits from this lesson, written once at the top so they are easy to find and change.class BudgetExceeded(Exception)makes a special kind of error. Naming it lets other code catch this problem and nothing else.class Budgetis a class, a blueprint for an object that holds its own data. Each run gets its ownBudget, with its own count inself.calls.count_call()is called before every model call. If the count has reached the limit, it raisesBudgetExceeded. Otherwise it adds one. The check comes first, so the seventh call never happens.class RateLimiterkeeps a dictionary calledcounts. Its key is a pair: the user and the minute number.now_seconds // 60divides by 60 and drops the remainder. Seconds 0 to 59 give 0, and seconds 60 to 119 give 1. That is the fixed window.allow()returnsFalsewhen the user already used the limit in this minute. Otherwise it adds one and returnsTrue.- The
while Trueloop is a runaway agent on purpose. It never stops by itself, andBudgetstops it. - The last lines send twelve requests in twelve seconds, then one at second 61 (a new window), then one from a different user.
Run 1: stopped after 6 model calls -> hand over
Seconds 0-11: 10 allowed, 2 refused
Second 61: True
Other user, second 5: TrueThe runaway loop stops at six calls. The first ten requests pass, and the next two are refused. A new minute opens the door again, and another user has their own count.
Conclusion and your next step
Agents choose their own steps, so you must cap them. Use a budget for one run (steps, model calls, size, time and spend) and a rate limit for how often runs start. Count in code, fail closed when a limit is hit, tell the user kindly and log the reason.
Your next step: write down the five limits for an agent you are designing, with a number and a reason for each. Then continue to Human Review for High-Impact Actions, where you decide which actions are too important for the agent to take alone.
Want more? Read Output Validation and Policy Enforcement to see why a retry should be limited to one, or the Agent Launch Safety Checklist for a final pre-launch review.
Common errors and how to fix them
The agent still runs too long even with MAX_ROUNDS set.
Why it happens: Retries, grounding checks and helper calls add model calls that the round counter does not see.
Fix: Count every model call with a Budget, and keep MAX_ROUNDS as well.
Real customers are refused during a normal busy hour.
Why it happens: The rate limit was set from a guess, or counts all users together.
Fix: Measure normal traffic, set the limit above it, and count per user.
The limit check runs after the model call.
Why it happens: The count is raised after the money is already spent.
Fix: Check and count before each call, as count_call() does.
Users see a raw error when a limit is hit.
Why it happens: The BudgetExceeded error is not caught, or no friendly reply was written.
Fix: Catch the error where the run starts, and return the handover or the "try again in a minute" message.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a size cap and a second limit to the budget
Extend the Budget class so it also stops a run when the total characters sent to the model pass 4000. Add a method count_chars(text), raise BudgetExceeded with a clear message, and test it with three texts of 1500 characters each.
You will need
- The Budget class from this lesson.
- A new limit named MAX_CHARS_PER_RUN = 4000.
- Three test texts, each made with "x" * 1500.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Add
self.chars = 0in__init__. - Compare
self.chars + len(text)with the limit before you add anything. - Catch the error in your test and print the message.
Show a model answer
Add MAX_CHARS_PER_RUN = 4000 at the top and self.chars = 0 in __init__. In count_chars(self, text), compute new_total = self.chars + len(text). If new_total > MAX_CHARS_PER_RUN, raise BudgetExceeded(f"stopped: {new_total} characters is over the limit of {MAX_CHARS_PER_RUN}"). Otherwise set self.chars = new_total. With three texts of 1500, the first two reach 3000 and pass, and the third would reach 4500 and is refused. Checking before adding matters, because it is the same rule as the model call count: refuse first, spend second.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: A. Hidden extra calls are where costs creep in. The third option is tempting because models do lose count, but that is a reason to count in code, not a reason to count calls instead of rounds.
Show the answer and explanation
Answer: B. Failing closed protects the budget and other users. Running it anyway makes the limit pointless, and asking the model brings back the weakness of rules that only live in the prompt.
Show the answer and explanation
Answer: B. Code counts exactly and cannot be talked out of the rule. An instruction is a request that the model may forget, and a browser can be changed by the person using it.
Frequently asked questions
What is a runaway AI agent?
It is an agent run that keeps going far past what the task needs, for example by looping on tool calls or retrying forever. It wastes money and time, and it can hit provider limits. Caps on steps and model calls stop it.
How do I stop an AI agent from looping forever?
Put a hard limit on the number of steps and on model calls, counted in code. When the limit is reached, stop and hand the case to a person with a clear message. Also look at why it looped, for example a tool that keeps failing.
What is the difference between a budget and a rate limit?
A budget limits what one run may use, such as six model calls. A rate limit limits how often runs may start, such as ten per minute for each user. You normally need both.
What does fail closed mean?
It means that when something goes wrong, the system stops the risky action instead of carrying on. A budget that is used up ends the run. A rate limit that is reached refuses the request. Failing open would let the work continue and is usually the more dangerous choice.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- LLM10:2025 Unbounded Consumption(opens in a new tab)
OWASP Foundation · Official documentation · Describes how unlimited use of an LLM application leads to cost, denial of service and abuse.
- OWASP Top 10 for LLM Applications(opens in a new tab)
OWASP Foundation · Official documentation · The full list of risks covered in this module.
- Rate limits(opens in a new tab)
Google · Official documentation · Explains that providers apply request limits to accounts. Check it for your own limits.
- Building effective agents(opens in a new tab)
Anthropic · Official documentation · Discusses giving agents a way to stop, including an upper bound on how many loops they may run.
- Python tutorial: classes(opens in a new tab)
Python Software Foundation · Official documentation · Background for the `class` lines in the example.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.