FlowKit

Capping the cost of an AI agent in n8n: circuit breaker and budget guardrails

Published 29 August 2026 · 6 min read

An AI agent that calls a language model has no built-in cost meter: it does what it's told, as many times as it takes, until the task is done or an error stops it. As long as volume stays low, that missing cap goes unnoticed. The day a traffic spike, a looping tool, or simply a busier month sends the bill off course, it's already too late — the money is spent. Our guide on tracking AI call costs in n8n covers logging that spend after the fact. This one goes further: how to actively prevent the runaway, with a real budget circuit breaker that cuts off the agent before the bill spirals.

A cost that can't be predicted in advance

The most common intuition — "we know the model's price, so we can estimate the cost" — doesn't hold for an agent that chains reasoning with tool calls. A study from the Stanford Digital Economy Lab, run with Microsoft Research and published in 2026 (arXiv 2604.22750, see on Google Scholar), measured token consumption across eight frontier models on identical agentic tasks. The result: on the same task, two runs can differ by up to 30x in tokens consumed — and the models themselves, asked to estimate their own cost ahead of time, are systematically wrong, with a weak correlation between the estimate and reality. An agent that queries a RAG search tool, retries a malformed request, or hits a longer-than-expected document can cost ten times more than the run next to it, with no signal warning you beforehand.

That unpredictability is the core of the problem: you can't just compute an average monthly budget and hope reality complies. You need a mechanism that reacts to actual spend, live, not a budget discovered blown after the fact next month.

Why tracking alone protects nothing

Logging every call — input tokens, output tokens, estimated cost — into a Supabase table, as described in our AI cost tracking guide, is an essential foundation. But a log is passive: it answers "what did we spend?", never "can we still spend?". A dashboard showing a rising curve stops nothing by itself; someone has to look at it, understand it, and cut the workflow manually — usually after the month ends, once the bill has already landed.

A circuit breaker flips that logic around: it's an active guardrail, checked before every costly call, that can interrupt the execution on its own.

The circuit breaker pattern, applied to budget

The circuit breaker is a classic software reliability pattern, popularized to protect a system from failing network calls by cutting off access to a service that fails too often, rather than keep hammering it for nothing. A literature review by Falahah, Surendro and Sunindyo ("Circuit Breaker in Microservices: State of the Art and Future Prospects," IOP Conference Series: Materials Science and Engineering, 2021, see on Google Scholar) formalizes its three states: closed (traffic flows normally), open (traffic is cut off outright, without even attempting the call), and half-open (a test call is allowed to check whether recovery is possible). The same reasoning applies almost as-is to an AI budget: instead of cutting off a failing service, you cut off an agent that has hit its spending cap — the underlying protection principle is identical.

Three layers of guardrail, not just one

Three different scales of protection matter here, and they complement each other:

  • Per execution: the AI Agent node's Max Iterations setting, covered in our guide to common AI Agent errors, bounds the number of tool round-trips inside a single execution. It stops a local infinite loop, but sees nothing of what happens across the day's other executions.
  • Per period (day or month): the budget circuit breaker described here, which reasons over cumulative spend across every execution and cuts off model access once the cap is reached.
  • Manual: a switch a human can flip in an emergency — an incident (prompt drift, a flooding attack) shouldn't have to wait for the budget counter to catch up.

Building the circuit breaker in n8n

The central piece is a Supabase table that carries both the counter and the state, updated through an atomic Postgres function — this is the technical detail that separates a real circuit breaker from a rough approximate counter:

create table budget_tracker (
  id text primary key,
  period_start date not null default current_date,
  spent_usd numeric(10,4) not null default 0,
  cap_usd numeric(10,4) not null,
  state text not null default 'closed'
);

create or replace function increment_budget(p_id text, p_amount numeric)
returns table(spent_usd numeric, cap_usd numeric, state text) as $$
  update budget_tracker
  set spent_usd = spent_usd + p_amount,
      state = case
        when spent_usd + p_amount >= cap_usd then 'open'
        else state
      end
  where id = p_id
  returning budget_tracker.spent_usd, budget_tracker.cap_usd, budget_tracker.state;
$$ language sql;

The key point: this increment and check happen in a single SQL statement, executed on the Postgres side. If the counter were read and then written back from two separate n8n nodes via a split SELECT/UPDATE cycle, two concurrent executions could both read a balance still under the cap before either had time to write its update — and both would pass, when only one should have been blocked. It's a variant of the same shared-state problem covered in our guide on n8n webhook idempotency: whenever several executions touch the same resource, only an atomic database-side operation avoids duplicates.

Inside the workflow, the sequence becomes:

  1. Right before the AI Agent node call, a Supabase node (or HTTP Request) calls increment_budget with the estimated cost of the upcoming call.
  2. An IF node checks the returned state: state = 'open' routes to the stop branch, state = 'closed' lets it through to the agent.
  3. On the stop branch, two options depending on context: a Stop and Error node (see our dedicated guide) for internal batch processing, where a clean, logged failure is acceptable; or a fallback reply with no model call for a public chatbot, where degrading gracefully beats breaking the conversation.
  4. At 80% of the cap, a parallel branch sends a preventive alert — for example in Slack, using our Slack AI bot guide — so you can act before the cutoff rather than discover it after the fact.

Automatic recovery: the half-open state

A circuit left open indefinitely stops being a guardrail and just becomes a broken service. Recovery needs to be automatic and predictable: a Schedule Trigger firing at midnight (or at the start of the month, depending on the cap's granularity) resets spent_usd to zero and flips state back to 'closed' for the new period. It's the equivalent of the classic circuit breaker's recovery test, simplified: instead of a one-off probe call, the time window itself acts as the reset timer.

Where to apply it first

This guardrail earns the most value on workflows exposed to traffic you don't fully control yourself: a public RAG chatbot like the one in the RAG Assistant Pack (€119), which can face a sudden spike of questions on any given day, or an automatic inbox triage flow like the one in the Inbox AI Pack (€79), exposed to an unusual influx of emails (spam, a viral campaign). In both cases, the circuit breaker doesn't replace cost tracking — it builds on top of it — but it turns a monthly budget from a hope into a kept promise.

In summary

An AI agent's cost isn't predictable in advance: recent research shows token consumption swings of up to 30x on an identical task, and the models themselves can't reliably estimate their own cost. Logging the spend (see our cost tracking guide) remains essential but stays passive. A budget circuit breaker — an atomic Postgres counter, a check before every call, a hard stop or graceful degradation once the cap is hit, automatic reset at the next period — turns that tracking into active protection, alongside Max Iterations protecting each individual execution. Three lines of defense, three different scales, and a budget that no longer drifts in silence.

FAQ

Frequently asked questions

What's the difference between tracking cost and a budget circuit breaker?

Tracking (logging every call into a table) answers "how much have we spent?", after the fact. A circuit breaker answers "can we still spend?", before each call, and can stop the workflow on its own. The two are complementary: tracking feeds the circuit breaker with data, but without an active stop condition, a cost dashboard never stops anything — it just records the drift.

How do you avoid race conditions when several executions draw on the same budget at once?

By handing the counter increment to an atomic PostgreSQL function (an UPDATE ... RETURNING) instead of a read-then-write cycle done from n8n itself. Two concurrent executions that each read the balance, compute a new total locally, and write it back can both pass a check that should have blocked one of them. A single SQL statement that increments and returns the state in one operation removes that race window, no matter how many n8n workers run in parallel.

Should the service stop completely once the budget is hit, or degrade gracefully?

It depends on the workflow. For internal batch processing (email classification, lead enrichment), a hard stop with Stop and Error is fine — nothing urgent is waiting on an immediate reply. For a chatbot exposed to visitors, a hard stop is a bad experience; it's better to fall back to a canned response ("this AI feature is temporarily unavailable, please try again later", or a reply with no model call) than to break the conversation outright.

Is the AI Agent node's Max Iterations setting enough as a budget guardrail?

No, it covers a different problem. Max Iterations bounds the number of tool round-trips inside a single execution — it stops an agent from looping endlessly on one call. A budget circuit breaker reasons at the level of a day or a month, across every execution: even if each individual run is clean and fast, a thousand clean runs in the same day can still blow past the intended budget. The two guardrails are complementary, not interchangeable.

Bundle FlowKit Complet

€269