Skip to main content
Back to all articles
AI Engineering 7 min readUpdated August 31, 2026

An AI Budget Should Fail Before the Invoice Does

Logging token cost after the fact is accounting, not control. This article designs per-tenant AI budgets with atomic reservations, actual-usage settlement, soft and hard limits, and concurrency-safe metering for RAG and agent workloads.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-cost#multi-tenancy#ai-agents#usage-metering#budgets#llm-cost#postgresql#typescript#python
On this page

A dashboard that tells you yesterday's AI spend is useful. It does not stop one buggy agent from creating tomorrow's bill tonight.

The difference is enforcement.

In a multi-tenant AI product, I want cost control to happen before expensive work begins, not only after provider usage has already been recorded. That becomes particularly important once a single user request can branch into retrieval, multiple model calls, tool use, retries, evaluation, and background work.

A naive implementation usually looks like this:

TypeScript
const spent = await getTenantSpend(tenantId);if (spent < monthlyLimit) {  await callModel();}

It looks reasonable until fifty workers run it at the same time. They all read the same remaining balance, all decide capacity exists, and all spend it.

That is not an AI problem. It is a reservation and concurrency problem.

The design I prefer is close to systems that reserve inventory or credit: estimate the maximum reasonable cost of an operation, reserve that amount atomically, execute, then settle the reservation against actual usage.

Separate metering from pricing

The most durable facts are what the provider actually reported:

type ModelUsage = {  provider: string;  model: string;  inputTokens: number;  cachedInputTokens: number;  outputTokens: number;  occurredAt: string;};

I store those dimensions even if I also calculate a currency amount immediately.

Pricing changes. Providers introduce cached-token rates, tool-specific charges, image units, or new billing dimensions. Historical usage should remain recomputable with a versioned pricing table instead of becoming an unexplained cost=0.0137 field whose formula disappeared six months ago.

For enforcement, however, the runtime still needs a current internal estimate. I express money as integer micros of the billing currency rather than floating-point dollars.

TypeScript
type MoneyMicros = bigint;​type PriceQuote = {  priceVersion: string;  estimatedMicros: MoneyMicros;};

The exact pricing data belongs in configuration or a pricing service, not scattered through agent code.

Budget scopes are product decisions

One global monthly cap is rarely enough.

Useful scopes can include:

Text
organization / tenant monthly budgetworkspace or project budgetper-user daily budgetper-run maximumper-feature maximumbackground-job budget

The hierarchy depends on the product.

A customer may have a $500 monthly organization allowance but still want one research run capped at $2 so a malformed task cannot consume the whole month. An internal product may care more about team/project limits than billing plans.

I model effective limits explicitly:

TypeScript
type EffectiveBudget = {  tenantMonthlyMicros: bigint;  userDailyMicros?: bigint;  runMicros: bigint;  warningAtPercent: number;};

A run must satisfy every applicable hard scope. Passing the tenant check does not override a smaller run budget.

Reserve before calling the model

Suppose a request has enough prompt material for an estimated 18,000 input tokens and allows up to 4,000 output tokens.

The runtime prices a conservative reservation before sending the call.

type CostReservation = {  id: string;  tenantId: string;  runId: string;  amountMicros: bigint;  status: "active" | "settled" | "released" | "unknown";};​interface BudgetLedger {  reserve(input: {    tenantId: string;    runId: string;    amountMicros: bigint;  }): Promise<CostReservation>;​  settle(input: {    reservationId: string;    actualMicros: bigint;  }): Promise<void>;​  release(reservationId: string): Promise<void>;  markUnknown(reservationId: string): Promise<void>;}

The important behavior is inside reserve: it must check remaining budget and claim capacity atomically.

A read-then-write budget check races

This pattern is unsafe under concurrency:

SQL
SELECT spent_micros FROM tenant_budget WHERE tenant_id = $1;-- application decides there is enough moneyUPDATE tenant_budget SET spent_micros = spent_micros + $2 ...;

Two workers can make the decision from the same old value.

One database-level approach is to maintain committed spend plus active reservations and perform the reservation in a transaction that locks the budget row.

SQL
BEGIN;​SELECT limit_micros, spent_micros, reserved_microsFROM tenant_budgetsWHERE tenant_id = $1FOR UPDATE;​-- application verifies:-- spent_micros + reserved_micros + requested <= limit_micros​UPDATE tenant_budgetsSET reserved_micros = reserved_micros + $2WHERE tenant_id = $1;​INSERT INTO ai_cost_reservations (  id,  tenant_id,  run_id,  reserved_micros,  status) VALUES ($3, $1, $4, $2, 'active');​COMMIT;

For high-throughput systems, a single locked monthly row can become contention. Alternatives include atomic conditional updates, partitioned counters, Redis/Lua reservations with durable reconciliation, or a dedicated metering service.

The invariant matters more than the storage choice: concurrent workers must not independently spend the same remaining allowance.

Settlement uses actual usage

After the provider responds, calculate actual cost from its reported usage and settle the reservation.

If the provider call throws after it may already have accepted the request, I keep the reservation in an unknown state until reconciliation. Releasing it immediately would make the ledger optimistic at exactly the moment we have least information.

async function executeBudgetedModelCall<T>(input: {  tenantId: string;  runId: string;  quote: PriceQuote;  ledger: BudgetLedger;  call: () => Promise<{ value: T; actualMicros: bigint }>;}): Promise<T> {  const reservation = await input.ledger.reserve({    tenantId: input.tenantId,    runId: input.runId,    amountMicros: input.quote.estimatedMicros,  });​  try {    const result = await input.call();    await input.ledger.settle({      reservationId: reservation.id,      actualMicros: result.actualMicros,    });    return result.value;  } catch (error) {    await input.ledger.markUnknown(reservation.id);    throw error;  }}

An adapter that can prove the request never left the process—for example, local validation failed before any network call—can release the reservation instead. That distinction belongs near the transport boundary because a generic budget wrapper cannot infer it from an exception message.

Reservations need expiry and reconciliation

A worker can crash after reserving capacity.

If nothing releases that reservation, the tenant eventually appears to have no budget even though the work never completed.

Reservations therefore need timestamps and a recovery process:

TypeScript
type ReservationState =  | "active"  | "settled"  | "released"  | "unknown"  | "expired";

A sweeper can examine stale active reservations and decide whether they can be safely released or require provider/run reconciliation.

This should be idempotent. Running the reconciler twice must not refund a reservation twice.

The cost ledger is financial-ish state even if no money is directly moved. I treat its transitions with more care than an analytics counter.

Reserve for the path, not only the next call

A model call can cause three more model calls.

If the planner reserves 10 cents, spends 8, then launches five tool-analysis branches that each reserve another 10, the run can still exceed the product's intended maximum.

I keep a run-level budget beside tenant-level capacity:

TypeScript
type RunBudgetState = {  runId: string;  hardLimitMicros: bigint;  committedMicros: bigint;  reservedMicros: bigint;};

Every child reservation checks both:

Text
tenant remaining capacityANDrun remaining capacity

For subagents, I can allocate child envelopes from the parent rather than letting each child see the tenant's entire remaining balance.

A parent with 50 cents left might give three workers 15 cents each and keep 5 cents for synthesis. That is much safer than telling each worker “the tenant still has $200 this month.”

Soft limits are different from hard limits

A hard limit answers: should this work start?

A soft limit changes behavior before the system reaches that point.

At 70% of a monthly allowance I might only emit a warning. At 90%, the product may prefer smaller models for optional tasks, skip nonessential enrichment, reduce automatic retries, or ask before starting expensive research.

Those policies should be explicit.

type BudgetMode = "normal" | "conserve" | "blocked";​function budgetMode(  spentAndReserved: bigint,  limit: bigint,): BudgetMode {  if (spentAndReserved >= limit) return "blocked";​  const percent = Number((spentAndReserved * 100n) / limit);  if (percent >= 90) return "conserve";  return "normal";}

A production function should reject a zero/invalid limit before doing division. The example assumes validated positive configuration.

Conservation can feed the model router later in the stack; it should not be implemented as a vague system-prompt instruction to “use fewer tokens.”

Token limits are not the same as cost limits

Two models can charge differently for the same number of tokens. Cached input may cost differently from uncached input. Some providers price tools or modalities separately.

A request can also have cheap input and expensive output.

That means this is incomplete:

Text
max 20,000 tokens per user

It can still be a useful safety dimension, especially for context growth, but it is not a billing budget.

I usually track both:

Text
context/input/output token ceilings for technical controlcurrency budget for economic controlprovider quota/rate limits for capacity control

They solve related but distinct failures.

Budgets should include retries

A retry is not free just because the first call failed.

If a model call times out after doing substantial work, the retry may double cost. If a judge model runs three times for calibration, all three runs count. If a tool invokes a paid search API, that may belong in the same run budget even though it is not an LLM token charge.

I want one run ledger that can contain multiple usage classes:

TypeScript
type UsageCharge = {  kind: "model" | "embedding" | "reranker" | "paid-tool";  provider: string;  amountMicros: bigint;  referenceId: string;};

That gives the product a meaningful answer to “what did this research job cost?” instead of only “what did the final generation cost?”

Multi-tenant isolation applies to the ledger too

Budget records are tenant-scoped application data.

Every reservation and query should include the trusted tenant identity from authentication/run state. The model should not select a billing tenant in a tool argument.

I also avoid returning raw organization spending details to the model unless the task genuinely needs them. The runtime can expose a narrow policy result:

JSON
{  "mode": "conserve",  "remainingRunBudget": "low"}

The planner does not need the customer's exact monthly invoice to choose a cheaper optional path.

Do not make budget failures look like model failures

If a reservation is rejected, the model provider is healthy.

The run stopped because application policy denied further spend.

That distinction belongs in traces and user-facing behavior:

Text
run.status = stoppedstop_reason = budget_exhausted

For an interactive assistant, the UI can explain that the current workspace or task budget has been reached. For background automation, the run can pause for an administrator to raise the limit or for the next budget period.

Automatically retrying a budget rejection is pointless.

Budget evaluation belongs in CI too

An agent prompt change can increase cost without changing answer quality.

For representative evaluation cases I track:

Text
success rateinput tokensoutput tokensmodel callspaid tool callsestimated/actual costlatency

A candidate workflow that improves quality by 1% while tripling p95 cost deserves a deliberate decision, not an accidental deployment.

This connects cost policy to the evaluation gates already covered earlier in the series.

When a ledger is unnecessary

A small internal tool with one model call and a fixed company account may only need provider billing alerts and a monthly dashboard.

Reservation machinery becomes useful when spend is tenant-visible, contractual, high-volume, agentic, or unpredictable enough that post-hoc monitoring is too late.

The key shift is to stop treating AI spend as a log line.

Once model calls can branch and run concurrently, cost becomes a consumable resource. Consumable resources need ownership, atomic reservation, settlement, limits, and recovery from partial failure.

That is normal production engineering. The only new part is that the resource being reserved happens to be probabilistic compute.

KEEP READING

Related engineering notes