How to Stop an AI Agent From Burning Money Overnight
PublicDecember 2, 20268 min read

How to Stop an AI Agent From Burning Money Overnight

Unattended AI agents can loop all night and run up a huge API bill. Here is how to cap every run with turn and dollar limits, catch loops early, set an account-level backstop, and trace exactly which steps burned the tokens.

Share:XLinkedIn

You start a coding agent before bed, give it a long task, and close the laptop. In the morning the task is half done and the API bill is not. This week a developer on r/LLMDevs posted a thread titled "Woke up to a massive bill after an unattended agent loop burned tokens all night". It's a common story, and it's very preventable.

The short answer: an unattended agent needs limits at three levels. Cap every run (turns and dollars), catch loops before they repeat all night, and put an account-level spend limit underneath as a backstop. Then log the cost of every step, so the morning after you know exactly what burned the money.

If you want a refresher on the loop itself, I walked through it in my video Anatomy of AI Agents: How They Actually Work. Everything below is about putting a meter on that loop.

Why do unattended agents get so expensive?

Because every turn of the loop pays for the whole conversation again. On turn one the agent sends the system prompt, the tool definitions and your task. On turn forty it sends all of that again, plus every tool result, test log and diff from the thirty-nine turns before it.

Let's put rough numbers on it. Say the context starts at 50,000 tokens and grows by 5,000 tokens per turn. Turn 100 alone sends 545,000 tokens, and the whole run adds up to about 29.75 million input tokens. Prompt caching makes most of that much cheaper, but only while the cache stays warm (more on that below).

Now add the failure mode that actually causes the overnight bill: a loop. The agent runs a test, the test fails, it makes a small edit, the test fails the same way, and it tries again. Nothing crashes, so nothing stops it. Each attempt is a little more expensive than the last, because the context keeps growing.

How do you cap a single run?

Give every unattended run two limits: a maximum number of turns and a maximum spend. The turn limit catches "it went round and round". The dollar limit catches "each turn got expensive".

Most agent tools already have the first one. Here is what the documentation says for three common ones:

ToolTurn limitDollar capWhat happens at the limit
Claude Code (print mode, -p)--max-turns (no limit by default)--max-budget-usdThe run stops
OpenAI Agents SDKmax_turns on Runner.runTrack it yourselfRaises MaxTurnsExceeded, or returns your fallback via error_handlers
LangGraphrecursion_limit (default 10,007 super-steps since 1.1.4)Track it yourselfRaises GraphRecursionError

Look at that LangGraph default for a second. Ten thousand steps is a safety net against infinite recursion, not a budget. If you never set it, your agent effectively has no turn limit.

In Claude Code, an overnight run might look like this:

claude -p --max-turns 40 --max-budget-usd 5.00 "Fix the failing tests in tests/api and summarise what you changed"

Two details from the Claude Code docs matter here. The budget is checked against Claude Code's own client-side cost estimate, which can differ from your bill, and spend can go past the cap, so leave headroom. Spend from subagents counts towards it too.

In the OpenAI Agents SDK, set the limit and decide what the user gets back when it's hit:

from agents import Agent, Runner, RunErrorHandlerInput, RunErrorHandlerResult

agent = Agent(name="Fixer", instructions="Fix the failing tests.")

def on_max_turns(_data: RunErrorHandlerInput[None]) -> RunErrorHandlerResult:
    return RunErrorHandlerResult(
        final_output="Stopped at the turn limit. Partial progress is in the log.",
        include_in_history=False,
    )

result = Runner.run_sync(
    agent,
    "Fix the failing tests in tests/api",
    max_turns=40,
    error_handlers={"max_turns": on_max_turns},
)

In LangGraph, pass recursion_limit as a top-level config key, not under configurable:

graph.invoke(inputs, config={"recursion_limit": 60})

How do you choose the numbers? Run the task normally a few times, note how many turns and how much money it takes, and set the limits at roughly twice that. Too tight and you kill useful work. Too loose and the limit never fires.

How do you add a dollar cap when the framework doesn't have one?

Build a small budget guard. Every model response already tells you how many tokens it used, so the guard only has to multiply by your prices and keep a running total. Think of it like a taxi meter that you check before every new ride, not after.

class BudgetExceeded(Exception):
    pass

class BudgetGuard:
    def __init__(self, max_usd, price_per_million):
        self.max_usd = max_usd
        self.prices = price_per_million  # e.g. {"input": ..., "output": ..., "cache_read": ..., "cache_write": ...}
        self.spent = 0.0

    def record(self, usage):
        cost = sum(usage.get(kind, 0) * self.prices[kind] / 1_000_000 for kind in self.prices)
        self.spent += cost
        if self.spent >= self.max_usd:
            raise BudgetExceeded(f"Spent ${self.spent:.2f} of ${self.max_usd:.2f}")
        return cost

Call record() after every model call, and stop the loop cleanly when it raises. This adds no meaningful latency, because it's a bit of arithmetic on numbers you already have. You can also track spend per ten minutes as a "velocity" check: a run that suddenly spends far faster than usual is often stuck.

Use your provider's real prices, including the cache read and cache write rates, or the guard will undercount.

How do you catch a loop before it runs all night?

A turn limit stops a loop eventually. A loop detector stops it early. A few simple signals work well:

  1. Repeated tool calls. Hash the tool name and its arguments. If the same call appears three or four times, stop and report.
  2. Repeated failures. If the same test fails with the same error after several edits, the agent is guessing. Stop.
  3. No progress. If several turns pass with no file changes and no new information, stop.
  4. Retries with a ceiling. Retry network and rate-limit errors with backoff, but cap the number of retries, so a provider outage doesn't turn into a retry storm.

None of these need another model call. That's the point: the check should be cheaper than the thing it protects.

What is the account-level backstop?

The per-run limits live in your code. If your code has a bug, you still want a hard limit somewhere else.

On the Claude API, the Start, Build and Scale tiers each carry a monthly spend cap, and you can set your own lower limit in the Claude Console. You can also set custom spend limits for individual workspaces. When a limit you set is reached, Anthropic's docs say requests return HTTP 400 with a message starting "You have reached your specified API usage limits" (or "workspace API usage limits" for a workspace limit).

One detail is worth knowing. The docs say a spend limit on the default workspace might not count or stop some usage, including the Console playground, Managed Agents sessions, and Claude Code used through a Console account in the default workspace. So give unattended agents their own workspace and their own API key, and put the limit there. That also means hitting the limit stops the agent without stopping everything else you run.

Whichever provider you use, check what its spend limits actually do: some stop requests, others only send an alert.

Why do pauses cost money too?

This one surprises people. Prompt caching only stays cheap while the cache is warm. Requesty, an LLM router, reported that Claude's default cache lives 5 minutes and every read restarts the timer, while GPT's default lasts at least 30 minutes on recent models.

While an agent is busy, requests arrive every few seconds and the cache stays warm. But if it waits, for a human approval, a slow CI job or a long rate-limit backoff, the cache can expire and the next turn pays the cache-write price on the whole conversation. Requesty reported that over 30 days of coding-agent traffic, 23.1% of the Claude bill went to rebuilding caches after the developer stepped away, and that one 8-minute break on a 210,000-token Opus 5.5 session turned a $0.04 cache read into a $1.05 cache write.

For unattended runs, that gives you two practical options. Avoid long idle waits inside a run, or choose Claude's 1-hour cache from the first request when you know there will be pauses. Requesty found that switching to the 1-hour cache in the middle of a warm conversation rewrote the whole prompt, so decide up front.

How do you find out what burned the tokens?

Log every step: the turn number, the tool called, input, output and cache tokens, the estimated cost and the running total. Write it to a file or your tracing tool as the run happens, not at the end, because a run that gets killed never reaches the end.

Then the morning-after question changes from "why is the bill so high?" to "turn 63 to 140 called the same test 77 times". That's a bug you can fix.

A checklist before you leave an agent running overnight

  1. Set a turn limit about twice the normal run length.
  2. Set a dollar cap per run, built-in or with a budget guard.
  3. Add loop detection for repeated calls, repeated failures and no progress.
  4. Cap retries, with backoff.
  5. Run it in its own workspace or project, with its own key and spend limit.
  6. Avoid long idle waits, or pick the longer cache up front.
  7. Log tokens and cost per step as you go.

The takeaway

An agent with no budget isn't autonomous, it's unsupervised. The model decides what to do next. Your harness decides how much it's allowed to spend doing it. I wrote more about that split in What Is Harness Engineering?, and spend limits are one of the easiest places to start.

References

Share:XLinkedIn

Related Articles

Comments

Sign in to join the conversation.

No comments yet. Be the first to share your thoughts!