Skip to article
API429 / Field notes

AI API cost guardrails: set budgets for tokens, retries and agent loops

Set application-side cost guardrails for AI APIs with atomic pre-call reservations, prepay balance thresholds, spend-window checks, and loop caps.

Hourglass and a queue of paper request cards
Editorial photo illustration: Hourglass and a queue of paper request cards. Topic: AI API cost guardrails: set budgets for tokens, retries and agent loops.

Set an explicit spending allowance before an AI request leaves your server, cap the number of steps and retries, and reconcile the estimate against actual usage after the response returns. Most runaway bills come from long context, repeated retries, unmonitored prepay credit depletion, and multi-step agent loops rather than a single ordinary prompt.

This guide consolidates task-level token reservations, prepay balance watermarks, and spend-window guardrails into one application budgeting workflow. Check published model rates in the pricing comparison hub and the API429 pricing overview before setting your per-request ceilings.

Know the billing units before you set a limit

Different endpoints use different billing units. Text and multimodal chat models are usually priced per 1M input and output tokens, often with separate rates for cached tokens, long context, or tools. Image generation is commonly priced per image or output tokens depending on the model, speech models per character or audio token, and video models per second.

Use the maintained comparison pages when choosing a baseline: OpenAI pricing, Claude pricing, and Gemini pricing. Keep vendor list prices, API429 rates, and your application's internal task budget separate.

Control layer What it measures Point-in-time or atomic Action when threshold is crossed
Task pre-call reservation Estimated input tokens + capped max_tokens + tool/media units Atomic in your application ledger Reject or downgrade before calling the API
Agent loop & retry cap Cumulative steps, tool calls, and retry attempts per task ID Atomic in worker state Stop loop and return partial/escalation state
Account prepay balance watermark GET /api/client/balance or provider billing alerts Point-in-time observation Alert operators and pause low-priority batch queues
Direct provider spend-window tier Project cumulative spend and usage-tier limits Enforced by upstream provider Pause non-essential jobs; do not blind-retry 429s

Reserve the worst-case cost of one step

Before sending a request, estimate input size, set an explicit output ceiling (max_tokens or max_output_tokens), and calculate the maximum cost of that step using the Gemini token counting guide:

reserved_cost =
  input_tokens * input_rate +
  max_output_tokens * output_rate +
  media_or_tool_units * unit_rate

Reserve that amount against the task or user budget before the network call. When the response arrives, replace the reservation with the actual usage reported by the API. If the request fails before execution is confirmed, mark the state clearly so a blind retry does not double-spend the allowance.

Separate prepay balance checks, spend-window 429s, and atomic ledgers

Production teams often conflate three different financial boundaries:

  1. Application-owned atomic budget ledger: When multiple workers share a tenant or campaign budget, update the reservation atomically in your own database or Redis store. Otherwise, concurrent workers will read the same remaining balance and collectively overspend it.
  2. Prepay credit balance observations: Both direct provider prepay billing (Google Gemini billing) and API429's authenticated GET /api/client/balance endpoint report current account balance. As explained in API429 vs direct Gemini API, a balance read is a point-in-time observation, not a capacity reservation for in-flight requests. Poll balance on a short interval to trigger low-watermark alerts and shed deferrable batch traffic before the account hits zero.
  3. Spend-based rate limits and usage tiers: Under Google Gemini API rate limits, direct Google project limits depend on usage tiers tied to cumulative spend and can return 429 RESOURCE_EXHAUSTED (RFC 6585 Section 4) when a spend or token window is saturated. Rotating API keys inside the same Google Cloud project does not create a new quota pool. Instead, pause background jobs via queue admission controls and keep interactive calls within your retry budget policy.

Cap agent loops and handle incomplete results

An agent that can call tools, rewrite queries, or inspect long conversation history needs a hard step count and a total token budget for the whole task. Trim or summarize old turns instead of resending the entire transcript on every step, and pause for human approval before expensive batches.

A timeout does not establish whether generation ran or was charged. Before repeating a paid operation, check your application idempotency ledger and the service's retry guidance. Use the retry budget policy to parse Retry-After seconds or HTTP dates and check the total deadline before scheduling another call.

Runnable offline Python atomic budget and balance guard

The standalone Python module below reserves worst-case step cost before dispatch, blocks deferrable workloads when observed account balance drops below a safety watermark, and reconciles actual billed usage after completion:

from dataclasses import dataclass

@dataclass
class TaskBudgetLedger:
    task_limit_usd: float
    reserved_usd: float = 0.0
    spent_usd: float = 0.0
    steps_used: int = 0
    max_steps: int = 4

def worst_case_step_cost_usd(
    *,
    input_tokens: int,
    max_output_tokens: int,
    input_rate_per_1m: float,
    output_rate_per_1m: float,
    tool_fee_usd: float = 0.0,
) -> float:
    in_cost = (input_tokens / 1_000_000) * input_rate_per_1m
    out_cost = (max_output_tokens / 1_000_000) * output_rate_per_1m
    return round(in_cost + out_cost + tool_fee_usd, 6)

def reserve_step_budget(
    ledger: TaskBudgetLedger,
    *,
    step_cost_usd: float,
    observed_account_balance_usd: float,
    low_balance_watermark_usd: float,
    interactive: bool,
) -> tuple[bool, str]:
    if ledger.steps_used >= ledger.max_steps:
        return False, "max_agent_steps_exceeded"
    if not interactive and observed_account_balance_usd <= low_balance_watermark_usd:
        return False, "low_balance_shed_background_work"
    if observed_account_balance_usd < step_cost_usd:
        return False, "insufficient_observed_account_balance"
    if ledger.spent_usd + ledger.reserved_usd + step_cost_usd > ledger.task_limit_usd:
        return False, "task_budget_exceeded"
    ledger.reserved_usd = round(ledger.reserved_usd + step_cost_usd, 6)
    ledger.steps_used += 1
    return True, "reserved"

def reconcile_step_budget(
    ledger: TaskBudgetLedger,
    *,
    reserved_step_usd: float,
    actual_step_usd: float | None,
) -> str:
    if actual_step_usd is None:
        return "uncertain_outcome_hold_reservation"
    ledger.reserved_usd = round(max(0.0, ledger.reserved_usd - reserved_step_usd), 6)
    ledger.spent_usd = round(ledger.spent_usd + actual_step_usd, 6)
    return "reconciled"

if __name__ == "__main__":
    task = TaskBudgetLedger(task_limit_usd=0.05, max_steps=3)
    est = worst_case_step_cost_usd(
        input_tokens=12_000,
        max_output_tokens=2_000,
        input_rate_per_1m=1.25,
        output_rate_per_1m=5.00,
    )
    ok, reason = reserve_step_budget(
        task,
        step_cost_usd=est,
        observed_account_balance_usd=15.0,
        low_balance_watermark_usd=5.0,
        interactive=True,
    )
    actual = worst_case_step_cost_usd(
        input_tokens=12_000,
        max_output_tokens=600,
        input_rate_per_1m=1.25,
        output_rate_per_1m=5.00,
    )
    state = reconcile_step_budget(task, reserved_step_usd=est, actual_step_usd=actual)
    print("Reservation:", ok, reason, "| Reconciled:", state, "| Spent USD:", task.spent_usd)

Validate before increasing volume

Run a small representative task and compare estimated tokens, reported usage, and actual charges. Measure accepted results rather than assuming the least expensive token rate produces the least expensive completed task. Include failures and retries in the denominator.

For API429, choose an ID available to your key and check the model catalog, documentation, API reference, and FAQ. A catalog listing establishes published model information; it does not prove support for every optional feature of a provider's direct API.

FAQ

Does polling GET /api/client/balance reserve funds for concurrent requests?

No. A balance check is a point-in-time read of your account credit. Concurrent workers must still track and reserve in-flight task budgets atomically in your own application store.

What should a worker do if a request times out after reserving budget?

Do not immediately release the reservation and trigger a blind retry. Hold the reservation in an uncertain_outcome state while reconciling the request log or operation ID so a delayed completion does not double-charge the task.

Why do direct Gemini API projects hit 429 even when RPM is low?

Direct Google Gemini quotas evaluate multiple dimensions simultaneously—including input tokens per minute (input TPM), daily requests (RPD), and usage-tier spend limits. One large prompt or retry burst can exhaust input TPM while request count remains small.

How should background batch jobs react to low prepay balance watermarks?

Configure two watermarks in your scheduler: an early warning threshold that pauses deferrable batch jobs and alerts finance/ops, and a hard floor that stops non-critical calls before interactive traffic fails.

Sources & further reading

  1. Google Gemini API pricing
  2. Google Gemini API billing and prepay
  3. Google Gemini API rate limits
  4. Anthropic Claude pricing
  5. OpenAI API pricing
  6. HTTP 429 definition
  7. API429 client documentation
  8. API429 public OpenAPI

Put the next step into practice.

Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

Telegram