HOW-TO GUIDE19 min read

AI Agent Cost Control: Stop Runaway Loops

A production agent needs hard runtime limits, not just a dashboard that tells you what it spent after the loop stops.

P
PADISO teamPublished 13 Oct 2026

AI agent cost control means setting enforceable limits on how long an agent can run, how much it can spend and when it must stop or ask for help. Use step ceilings, per-run token or dollar budgets, and circuit breakers together, then measure them in production. We build these controls into AI agents and automation, because a usage chart cannot stop a live agent from making its next call.

A runaway agent can keep making valid requests while repeating a failed task. The provider may return a successful response each time, even when the workflow is not getting closer to its goal. The practical fix is to put limits at several layers: inside the agent runtime, at the model gateway and around tools that can trigger repeated work. This guide shows how to implement those limits and test that they actually stop execution.

The risk is not limited to accidental loops. The OWASP GenAI risk description for unbounded consumption covers excessive resource use that can create financial and service impacts. A sound design treats spend, latency and repeated actions as runtime safety concerns, not only as items to review at month end.

What do you need before implementing AI agent cost control?

Start by mapping the actual path a request takes. A simple agent may call a model, use one search tool and return a result. A more involved workflow may call several models, run tools, delegate to sub-agents, retry failures and pass a growing transcript between each step. You cannot set a useful budget if you do not know which parts of the system can spend it.

Before changing code, gather the following:

  • A workflow map: Record each model call, tool call, retry, delegation and human approval point.
  • A cost boundary: Decide whether the limit applies per user request, agent run, customer, team or time period. Use more than one boundary where necessary.
  • A baseline: Capture model, input and output tokens, tool duration, call count, retries and the outcome for representative tasks.
  • A definition of done: Specify what counts as a successful result. “The model returned text” is not enough if the agent has not completed the business action.
  • A failure policy: Decide what the agent should do when it reaches a limit, a tool fails or the budget service is unavailable.
  • An owner: Name the team responsible for the limits, alerts, incident response and periodic review.

This baseline matters because limits that are too high leave room for runaway execution, while limits that are too low turn normal work into repeated interruptions. Start with observed workloads and a deliberate safety margin. Do not copy example thresholds from another company or framework and assume they fit your task.

Draw the system boundary too. If a user action can start two agents, and each agent can create more agents, the budget needs to cover the whole run tree. A per-agent limit alone may not bound total spend. Similarly, if your application retries a failed request after the agent runtime stops, the outer application can still multiply calls. Include queues, scheduled jobs, client retries and provider failover in the map.

A short inventory table makes gaps visible:

Boundary What to record Control to add
Agent run Steps, model calls, duration and total spend Per-run ceiling and deadline
Model call Model, input tokens, output tokens and estimated cost Gateway budget check and output limit
Tool call Tool, arguments, response status and duration Timeout, retry policy and repetition detector
Delegation Parent run, child runs and shared budget Propagated run identifier and aggregate cap
Tenant or team Usage across concurrent runs Rate limit and period budget

Step 1: Define the unit of work and its budget

Choose a unit that corresponds to something a person or system asks the agent to do. That is usually one user request, one queued job or one bounded business task. Give every unit a unique run identifier and carry it through model calls, tools, child agents and logs. Without this identifier, it is difficult to connect an expensive model request to the workflow that caused it.

Then define a budget with more than one dimension. A dollar cap is easy to explain, but it does not by itself constrain latency or tool activity. A useful per-run policy may include:

  • A maximum number of graph transitions or agent iterations.
  • A maximum number of model requests.
  • An input and output token ceiling, either separately or together.
  • A maximum estimated cost for the run.
  • A wall-clock deadline.
  • A maximum number of tool calls, with a smaller limit for high-risk tools.
  • A limit on retries and child-agent creation.

Treat these as independent limits. If an agent reaches its call ceiling before its token ceiling, it should stop. If it reaches the deadline with budget remaining, it should also stop. The first limit reached ends autonomous execution.

Set the initial values from traces of normal work. For example, if a workflow typically needs a few model turns and one or two tool calls, do not set an iteration ceiling in the hundreds simply because the framework allows it. At the same time, test a realistic complex case so your cap does not prevent legitimate completion. Record why each value exists and who can change it.

A budget should be allocated, not merely displayed. If a request can spend up to a certain amount, reserve that amount against the customer or team budget when the run starts. Release unused reservation when the run ends. If the application supports concurrency, make reservation and release atomic, so simultaneous requests cannot each observe the same remaining balance and overspend it.

For delegated work, decide whether child agents share the parent’s remaining allowance or receive smaller allocations from it. Shared budgets are easier to reason about: no child can spend beyond what remains for the overall task. Separate child budgets can be useful where teams need isolation, but the sum of those allocations must not exceed the parent limit.

Document what happens when a limit is reached. Common choices are to return a partial answer, ask the user to narrow the request, send the task to a human review queue or fail with a clear message. The right response depends on the impact of an incomplete result. Do not leave the agent to decide whether it should ignore a limit that the system is meant to enforce.

Step 2: Put a hard step ceiling in the agent runtime

A step ceiling limits how many times an agent can transition through its reasoning and action loop. It is the simplest defence against an agent that keeps taking another step without making progress. Use the runtime’s own mechanism where available, then add an application-level limit so the policy does not depend on a single library.

For LangGraph, the documented recursion_limit controls graph execution and an exceeded limit raises a recursion error. See the LangGraph documentation on graph recursion limits. Set the value for the specific workflow rather than relying on a general default:

config = {"recursion_limit": 12}

try:
    result = app.invoke(inputs, config=config)
except GraphRecursionError:
    result = {
        "status": "needs_review",
        "message": "The task reached its execution limit."
    }

The value above is an illustration, not a recommended universal setting. Test the appropriate ceiling against normal tasks, difficult but valid tasks, tool failures and loops. A framework step count may not equal a model call count: one graph transition might not call a model, while another node could trigger a separate retry. Track both.

Set the ceiling at the narrowest useful level. A research task and a simple classification task do not need identical limits. But avoid allowing a prompt or model output to raise its own limits. If an agent can decide that it needs unlimited extra steps, the boundary is not a boundary.

Apply the same thinking to sub-agents. Each child needs its own small limit, and the parent needs an aggregate limit across all children. Set a maximum delegation depth and maximum number of children. Otherwise a safe-looking limit on each agent can still create an excessive total number of model calls.

Handle tool errors as explicit outcomes

A common loop begins when a tool returns an error and the agent treats the error as evidence that it should try again. The response may be a timeout, rate limit, permission failure, malformed result or empty search response. Decide which errors are retryable and how many retries each gets.

For each tool, define:

  • Which status codes or error classes can be retried.
  • Whether the retry must wait, and how long.
  • The maximum retry count.
  • Whether the arguments must change before a retry.
  • When to stop and return a human-readable failure.

Do not retry a permanent error, such as invalid permissions, with the same arguments. For a temporary rate limit, use the provider’s retry guidance if available, apply a bounded delay and stop after the configured attempts. A tool should return a structured error that the orchestration layer can interpret, not a vague string that invites the model to improvise another attempt.

Check framework defaults rather than assuming they fail safely. Some libraries catch tool exceptions and turn them into observations for the agent. That can be useful, but it can also make a persistent failure look like a normal step. Make the error-handling behaviour explicit and test it. The agent should not be able to hide a failed tool call by converting it into an endless request for more context.

Step 3: Enforce token and dollar budgets at the gateway

Runtime limits protect the orchestration flow. A model gateway adds a central enforcement point between your application and model providers. It can apply policy consistently when several services use different models or when developers add a new agent. Our platform engineering team works on this kind of shared boundary, including gateways, identity and operational controls.

Create separate credentials or virtual keys for meaningful workloads, such as an agent type, environment or tenant. Avoid one shared key for unrelated production workflows. A per-workload identity helps you attribute usage, apply limits and revoke access without changing every application that uses the provider.

Set hard limits for the dimensions your gateway can enforce. These may include a budget over a defined period, a maximum spend per model, request rate limits and token limits per request. The LiteLLM proxy documentation for budgets, rate limits and virtual keys describes controls for managing proxy users and keys. Confirm the current behaviour and requirements in the version you deploy before treating a setting as a production safeguard.

A key design question is whether the gateway can reject a call before it reaches the provider. A dashboard that updates after a call is useful for reporting, but it cannot prevent that call from adding cost. Where the gateway supports pre-request checks, use them. If it only reconciles spend after a response, combine it with stricter runtime limits and a conservative local budget.

Do not assume that setting a budget field guarantees a hard stop. Check whether the gateway needs a database or another backing service to persist usage, how it behaves when that service is unreachable, how it calculates cost and whether limits apply across multiple gateway instances. A configuration that fails open during a database outage can look correct in a test and fail under the exact conditions where you need it.

Test the enforcement path directly:

  1. Create a test identity with a deliberately small budget.
  2. Send requests that should fit under the limit.
  3. Continue until the remaining budget is too small for another request.
  4. Verify the gateway rejects that request before it is sent upstream, if pre-execution enforcement is supported.
  5. Confirm the application stops, records the reason and does not retry the rejected request indefinitely.
  6. Repeat with the budget store unavailable and observe whether the system fails open or closed.

Choose fail behaviour according to the risk. For low-impact internal experimentation, a temporary fallback may be acceptable. For production workflows that can create financial or regulatory consequences, a failure to confirm remaining budget should usually prevent further autonomous work. Document any exception and keep an alert on it.

Step 4: Add circuit breakers for repeated or unproductive work

A circuit breaker stops a class of calls temporarily when the system sees a pattern that suggests it is failing. In conventional services, this often means repeated failures from a dependency. For agents, the pattern can also be repeated tool calls, recurring errors or spend that rises too quickly for the task.

A simple breaker has three states:

  • Closed: Calls are allowed and outcomes are recorded.
  • Open: Matching calls are blocked or diverted after a trip condition.
  • Half-open: A limited test is allowed after a cooldown to see whether the dependency or workflow has recovered.

For tool repetition, compare the tool name and normalised arguments. Normalisation means representing equivalent JSON arguments consistently, such as sorting object keys and removing fields that do not change the action. A repeated signature is a useful signal, but do not treat it as the only signal. A loop can change a small field each turn while still repeating the same failed intent.

Combine signals such as:

  • The same normalised tool call returning the same failure several times in a row.
  • The same tool being called repeatedly without a new observation or changed input.
  • Repeated model responses that request the same missing information.
  • A run using tokens or money at an unusual rate.
  • A child-agent chain reaching its depth or fan-out boundary.

Thresholds should be chosen from your own workload and treated as policy values you can adjust. For instance, a rule that trips after three identical failed calls can be a reasonable starting point to test, not a standard that fits every tool. A harmless read-only search can tolerate a different retry pattern from a payment, account update or bulk export.

Track breakers by workflow and tool. A single global breaker can block unrelated customers because one integration is failing. Conversely, a breaker scoped to only one process instance may not detect a tenant-wide storm. Choose the scope to match the failure: a broken dependency may need a shared breaker, while a repeated user request may need a per-run breaker.

When a breaker trips, do not simply throw an opaque exception. Stop autonomous execution and choose a safe fallback. You might return the verified partial result, state that the requested action could not be completed, offer a human review option or route the task to an operational queue. A cheaper model can help produce a short status message, but do not invoke another model automatically if the budget is exhausted. The fallback must not become a second path around the cap.

For actions that change money, records, access or customer outcomes, use a human approval gate before repeating an uncertain action. The agent must know whether the first attempt succeeded before trying again. Use idempotency keys where the external system supports them, so a retry cannot accidentally apply the same action twice.

AWS’s Agentic AI Lens guidance on agent cost controls and its cost control best practice are useful references for considering cost safeguards as part of system design. Adapt any pattern to your own architecture and test the failure paths.

Step 5: Stop context from compounding across turns

An agent often sends some version of its conversation history with each new model request. As tool outputs and prior messages accumulate, later requests can contain much more input than earlier ones. A loop can therefore become more expensive per turn, even if the model and output length stay constant.

Start by inspecting traces for input tokens by turn. Check whether the agent resends full tool results, duplicated instructions, old reasoning or large documents that are no longer relevant. Do not infer cost from the number of turns alone. The same number of turns can produce very different usage when context size varies.

Useful controls include:

  • Trim irrelevant history: Keep messages needed for the next decision, not every intermediate detail.
  • Summarise with care: Replace old observations with a concise, verifiable summary when the original material is no longer needed.
  • Limit tool output: Return only fields the agent needs. Paginate large results and require an explicit next page.
  • Store references instead of payloads: Keep a document or result in an application store and pass a stable reference where appropriate.
  • Set per-request token ceilings: Constrain both input construction and model output where the API supports it.
  • Use caching where it fits: Reuse stable prompt components when the provider and request pattern support caching.

A summary is not free and can lose important details. Keep the source available for verification, record what the summary excludes and test the agent on cases where an omitted detail changes the answer. For important business actions, preserve the evidence needed to explain why the agent made its decision.

Caching can reduce repeated processing of unchanged prompt content, but it is not a loop breaker. It does not stop an agent from issuing more requests, calling a failing tool or generating excessive output. Read the OpenAI API prompt caching guide for provider-specific behaviour and confirm current eligibility and pricing before relying on it in a cost estimate.

Step 6: Make the stop path safe and useful

When a limit is reached, the agent needs a defined end state. Decide in advance what the user sees, what the system records and whether the work can resume. If the only result is a generic error, people may repeatedly submit the same task, creating more load without understanding what happened.

A useful stop response should say, in plain terms, that the task stopped because it reached a safety or resource limit. It can explain what was completed, what remains uncertain and what the user can do next. Avoid exposing internal secrets, raw prompts or provider credentials in the message.

For work that can safely resume, persist the state needed to continue and require an explicit new run or approval. Do not silently restart from the beginning. A resume should have its own run identifier, inherit the original budget context and account for work already performed. Otherwise, a user-facing “try again” button can become an unbounded retry mechanism.

Use a different policy for side-effecting actions. If the system is unsure whether a tool completed an action, check the external system or send the task for human review before retrying. Do not let an agent repeat a payment, update or notification simply because it did not receive a clear response.

Log the stop reason as structured data. Useful fields include the run identifier, tenant, workflow version, policy limit reached, model and tool names, current usage, last tool result and whether a side effect may have occurred. Keep sensitive content out of general logs or apply the organisation’s data handling controls. These records help teams distinguish a legitimate complex task from a defective prompt, tool outage or policy that needs adjustment.

Step 7: Test the limits before production

Cost controls only work if they hold under failure. Add tests that deliberately try to cross each boundary, then verify the whole system stops rather than moving to another route.

Build a test set around realistic failure modes:

  • A tool returns the same error on every call.
  • A tool responds slowly and triggers timeouts.
  • A tool returns HTTP 429 or another retryable response.
  • A tool returns empty or malformed data.
  • The model repeats the same request with slightly different wording.
  • A parent agent repeatedly delegates to a child agent.
  • A model response is unusually long.
  • The gateway budget store is unavailable.
  • Two or more runs try to consume the same remaining budget concurrently.
  • The application client retries after the agent has already stopped.

For every test, check the model request count, tool call count, token use, estimated cost, elapsed time, user response and audit record. A test that only checks for an exception may miss a second request initiated by a queue worker or client retry.

Use deterministic mocks for control-flow tests, then run a small number of controlled integration tests against provider APIs. Put a low budget on test credentials and do not run open-ended experiments against a production key. Keep a kill switch available to disable a workflow or revoke its credentials if an incident is underway.

Run evaluations on both completion quality and restraint. The agent should finish valid tasks within the defined budget, stop invalid or looping tasks, and explain when it cannot proceed. Anthropic’s research on evaluating agents is a helpful reference for thinking about evaluations beyond a single final answer. Your tests should reflect your workflows, tools and acceptable failure behaviour.

Step 8: Observe cost and tune limits safely

Collect telemetry at the level of individual runs. At minimum, record the workflow name and version, model, input and output tokens, number of calls, tool retries, duration, estimated cost, result status and stop reason. Attach a correlation identifier across services so that gateway records, agent traces and tool logs can be joined.

Review both averages and outliers. An average can look healthy while a small number of runs consume most of the budget. Break results down by workflow, tenant, model, tool, software release and task outcome. Keep failed or abandoned runs in the analysis. Excluding them hides precisely the cases where cost controls matter most.

Set alerts for unusual usage, but do not confuse an alert with enforcement. A notification tells someone that a threshold was crossed; a hard limit prevents another request. Use alerts to investigate drift and tune policy, while keeping runtime and gateway controls in place.

When you change a limit, use a controlled release. Compare completion rates, manual review volume, cost per successful task and failure reasons before and after. If a cap blocks valid work, find out whether the workflow needs a better tool, less context, a clearer task boundary or a different model. Raising the ceiling should not be the automatic response to every incomplete task.

For Australian organisations, include AI runtime controls in operational risk discussions where the workflow affects important services. The right governance depends on the organisation and use case. Our AI strategy and solutioning service helps teams decide which controls, ownership and reporting belong in an AI operating model. If you are still assessing where to start, use the AI readiness test to identify gaps across capability and governance.

A practical implementation checklist

Before you release an agent, confirm each item:

  • Every run has a unique identifier that follows calls through models, tools and child agents.
  • The workflow has a tested step ceiling and deadline.
  • Model calls have token and cost limits appropriate to the task.
  • A gateway or equivalent enforces budget policy before new calls where possible.
  • Budget accounting works under concurrent requests and across application instances.
  • Tool retries are bounded, classified and observable.
  • Repeated tool signatures and unproductive patterns can trip a breaker.
  • Child agents inherit or receive a bounded share of the parent budget.
  • Limit responses do not automatically trigger another run.
  • Side-effecting actions have idempotency or human review controls.
  • The system has a defined behaviour if its budget service is unavailable.
  • Failure tests verify that no alternate path continues spending.
  • Logs show why a run stopped without exposing unnecessary sensitive data.
  • A named owner reviews usage, incidents and policy changes.

Common mistakes to avoid

Relying on provider account alerts alone. Alerts may arrive after requests have already consumed budget. Use them for visibility, not as your only stop mechanism.

Setting only a maximum number of retries. The model may make a new call without using the retry mechanism you limited. Set a total call or cost ceiling as well as retry-specific rules.

Giving every agent its own generous budget. Per-agent caps can add up quickly when agents run concurrently or spawn children. Enforce an aggregate run or tenant limit too.

Retrying every tool error. A permission error or malformed request will not become transient because the agent repeats it. Classify errors and make retries finite.

Treating a successful HTTP response as progress. A model can return a valid response that repeats a failed plan. Track business outcomes and repeated actions, not just status codes.

Making the fallback another autonomous loop. Switching models or delegating to a reviewer agent can still incur more cost. The fallback must use the same budget policy and must be allowed to stop.

Testing only the happy path. Limits are most valuable when tools fail, budget services disconnect or requests arrive concurrently. Test these conditions before release.

Where PADISO fits

We help teams design and implement production agent controls through AI agents and automation and platform engineering. A practical first step is to map one costly or high-risk workflow, trace its model and tool calls, then turn its budget and stop conditions into testable runtime rules.

Wrap-up: make stopping part of the design

A reliable agent knows when it is allowed to continue and what happens when it must stop. Put a step ceiling in the runtime, enforce a shared budget before model calls, and use circuit breakers to catch repeated or unusually costly work. Then test failure paths, observe outcomes and revise limits based on evidence rather than guesswork.

Choose one production workflow this week and write down its maximum steps, calls, spend and runtime. Then test a repeated tool failure and confirm the next model request is blocked when the limit is reached. If you want help turning those controls into an architecture and delivery plan, talk to PADISO.

WANT TO TALK THROUGH YOUR SITUATION?

Talk it through with us. Thirty minutes, no slides.

P
Written by the PADISO TeamSydney-based technology leaders who build what they advise on. Seven years of fractional CTO, architecture and AI work for enterprise, government and private equity.

Keep reading

All posts →

Let's talk.

Tell us what you are weighing up, whether it is a build, a roadmap or a deal. You will leave the call knowing your next step.

Book a 30-min callhi@padiso.co