This article was drafted with AI help and reviewed by the author.
An n8n AI Agent that gets stuck calling the same tool doesn't throw an error on the first loop. It just keeps calling the model. Run that on a busy webhook and the provider bill is the first alert you get.
Provider spend limits help, but they act on the whole account. They don't know that the support agent should stop while the invoice extractor keeps going.
This post builds a per-workflow daily budget for n8n. The idea is the same one a card terminal uses. Hold the worst case before the work starts. Settle the real amount when it ends. If you can't prove the real amount, keep the hold.
The SQL was parsed with a PostgreSQL parser (pglast, PostgreSQL 17 grammar). The two Code node scripts were run locally with a small stub for $() and $execution. None of it was run inside n8n or against a live database. All prices are placeholders.
Why "check the total, then run" isn't enough
The obvious gate reads today's spend, compares it to a limit, and lets the run through if there's room.
That breaks in two ways.
Concurrency. Ten webhook executions start in the same second. All ten read the same total. All ten see room. All ten run.
Unknown cost. At the moment you check, you don't know what this run will cost. An agent with tools might make one model call or eight.
A reservation fixes both. Each run claims its worst-case cost in one atomic database update. If the claim doesn't fit under the limit, the run doesn't start.
Work out the worst case
You can only reserve a worst case if the run has one. Three settings give it one.
- Max Iterations on the AI Agent node. n8n's Tools Agent has a Max Iterations option, and the docs list the default as 10. Set it on purpose. When the agent reaches it, the run stops instead of looping on.
- Max output tokens on the chat model sub-node. Each model call can now only write so much.
- A ceiling on input size. Trim conversation memory to a fixed window and cap how much retrieved text you pass in. Then measure the biggest prompt you actually send and use that number.
Worst case per run is then roughly:
``text (max iterations + 1) x (max input tokens x input price + max output tokens x output price) / 1,000,000 ``
The extra call is margin for the final answer. It's a deliberately pessimistic number. That's the point.
The ledger
Two tables. One row per budget per day, and one row per reservation.
```sql create table aibudgetledger ( budgetkey text not null, day date not null, limitusd numeric(12,6) not null, reservedusd numeric(12,6) not null default 0, spentusd numeric(12,6) not null default 0, primary key (budget_key, day) );
create table aibudgetreservations ( executionid text primary key, budgetkey text not null, day date not null, amountusd numeric(12,6) not null, settledusd numeric(12,6), created_at timestamptz not null default now() ); ```
budget_key is whatever you want to cap separately. One key per workflow is a good start.
Reserve, atomically
```sql create or replace function reserveaibudget( pkey text, plimit numeric, pamount numeric, pexecutionid text ) returns boolean language plpgsql as $$ declare vok boolean; begin insert into aibudgetledger (budgetkey, day, limitusd) values (pkey, currentdate, plimit) on conflict (budgetkey, day) do nothing;
update aibudgetledger set reservedusd = reservedusd + pamount where budgetkey = pkey and day = currentdate and spentusd + reservedusd + pamount <= limitusd; v_ok := found;
if vok then insert into aibudgetreservations (executionid, budgetkey, day, amountusd) values (pexecutionid, pkey, currentdate, p_amount); end if;
return v_ok; end $$; ```
The update only succeeds if the reservation still fits. Postgres takes a row lock for the update, so two concurrent reservations for the same key are applied one after the other. Under the default read committed level, the second one re-checks the where clause against the row the first one just wrote. That's what stops ten runs from all seeing the same room.
current_date uses the database session time zone. Set it to the zone your budget day should follow, or pass the day in from n8n.
Settle, once
```sql create or replace function settleaibudget(pexecutionid text, pactual numeric) returns void language plpgsql as $$ declare r aibudgetreservations%rowtype; begin select * into r from aibudgetreservations where executionid = pexecutionid and settled_usd is null for update;
if not found then return; end if;
update aibudgetledger set reservedusd = reservedusd - r.amountusd, spentusd = spentusd + pactual where budgetkey = r.budgetkey and day = r.day;
update aibudgetreservations set settledusd = pactual where executionid = pexecution_id; end $$; ```
Settling releases the hold and books the real amount. The settled_usd is null check plus for update means a second settle call for the same execution does nothing.
Wiring it into the workflow
``text Webhook -> Code: Reserve Budget Input -> Postgres: select reserve_ai_budget($1, $2, $3, $4) as ok -> IF ok true -> AI Agent (Max Iterations set) (optional) HTTP Request: Call Model -> Code: Settle Input -> Postgres: select settle_ai_budget($1, $2) -> Respond / continue false -> Respond with a fallback, notify the owner in Slack ``
Use the Postgres node's Execute Query operation with query parameters, not string-built SQL.
The reserve step computes the hold from the same limits you set on the nodes.
```js // n8n Code node "Reserve Budget Input", mode: Run Once for All Items // Example prices only. Copy current rates from your provider. const PRICE = { inputPerM: 1.0, outputPerM: 4.0 }
// These three must match the real settings on the AI Agent and model nodes. const MAXITERATIONS = 6 const MAXINPUTTOKENSPERCALL = 8000 const MAXOUTPUTTOKENSPER_CALL = 600
const perCall = (MAXINPUTTOKENSPERCALL PRICE.inputPerM + MAXOUTPUTTOKENSPERCALL PRICE.outputPerM) / 1e6
return [{ json: { budgetKey: 'support-agent', limitUsd: 20, // One extra call as margin for the final answer. reserveUsd: Number(((MAX_ITERATIONS + 1) * perCall).toFixed(6)), executionId: String($execution.id) } }] ```
Keep those constants next to the node settings they mirror. If someone raises Max Iterations and forgets this node, the reservation is too small. A sticky note on the canvas helps.
Where does the real cost come from?
This is the honest part.
If your model calls go through an HTTP Request node, the provider's response includes token usage. For OpenAI's Responses API that's usage.input_tokens, usage.output_tokens, and usage.input_tokens_details.cached_tokens. You can price that exactly.
If you use the AI Agent node with a chat model sub-node, n8n shows token usage in the execution view, but getting it as data into a later node isn't straightforward in every version. Check what your version exposes before you rely on it.
The settle step handles both cases. It measures when it can and keeps the full hold when it can't.
```js // n8n Code node "Settle Input", mode: Run Once for All Items // Example prices only. Copy current rates from your provider. const PRICE = { inputPerM: 1.0, cachedPerM: 0.1, outputPerM: 4.0 }
const reservation = $('Reserve Budget Input').first().json const calls = $('Call Model').all()
let actualUsd = 0 let missing = 0
for (const item of calls) { const usage = item.json.usage if (!usage || typeof usage.inputtokens !== 'number') { missing += 1 continue } const cached = Math.min(usage.inputtokensdetails?.cachedtokens ?? 0, usage.inputtokens) actualUsd += ((usage.inputtokens - cached) PRICE.inputPerM + cached PRICE.cachedPerM + (usage.output_tokens ?? 0) * PRICE.outputPerM) / 1e6 }
// No usage, or partial usage, means we cannot prove the real cost. // Keep the whole reservation as spent and let the daily true-up fix it. const settleUsd = calls.length === 0 || missing > 0 ? reservation.reserveUsd : actualUsd
return [{ json: { executionId: reservation.executionId, settleUsd: Number(settleUsd.toFixed(6)), measured: missing === 0 && calls.length > 0 } }] ```
That's the "fail closed" rule. A run you couldn't measure is booked at its worst case. You'll hit your cap a bit early. You won't blow through it.
To get closer to real numbers without per-call usage, give each workflow its own provider project or API key. Then compare the provider's usage view for that key with the ledger once a day and adjust.
Clean up stuck holds
If the agent errors after the reservation, nothing settles it. Run this from a separate workflow on a Schedule Trigger every 15 minutes or so:
``sql select settle_ai_budget(execution_id, amount_usd) from ai_budget_reservations where settled_usd is null and created_at < now() - interval '1 hour'; ``
It books any hold older than an hour at its full amount. Pick a cut-off longer than your slowest real run.
What to do when the gate says no
Don't just drop the request. Decide per workflow.
- Customer-facing chat: send a short fallback ("a person will get back to you") and create a task for a human.
- Back-office jobs: park the item in a queue table and let tomorrow's budget pick it up.
- Either way: alert the workflow owner once, not on every refused run. A refused reservation is often the first sign of a loop or a traffic spike.
Limitations
- The worst case is only as good as your limits. If tools can return huge results into the prompt, cap them, or your input ceiling is fiction.
- Over-reserving lowers throughput near the cap. That's the trade for never overshooting.
- The ledger tracks model spend only. n8n execution costs, hosting and anything else sit outside it.
-
current_dateand the one-hour sweep are simple choices. Adjust both to how your workflows actually run. - Field names in the settle script follow one provider's API. Read your own response shape first.
Takeaways
- A total-then-run check fails under concurrency. Reserve atomically instead.
- Give every agent run a real worst case: Max Iterations, max output tokens and a capped input.
- Settle with measured usage when you have it. Keep the full hold when you don't.
- Sweep stuck holds on a schedule.
- Decide what "no budget left" means for each workflow before it happens.
This post only covers the model line. For the full set of monthly costs around an agent, including platform fees, hosting and the time someone spends maintaining it, this breakdown of AI agent cost per month is a useful companion.
Top comments (2)
The reservation has to size the last turn, not the first. In an agent loop the largest request is the final one, because every tool result stays in context and goes out again with each call. A fixed per-call estimate under-reserves the long runs the cap exists for.
Reserving the worst case before the run starts keeps ten concurrent runs from all seeing the same room in the budget.