← all articles

Spend alerts before a runaway loop drains credit

The invoice nobody forecast

Most AI cost problems are slow. A feature gets more popular, prompts grow a little, and the monthly bill creeps up. Forecasting handles that, and so does tracking cost per customer. This piece is about the other kind: the fast one.

A retry loop that never gives up. An agent that keeps calling tools because its stop condition never fires. A scheduled job that runs every minute instead of every day because someone typed the cron expression wrong. A leaked API key that someone else is now using. A test script left running over the weekend against the production key.

Each of these can spend in hours what you’d normally spend in weeks. None of them shows up in a forecast, because none of them is normal usage. And by the time the monthly invoice arrives, the money is gone.

The defence is guardrails that notice abnormal spend quickly and stop it, or at least tell someone, before it gets large. Those guardrails live in three places: your provider’s account settings, your own code, and your alerting. Each catches things the others miss.

The short version: set a hard cap you can live with at the provider, put budgets and circuit breakers in your code, alert on the rate of spend rather than the total, and make sure the alert reaches a person who can act on it.

How loops turn into bills

It’s worth understanding the common patterns, because each one suggests a specific guardrail.

Retry storms are a very common one. A call fails, the code retries, and it fails again. If the retry has no limit, or the limit is high and there’s no backoff, the code hammers the API. If the failure is caused by the input, such as a prompt too long for the context window, every retry fails the same way. Some errors are billed and some aren’t, depending on the provider and the error, but even unbilled failures can be followed by successful calls on a fallback path that are billed.

Agent loops are the second pattern. An agent works in steps until it decides it’s done. If it never decides, because the task is impossible, the tool keeps returning errors, or the model is confused, it keeps going. Each step resends the growing context, so the cost per step rises as the loop continues.

Fan-out bugs are the third. A job meant to process ten items processes ten thousand, because a filter was wrong or a query returned everything. Each item is a normal-sized call, and there are far too many.

Scheduling mistakes are the fourth: jobs that run too often, or overlap because each run takes longer than the interval.

And leaked keys are the fifth, where the spend isn’t yours at all.

The damage formula, in letters

It helps to reduce a runaway to a simple formula, because it shows which guardrails matter most.

Say a runaway process makes R calls per minute, each costing C on average. It runs for T minutes before something stops it. The damage is R times C times T.

You can’t usually control R once a bug has started. A tight retry loop or a fan-out bug will make calls as fast as the API and your rate limits allow. C depends on the call: a short classification is cheap, an agent step with a long context is expensive, and C often grows over time in agent loops.

That leaves T, the time to detection and response, as the lever you control most. Every guardrail in this piece is really about shrinking T or putting a ceiling on the product.

Hard caps put a ceiling on the total, whatever T turns out to be. Per-key and per-task budgets put smaller ceilings on smaller units, so one runaway can’t consume the whole allowance. Rate-based alerts shrink T from days or hours to minutes. Kill switches shrink the gap between an alert and the spend stopping.

Now compare. A monthly total alert on billing data might leave T at many hours, or days. A rate alert on in-code metrics might bring it under an hour. A per-task budget brings it to the length of one task. The difference in damage is proportional.

Plug your own call rate and cost per call into the formula. It usually makes the case for rate alerts and per-task budgets on its own.

Hard caps at the provider

The first line of defence is the one you set in the provider’s console, because it works regardless of what your code does.

Many model providers let you set a spending limit on your account or organisation. When usage reaches it, further API requests are refused until the limit is raised or the period resets. Some also let you set limits per project, per workspace or per API key. The exact options vary by provider and change over time, so check the billing or usage settings for yours.

Prepaid credit acts as a cap too. If your account runs on prepaid credit and automatic top-up is off, requests stop when the credit runs out. That’s a blunt instrument, and it’s effective. If automatic top-up is on, check its limits, because an unlimited auto-recharge removes the cap entirely.

The trade-off with any hard cap is that it stops good traffic along with bad. If your production feature hits the cap on the last day of the month because of a genuine traffic spike, users see errors. So set the cap at a level that’s comfortably above normal usage and still well below the amount that would hurt.

A practical approach is to separate environments. Give development and testing their own keys or projects with low caps, since that’s a common place for runaway scripts to start. Give production a higher cap with generous headroom, backed by the in-code guardrails and alerts below.

Check the cap after any major change in usage, so it doesn’t turn into a surprise outage.

Soft alerts at the provider

Alongside hard caps, many providers have usage alerts: an email or notification when spend crosses a threshold.

Set several thresholds, not one. A single alert at the cap tells you only that you’ve hit it. Alerts at, say, a quarter, a half and three quarters of your normal monthly spend tell you how fast you’re getting there. If the half-way alert arrives on day four, something’s wrong.

Know their limits. Provider billing data is often delayed, sometimes by hours. An alert based on billing data may arrive well after a fast loop has already spent heavily. Provider alerts are good for catching sustained overspend and poor at catching a spike in real time.

Check where alerts go. By default, they often go to the account owner’s email. If the account owner is a founder who reads email twice a day, or a finance address nobody monitors, the alert does nothing. Route them to a shared channel or an on-call system where someone will see them.

And test them. Temporarily lower a threshold on a test project so it fires, and confirm the message reaches the right place. An alert that has never fired is an alert you don’t know works.

Soft alerts are cheap to set up and catch a lot. They’re not a substitute for guardrails in your code, because they’re slower and they don’t stop anything.

Per-key budgets and separation

API keys are a natural unit for budgeting, and separating them well limits the damage any one problem can do.

Use a separate key for each application, service or job, not one shared key for everything. That way, when spend spikes, the provider’s usage dashboard can show which key is responsible, and you can revoke or limit that key without affecting the others.

Where the provider supports per-key or per-project limits, set them. A batch job that normally spends a small amount each night gets a limit a few times that. An interactive feature gets a limit sized to its peak traffic. A developer’s personal key gets a low limit.

Where the provider doesn’t support per-key limits, you can enforce them yourself with a proxy or gateway. All calls go through a small service that tracks spend per key or per application and refuses calls once a budget is spent. Several open-source and commercial LLM gateways do this, and a simple one isn’t hard to build.

Rotate keys and remove unused ones. Old keys in forgotten scripts, departed employees’ laptops or public repositories are how leaked-key spend happens. A quarterly review of which keys exist and what uses them is worth the half hour.

Store keys properly: environment variables or a secrets manager, never committed to a repository. Many providers and code hosts scan for leaked keys and may revoke them automatically, but don’t rely on that.

Budgets inside the code

Provider caps and alerts are coarse. The finest-grained guardrails belong in your own code, where you know what each call is for.

The most useful is a per-task budget. Before a task starts, give it a limit in tokens or estimated cost. After each model call, add the usage reported in the response to the task’s running total. When the total crosses the limit, stop the task, record why, and return a partial result or an error.

Set the limit from data. Run a sample of normal tasks, look at the distribution of cost per task, and set the budget several times above the typical case. Tasks that hit it are worth reviewing, since they’re either unusually hard or broken.

Add per-user or per-customer budgets for features where users trigger model calls. A daily cap per user stops one account, whether a heavy user or an abuser, from consuming a disproportionate share. It also limits the damage if a user’s session gets stuck in a loop.

Then a global budget for the whole application, tracked in a shared store such as a database or a cache. If total spend in the last hour exceeds a threshold, the application can switch to a degraded mode: cheaper models, fewer features, or queuing non-urgent work.

All of this depends on recording usage per call, which most APIs make easy by returning token counts in each response.

Retry policies that don’t multiply cost

Since retry storms are such a common runaway, retry logic deserves specific care.

Limit the number of retries. Two or three is usually enough for transient errors. Unlimited retries are never right for paid API calls.

Use exponential backoff with jitter. Each retry waits longer than the last, with some randomness so many clients don’t retry in lockstep. Most provider SDKs include retry logic with backoff; check its defaults and whether they suit you.

Retry only errors that retrying can fix. Rate-limit errors and temporary server errors are worth retrying. Errors caused by the request itself, such as invalid parameters, content that exceeds the context window, or content policy refusals, will fail the same way every time. Retrying them wastes time and, for some error types, money.

Be careful with retries on validation failures. If your code calls the model, gets output that fails a schema check, and calls again, each attempt is a fully billed call. Cap those retries separately and low, and log the failures so you can fix the prompt or schema.

Watch for retry stacking. If your code retries, your SDK retries, and a queue system retries the whole job on failure, a single failing request can turn into many billed calls. Know every layer that retries and make sure the total is bounded.

And log every retry with its reason. A sudden increase in retries is often the first sign of trouble.

Circuit breakers for agents

Agents need their own guardrails, because their loops are open-ended by design.

Set a maximum number of steps. Every agent loop should have a hard limit on iterations, after which it stops regardless of whether it thinks it’s done. Pick a number comfortably above what normal tasks need.

Set a maximum number of tool calls, overall and per tool. An agent that calls the same tool with the same arguments several times in a row is probably stuck. Detect repeated identical calls and stop, or tell the agent it’s repeating itself.

Track the agent’s token use per task, using the per-task budget from earlier. Agent costs grow faster than linearly with steps, because each step resends the growing context, so a limit on steps alone may not be enough.

Handle tool errors explicitly. When a tool fails, return a clear error to the agent and count the failure. After a few consecutive failures, stop the task. Agents given a failing tool often keep trying variations indefinitely.

Watch wall-clock time as well. A task that normally finishes in a minute and has been running for twenty is worth stopping, whatever its step count.

For multi-agent setups, apply these limits at every level, and give the whole task a total budget shared across its sub-agents. Otherwise each sub-agent’s individual limit is reasonable while the total is not.

Degrading gracefully instead of stopping

A hard stop is the safest response to runaway spend and often the most disruptive. For customer-facing features, it’s worth having softer options ready.

Switch to a cheaper model. If spend is climbing fast and you’re not yet sure why, routing traffic to a smaller, cheaper model reduces the cost per call while keeping the feature working. Quality drops a little; the bill drops a lot.

Serve cached answers. If the feature has a response cache, extend its use or its freshness window temporarily. Repeat questions get answered without new calls.

Queue non-urgent work. Background tasks such as summaries, enrichment and batch analysis can be paused and resumed later without users noticing much.

Reduce limits. Lower per-user caps, shorten maximum output lengths, or disable expensive options like high-effort reasoning or web search until the cause is found.

Turn off optional features. If an AI feature is a nice-to-have rather than core, a flag that hides it is often better than showing errors.

Each of these should be a configuration change, not a code change. Build the switches before you need them, and document which to use in which situation. Under pressure, nobody wants to write and deploy new code to reduce spend.

Graceful degradation also helps with legitimate spikes. If a launch brings far more traffic than expected, degrading keeps the feature available within budget while you decide whether to raise the limits.

Alerting on rate, not total

The most important alerting change is to watch how fast money is being spent, not just how much has been spent.

A total-based alert fires when monthly spend crosses a threshold. A runaway loop that starts on day twenty may push you past it within hours, and the alert arrives after most of the damage. A loop that starts on day two might not trip it for days.

A rate-based alert compares spend over a short window, such as the last fifteen minutes or the last hour, with a baseline. If the last hour’s spend is several times the typical hour’s spend, something unusual is happening, and you hear about it within the hour.

To build it, record usage per call with a timestamp, aggregate it into short windows, and compare each window with the same window on previous days, or with a rolling average. Most monitoring systems can do this with metrics you emit from your code.

Set thresholds carefully. Legitimate traffic varies by time of day and day of week, so compare like with like. Start with a generous multiple of normal, then tighten it as you learn what normal looks like.

Break it down by key, application or feature. A spike in one feature can be invisible in the total if other features are quiet. Per-feature rate alerts catch it.

Rate-based alerts are the guardrail that actually catches a fast runaway in time. Provider billing alerts rarely can.

Making sure someone acts

An alert is only as good as the response to it, and that’s where many setups fail.

Decide who receives spend alerts and what they’re expected to do. For a small team, that might be whoever is on call. For a larger one, it might be the team that owns the feature. Write it down.

Make the alert actionable. It should say which key, application or feature is spending, how fast, compared with what baseline, and where to look. A message that says only “spend threshold exceeded” sends someone digging through dashboards at a bad time.

Give responders a quick way to stop the spend. A kill switch per feature, such as a configuration flag that disables model calls for that feature, lets someone act in seconds without a deploy. Revoking or disabling a key in the provider’s console is the blunt option, and it’s worth knowing exactly how to do it before you need to.

Decide in advance when to stop and when to investigate. For a spike in a background job, stopping first and investigating later is usually right. For a customer-facing feature, the trade-off is harder, and it helps to have agreed on it in calm conditions.

Afterwards, review what happened. Which guardrail caught it, which should have, and what would have stopped it sooner? Each incident usually suggests one more limit or one better alert.

Guardrails for scheduled and batch jobs

Batch and scheduled jobs deserve their own guardrails, because they run unattended and often process large amounts of data.

Cap items per run. A job that normally processes a few hundred items should refuse to process a hundred thousand without an explicit override. If the input query or file suddenly contains far more than usual, stop and alert rather than proceeding.

Prevent overlap. If a job runs every hour and one run takes longer than an hour, the next run may start while the first is still going, doubling the work. Use a lock so only one instance runs at a time.

Make work idempotent. Record which items have been processed, so a job that crashes and restarts doesn’t reprocess everything from the start and pay for it twice.

Add a dry-run mode. Before a new job runs for real, run it in a mode that counts the items and estimates the cost without calling the model. That catches a wrong filter or query before it costs anything.

Check the schedule. A cron expression that runs every minute instead of every day is an easy mistake. Log each run’s start time and alert if runs happen more often than expected.

And give each job its own key and budget. A batch job sharing a key with an interactive feature can exhaust the feature’s budget overnight, and the first sign is users seeing errors in the morning.

When the runaway is your users

Not every spike is a bug. Sometimes the spend comes from users, whether heavy legitimate use, automated scripts using your product, or deliberate abuse.

Free tiers and trials are the usual target. An AI feature available without payment is attractive to anyone who wants free model access, and some people will script it. The pattern often shows up as many new accounts, each using the maximum allowed, or a few accounts making requests at machine speed.

Per-user daily caps are the first defence. They bound what any single account can spend, and they’re the same budgets described earlier applied at the user level.

Rate limits per user and per IP address slow automated use. A person can’t type a hundred messages a minute; a script can.

Sign-up friction helps where free access is the draw. Email verification, blocking disposable email domains, and requiring a payment method for higher limits all make mass account creation harder.

Watch for patterns: identical requests from many accounts, unusually long prompts, requests unrelated to your product’s purpose, or heavy use from newly created accounts. Those are worth alerting on separately from overall spend.

And make sure your product’s terms allow you to limit or suspend accounts that abuse the service. When it happens, act on the account quickly and adjust the limits that let it happen.

Legitimate heavy users are a different case. They’re a pricing question, and the right answer may be a higher tier rather than a lower cap.

Leaked keys and other people’s spend

A leaked API key produces a runaway bill with no bug in your code at all, and it needs its own precautions.

Keys leak through public repositories, shared screenshots, client-side code, logs, error messages and chat messages. Once a key is public, it can be found and used quickly.

Never put provider API keys in client-side code, such as a web page or a mobile app. Anyone can extract them. Route calls through your own backend, which holds the key and applies your budgets.

Scan your repositories for secrets, both before commits and on existing history. Many code hosts provide secret scanning, and some providers participate in programmes that automatically revoke keys found in public repositories. Treat those as a safety net, not a plan.

Use keys with the narrowest scope the provider allows. If keys can be restricted to certain models, projects or IP ranges, use those restrictions.

Per-key limits matter most here. A leaked key with a low limit can only do limited damage. A leaked key on an account with no caps can run up a very large bill.

Watch for usage patterns that don’t match your application: models you don’t use, request volumes at odd hours, or traffic from a key you thought was retired. Those are signs someone else is using it.

If you suspect a leak, revoke the key first and investigate after. Rotating a key is a minor inconvenience compared with what a leaked one can cost.

Testing and development environments

A lot of runaway spend starts in development, not production, and a little separation prevents most of it.

Developers write scripts that loop over data, test agent behaviour, and experiment with prompts. Those scripts are often run against real APIs, sometimes with production keys, and sometimes left running.

Give every developer or test environment its own key with a low spending limit. If a test script goes wrong, it hits the limit and stops, and the only thing affected is the developer’s afternoon.

Use cheaper models for development where possible. Most prompt and pipeline work can be done with a small model, switching to the production model only for final checks.

Consider mock responses for automated tests. Unit tests that call a real model API on every run are slow, flaky and expensive. Recorded responses or a simple mock work for most tests, with a small set of integration tests that hit the real API deliberately.

Put a limit on batch scripts by default. A script that processes a dataset should process a handful of items unless told otherwise, so a mistaken run over the whole dataset requires an explicit flag.

And clean up. Scheduled jobs created for testing, old keys, and experimental deployments that are still running quietly add cost and risk.

What these guardrails can’t do

Guardrails reduce the damage from runaway spend. They don’t remove the need to understand your usage, and they have limits worth being honest about.

They can’t distinguish a legitimate spike from a bug by themselves. A successful launch and a retry storm look similar in the first hour. Rate alerts tell you something unusual is happening; a person still has to decide what.

They add some complexity. Budget tracking, gateways and circuit breakers are code that can have bugs of their own, such as a budget counter that never resets or a gateway that becomes a single point of failure. Keep them simple and test them.

Hard caps can cause outages. A cap set too low, or not updated after growth, will stop your application at the worst moment. Review caps whenever usage changes significantly.

Provider billing data lags. No guardrail based on the provider’s own usage figures can catch a spike in real time. That’s why the in-code tracking matters.

And none of this replaces forecasting or cost attribution. Those tell you what normal looks like, which is what every guardrail here compares against. The guardrails are for when things stop being normal.

A starter set for this week

If you have no spending guardrails today, here’s a set you can put in place in a few days.

At the provider: set an account-level hard cap comfortably above normal monthly spend. Set usage alerts at several thresholds. Route them to a shared channel and test that they arrive. Turn off unlimited auto-recharge.

For keys: create separate keys per application and per environment. Set per-key limits where supported, and low limits on development keys. Remove keys you can’t account for.

In code: log token usage per call with the feature and key. Add a per-task budget to any agent or multi-step workflow. Cap retries, use backoff, and don’t retry errors that can’t succeed. Add a maximum step count and repeated-call detection to agents.

For alerting: add a rate-based alert comparing the last hour’s spend with a baseline, broken down by feature. Include enough detail to act on.

For response: add a kill switch per feature, write down who responds, and know how to revoke a key quickly.

Then review in a month. Look at what fired, what didn’t, and what would have caught the problems you actually had.

We compare model API pricing and the billing controls each provider offers, including spending limits and usage alerts, at AI Tool Gazette.

for builders
Running agents or scrapers at scale?

AI pipelines that crawl, research, or automate the web hit rate limits and geo-blocks fast. Singapore Mobile Proxy runs real 4G/5G mobile IPs that carriers still trust.

see plans →
read on
More from the Gazette

Tool reviews, model and pricing news, and build guides for people shipping real things with AI.

browse all articles →