Control AI API Spending: Prepaid vs Postpaid, Hard Caps, Alerts

Blog / Relays & gateways

Control AI API Spending: Prepaid vs Postpaid, Hard Caps, Alerts

The core of controlling API spending is putting a ceiling on your worst-case bill: prefer a prepaid account or one with a hard cap, give every project its own key, and log the usage of every call in your own code. The platform's billing page only shows you the damage after the fact. What actually stops a runaway is a cap and your own logs.

Before you think about how to save money, work out how much you could lose at most. An agent stuck in a loop, a batch job you forgot to stop, or a leaked key can burn a month's budget in a few hours. Below, the risks are covered from largest to smallest.

Prepaid vs postpaid: where does the risk differ?

ModelWorst caseBest for
Prepaid (top up first, spend until it runs out)Loss is limited to the balance you topped upIndividuals, experiments, beginners
Postpaid (settled at month end)Depends on whether the platform has a cap; can be far above what you expectedTeams with a reconciliation process
Fixed monthly subscription (with a quota)What happens when the quota runs out (throttling, suspension, or switching to pay-as-you-go) varies by service; check the terms of serviceSteady day-to-day coding usage

Prepaid has a built-in ceiling. The downside is that requests fail outright when the balance hits zero, so production workloads need a low-balance reminder. Postpaid is convenient, but if the platform has no hard cap, you have to build your own defenses. To decide between pay-as-you-go and a monthly plan, use the formula in this article to find the break-even point: Pay-as-you-go or monthly for AI APIs: one formula for the break-even point.

How do you set budget caps and alerts?

First, separate two concepts:

  • Alert (soft limit): a notification at a given amount; the service keeps running.
  • Hard limit: requests are rejected once the amount is reached.

Whether a platform offers a hard limit, what it is called, and where you set it varies a lot. Some platforms only have alerts with no blocking. Check the official documentation. If your platform only has alerts, treat them as the first line of defense and add a second one in your own code.

A suggested approach to thresholds (the numbers are examples; replace them with your own budget):

  1. Send an alert at 50% and again at 80% of the monthly budget, and stop non-critical jobs at 100%.
  2. Also alert when a single day's spend exceeds 3 times (monthly budget ÷ 30), to catch sudden bursts.
  3. Send alerts somewhere a person will actually see them (email, a team chat bot), not just the console.

Besides dollar amounts, watch request volume and error rate. A retry storm usually shows up first as a spike in 429s and 5xx errors, and only later as a bigger bill. For how to set those thresholds, see: How to set LLM API alert thresholds: 429, 5xx, timeouts, and P95 latency separately.

Why split keys by project?

With one key for everything, when something goes wrong you can't tell who burned the money, and you can't shut down only the part that misbehaves. Recommendations:

  • One key per project and per environment (development, staging, production).
  • Put the purpose and date in the name, for example blog-summarizer-prod-2026-10.
  • Give development keys a lower quota, and monitor production keys separately.
  • Keep keys in environment variables or a secrets manager. Never commit them to a repository or paste them into chats and screenshots.
  • Rotate them regularly. If you suspect a leak, revoke first and investigate afterward.

Some platforms let you set a separate quota or permissions per key, and some don't; check the official documentation. If yours doesn't, splitting keys still lets you attribute usage by key in your statistics.

How do you keep usage records in your own code?

Platform bills arrive late and are coarse, so log one line locally for every call. Most LLM API responses include token usage fields, and the field names differ by provider (check the official documentation). A minimal approach is to write them as JSON lines:

import json, time

def log_usage(project, model, usage, path="usage.jsonl"):
    row = {
        "ts": int(time.time()),
        "project": project,
        "model": model,
        "input_tokens": usage.get("input_tokens") or usage.get("prompt_tokens"),
        "output_tokens": usage.get("output_tokens") or usage.get("completion_tokens"),
    }
    with open(path, "a") as f:
        f.write(json.dumps(row, ensure_ascii=False) + "\n")

Then summarize by project with a short command (requires jq):

jq -s 'group_by(.project)[] | {project: .[0].project,
  calls: length,
  input: (map(.input_tokens // 0) | add),
  output: (map(.output_tokens // 0) | add)}' usage.jsonl

Once you have token counts, multiply by the unit prices on the official pricing page to estimate cost. Input, output, and cache hits are often priced separately; for the breakdown, see: How token billing works: a line-by-line breakdown of one LLM API call's bill.

Your own records have another use: reconciling against the platform's bill. When the two differ noticeably, go through the steps in Why is my API bill wrong: token counting rules, duplicate charges, and line-by-line checks.

What other safeguards can you add in code?

  • Set max_tokens (or the equivalent parameter) on every request so output can't grow without bound.
  • Give agent loops a maximum number of turns and a per-task token budget; stop and raise an error when exceeded.
  • Retries need a cap and backoff, and requests must be idempotent. Otherwise a retry after a timeout can be billed twice: How to prevent duplicate charges on API retries: idempotency and request deduplication after LLM timeouts.
  • For batch jobs, run 10 sample items first, estimate the cost per item, then scale up.
  • Cache results for identical requests so you don't pay twice for the same input.

A checklist you can use as-is

  1. The account is prepaid or has a hard cap set. If the platform has no hard cap, write down your own blocking mechanism.
  2. Alerts at 50% and 80% of the monthly budget are on, and the notification channel is monitored.
  3. One key per project and environment, with traceable names.
  4. Keys are not in the code repository, and you know where to revoke them if leaked.
  5. Every call logs project, model, and input and output tokens.
  6. Requests set max_tokens, and agent loops have a turn limit.
  7. Retries are capped and never resubmit a request that has side effects.
  8. Once a month, spend 15 minutes comparing your local logs with the platform bill.

How can a subscription gateway help control spending?

With a fixed monthly fee plus a quota, the plan sets the ceiling, which makes costs fairly easy for an individual developer to predict. For example, AGI Plan (a commercial partner of cdnping) is billed monthly in RMB (Chinese yuan), uses CU as its quota unit, and also supports pay-as-you-go top-ups; plans and prices are as listed at https://agiplan.dev/pricing. Whether this kind of plan fits depends on whether your usage is steady and whether you can accept what happens when the quota runs out.

The checklist above applies whichever way you connect: a gateway can't save you from an infinite loop in your own code.

Summary and next steps

Start with the two cheapest things: confirm the account has a cap (or switch to prepaid), and split out a separate key for each project. Then add local usage logs and alerts.

If your program depends on several upstream APIs, check /en/status for the probe status of each provider's API, and /en/models for the listing, delisting, and repricing history of models and providers, which makes price changes easier to catch in time. For ways to track price changes, see: How to find out right away when an LLM API price changes: changelogs, model catalogs, and bills as three tracking channels.

Related articles

Keep reading