cd /news/ai-agents/how-to-build-an-ai-agent-kill-switch… · home › topics › ai-agents › article
[ARTICLE · art-175295] src=startupfortune.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

How to build an AI agent kill switch before a loop burns your budget

A three-layer kill switch — a dollar-based circuit breaker in a shared store, a halt flag checked inside the single function every tool call passes through, and short-lived scoped credentials with provider spend limits — is needed to stop runaway AI agents that step limits miss, according to a guide that cites Knight Capital's more than $440 million loss in roughly 45 minutes on August 1, 2012. The guide calculates that one stuck run resending a 120,000-token context every 20 seconds at an illustrative $3 per million input tokens burns about $65 an hour, or roughly $900 from 6pm to 8am, and $36,000 if the same input hit 40 customers' runs. It recommends timing a fire drill so that flipping the halt flag to the last tool call takes well under a minute.

recommendation

Put a dollar-based circuit breaker in a shared store, check a fail-closed halt flag in the one function every tool call passes through, and add short-lived scoped credentials with provider spend limits; time a fire drill to confirm a halt lands in under a minute.

more in playbook: Securing agents and AI tools
by read11 min views2 publishedNov 24, 2026
How to build an AI agent kill switch before a loop burns your budget
Image: Startupfortune (auto-discovered)

An agent stuck in a loop can spend more overnight than most startups budget for a month, and a step counter won't catch it. If you ship agents to customers, you need a way to halt them that works even when your own code is wrong.

  • A step limit only counts one run's steps, so it can't stop queued jobs, scheduled retries or sub-agents running alongside it.
  • One stuck run with a 120,000-token context, calling every 20 seconds, burns roughly $900 between 6pm and 8am at an illustrative $3 per million input tokens.
  • Layer one is a circuit breaker that tracks dollars per run in a shared store, so a retry can't restart with a fresh budget.
  • Layer two is a halt flag checked inside the single function every tool call passes through, and it should fail closed for anything that spends or writes.
  • Layer three is short-lived, scoped credentials plus provider spend limits, which stop the agent even if your wrapper code has a bug.
  • Run a fire drill and time it: from flipping the flag to the last tool call should take well under a minute.

Knight Capital lost more than $440 million in roughly 45 minutes on August 1, 2012, when a software fault kept firing orders into the market and nobody could stop it fast enough. If you're working out how to build an AI agent kill switch, that's the failure to design against. The SEC's 2013 order against the firm found that Knight's own attempt at a fix, pulling the new code from some of its servers, made the situation worse.

Your agent won't trade equities. It'll call a search API, send emails, write to a database or open pull requests, and it'll do it faster than you can read the logs, with your card attached. The mechanics are the same: something acting at machine speed and no tested way to make it stop.

Most teams have done one thing about this. They set a maximum number of steps: LangGraph's recursion limit, a max-turns option in an agent SDK, or a counter inside a while loop. Keep it. But it lives inside one process and counts one run's steps. It knows nothing about the other 39 runs hitting the same bad input, the job waiting in the queue, the retry scheduled for 90 seconds from now, or the sub-agent your agent spawned with its own counter starting at zero.

Here's what that costs. Say your agent resends a 120,000-token context on every step and a step takes about 20 seconds. That's three calls a minute and 21.6 million input tokens an hour. At an illustrative $3 per million input tokens, you're paying about $65 an hour before a single output token. Leave one stuck run going from 6pm to 8am and it has cost you around $900. If the same input reached 40 customers' runs, the morning bill is $36,000. That's arithmetic on assumed numbers, not an incident I'm reporting, so plug in your own context size and call rate. The result is rarely comforting.

How Does an AI Agent Kill Switch Actually Work Before You Deploy One How does an ai agent kill switch actually work is a question most founders answer wrong, because a UI button and a real hard stop are not the same thing. This piece breaks down credential revocation, payment-rail budget caps, and true human-in-the-loop gating, using Replit's 2025 production database deletion as the case study in what happens... - how to test AI agent kill switches - AI agent power stop button actually works

A step cap also counts the wrong thing. Fifty cheap steps on a 5,000-token context cost less than ten steps on a bloated one. Dollars are what hurt you, so dollars are what you should measure.

The fix is three layers that fail in different ways. The first stops one run from overspending. The second lets a human halt everything at once. The third works even when the first two are broken. You want all three, because each one covers a hole in the others.

Layer one: the AI agent circuit breaker pattern, per run #

The circuit breaker comes from Michael Nygard's book Release It!, which described it for calls between services: count failures, and once they pass a threshold, stop sending requests for a while. It has three states. Closed means traffic flows. Open means everything is refused. Half-open means a single test request is allowed through to see whether the problem has cleared. Agents need the same thing, with spend as the thing being counted.

Every LLM response reports its token usage, so you can convert each call into dollars as it happens. Write that figure to a shared store such as Redis, keyed by run ID, using an atomic increment. Shared matters. If your agent fans out into parallel sub-agents, they must all draw down one budget, not each carry their own.

Pick the cap from data. Take a week of successful runs, find the median cost, and set the breaker at about five times that. Too tight and you'll trip on legitimate long tasks. Too loose and the breaker is decoration. When it trips, the run stops, its state is saved, its status becomes something like halted_budget, and an alert goes to a human. Half-open is a person raising the cap or approving one probe run. Nothing resumes by itself.

Expensive tools deserve their own line item. An LLM call is only part of the bill: a paid search or scraping API, an SMS provider or a headless browser service can cost more per step than the model does. Add each tool's per-call price to the same run total, and give the priciest ones a sub-cap of their own, so a loop that hammers a $0.05 lookup 10,000 times trips the breaker at $500, not at the end of the month.

The most common hole is the retry. If your job runner restarts a failed run and the new attempt starts with a fresh counter, the breaker has done nothing. Budget state belongs to the logical task, not the attempt. Do the same at tenant level, with a daily dollar ceiling per customer, so one bad account can't drain you.

How to set max iterations for AI agent loop before it drains your budget In the worked example, one uncapped loop at 200 steps costs roughly $95, against about $0.34 for a healthy task, because every step resends the whole history. A dollar ceiling near $3 would have stopped that run, and sub-agents should share the parent's budget. - how to set max AI agent iterations - stop AI agent loops draining budget

Add two cheap tripwires beside the dollar cap. A wall-clock limit catches runs that are slow rather than expensive. A repeat detector hashes the tool name and arguments of each call and trips when the same hash appears three times in a row, which is what a stuck loop looks like from the outside.

Layer two: a global flag for AI agent emergency stop in production #

A breaker protects you from a run that's overspending. It does nothing when you decide, at 2am, that every agent should stop now because a customer's data is being mangled or a vendor is sending errors. For that you need a flag a human can flip.

Keep it in a fast shared store. A Redis key read costs about a millisecond, which is nothing next to an LLM call that takes seconds. Scope it so you don't have to choose between everything and nothing: one key for global halt, one per tenant, one per agent, one per tool. Then you can freeze outbound email without stopping read-only research.

Where you check it is the whole game. Don't put it in the prompt. A model told to stop when it sees a stop notice is a model you're trusting to cooperate. Put it in the one wrapper function that every tool call passes through, so the check runs in your code before the call goes out. Queue workers should check the flag when they pick up a job and again before scheduling a retry. If a path to a tool exists that skips the wrapper, that's your next bug.

Make it fail closed. If the flag store is unreachable, tools that spend money or write data should refuse to run. Read-only tools can stay open if you'd rather. Teams hate this choice until the first time the flag store and the runaway agent fail at the same moment.

Two details catch people. First, a request already in flight will finish and bill you, so give your HTTP client a cancellation token and abort it when the flag flips. Second, when you the queue, don't just clear the flag later and let the backlog pour out. Release it gradually, and make your tools idempotent, so a run halted halfway and resumed doesn't send the same email twice.

Layer three: revocable credentials, the real how to stop a runaway AI agent control #

Layers one and two both run inside code you wrote, which means a bug in that code can disable them. Credentials sit outside it.

The standard is simple. Give each run a short-lived token, around 15 minutes, scoped to the data and tools that task needs. The agent never holds a master key. When you revoke a token, or rotate a key, every call fails with an auth error within seconds, whatever the agent's code thinks it's doing. Make sure your retry logic treats a 401 or 403 as final. If it retries them, you've swapped a spending loop for an error storm.

Then set limits at the provider. The major LLM vendors let you cap spend per project or workspace in their consoles, and your email, SMS and search vendors have send or quota limits too. Set each one below the amount you could survive losing, not at the default. A provider-side cap is the last line, enforced by someone else's servers.

Replit's July 2025 incident shows why instructions aren't enough. Jason Lemkin, founder of SaaStr, said Replit's AI agent deleted a live production database during a code freeze he'd told it, repeatedly and in capital letters, to respect. Replit CEO Amjad Masad apologised publicly and the company said it would separate development and production databases. The agent had been told not to act. It also had the access to act. Only one of those is enforceable, and it's the credential.

Run the drill before you need it #

An untested kill switch is a guess. Knight's rollback was a procedure nobody had rehearsed under pressure, and it cost them. So rehearse yours.

In staging, start an agent with fake tools that is built to loop forever. Flip the global flag and time how long until its last tool call. Then reset, and time it again with only credential revocation. Write the two numbers down. A good target is under a minute for the flag and under five for revocation. If you miss, find out why: a worker with a cached flag value, a sub-agent outside the wrapper, a retry queue nobody checks.

Then settle who's allowed to pull it. Any on-call engineer, without asking permission, is the right answer. A false alarm costs minutes of downtime. Waiting for approval overnight costs the $900 from earlier, multiplied by however many runs are looping.

Make the alert useful at 3am. It should carry the run ID, the customer, the spend so far, the last five tool calls, and a link that resumes or kills the run. An alert that says only 'budget exceeded' sends someone digging through logs while the loop is still spending.

Log every halt with the run ID, which layer fired, and the spend at that moment. After a month you'll know whether your five-times cap is right, and you'll have something concrete to show a customer who asks what happens when your agent goes wrong.

Before you ship, check that the budget survives a retry, that every tool call goes through the flag check, and that a revoked token ends the run. Then work out your own overnight number from your context size and call rate. If it's bigger than the monthly limit set on your provider account, you know what to fix first.

Also read: How to Calculate Gross Margin by Customer Segment in an AI Startup • How to calculate days payable outstanding for startups without losing suppliers • How to Calculate CAC for a Marketplace Startup by Side, Not Blended

This article is posted in AI News, check it out for more related stories.

Join the discussion #

Open in the community → Almost there. Sign in and your reply posts straight away.

── more in #ai-agents 4 stories · sorted by recency
── more on @knight capital 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-build-an-ai-a…] indexed:0 read:11min 2026-11-24 · —