How to put a spending limit on an LLM API key

Set a per-key monthly cap, a fixed budget, rate limits and a model allowlist on an LLM API key, see what happens at the cap, and split a balance across a team.

Checked 2026-11-22

·All posts·Models

A spending limit on an LLM API key is a hard cap the gateway enforces for that key alone, apart from the account's balance, so a leaked or looping key stops at its own ceiling instead of emptying the account; below is how to set one on UplinkSwitch, what a request gets back once the cap is reached, and how a team divides one prepaid balance into caps per person and per agent. Every control here is a field on the key, set in the console or over the key API at https://api.uplinkswitch.com/v1/keys.

Two caps, and which one you want

The key record carries two different ceilings. They answer two different fears.

ControlField on the keyResets?Error at the cap
Spend limit per periodmonthly_cap_usd, with spend_limit_period daily, weekly or monthlyYes: 00:00 UTC each day, Monday 00:00 UTC each week, or the first of the UTC month402 monthly_limit_reached (or weekly_ / daily_limit_reached)
Prepaid budgetbudget_usdNo; raise it or the key stays stopped402 key_budget_exhausted

The period limit suits a production key whose normal month you can predict: set it at expected spend plus a margin and it resets on its own. The counter is the key's settled charges plus its open holds in the current period, and the check happens in the ledger at admission, so twenty parallel calls cannot each squeeze under the line together.

The budget suits a key you hand to someone else: a contractor, a customer, a bot. It is carved out of your balance, never refills, and when it is spent the key is done until you raise it. PATCH moves a budget up or down, though not under the amount already spent on the key; sending null clears it.

Both can sit on one key. Neither changes the price of a token.

Set it over the API

Key management runs on an admin key, which you make once under Keys in the console ("Admin key"). An admin key manages keys and cannot call a model, so a leaked admin key spends nothing.

bash
# Create a key with a monthly cap, a hard budget, a rate limit and an allowlist.
# The cap and budget values are yours to pick; these are placeholders.
curl https://api.uplinkswitch.com/v1/keys \
  -H "Authorization: Bearer $UPLINK_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "support-bot",
    "monthly_cap_usd": 50,
    "spend_limit_period": "monthly",
    "budget_usd": 200,
    "rpm": 60,
    "concurrency": 5,
    "allowed_models": ["glm-5.3-flash", "gpt-6.1-sol"],
    "expires_at": 1798761600000
  }'
# 201: {"key": "sk-uplink-live-...", "data": {...}}  The full key appears once.

POST /v1/keys takes name and, optionally, allowed_models (up to 100 ids), allowed_ips, rpm, tpm, concurrency, monthly_cap_usd, spend_limit_period, budget_usd and expires_at in Unix milliseconds. The console's own field names (rate_limit_rpm, tpm_limit, monthly_spend_limit_micro, budget_micro) are accepted too.

bash
# Raise the cap on an existing key, or pause it.
curl -X PATCH https://api.uplinkswitch.com/v1/keys/KEY_ID \
  -H "Authorization: Bearer $UPLINK_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"monthly_cap_usd": 80, "status": "active"}'

# What the key has spent today, this month and ever, plus what is left of its budget.
curl https://api.uplinkswitch.com/v1/keys/KEY_ID/usage \
  -H "Authorization: Bearer $UPLINK_ADMIN_KEY"

GET /v1/keys/{key_id}/usage returns requests and spend for the current UTC day, the current UTC month and the key's lifetime, with a budget object (budget_usd, spent_usd, remaining_usd) when the key has one. Add ?group_by=user and it also lists this month's spend per end user, read from the user field your requests carry.

What happens at the cap

The request is refused before it reaches a model, with a 402 in the caller's own wire format and nothing charged. The OpenAI SDK raises its usual status error with the code in the body:

python
import openai
from openai import OpenAI

client = OpenAI(base_url="https://api.uplinkswitch.com/v1", api_key=KEY)

try:
    r = client.chat.completions.create(
        model="glm-5.3-flash",
        messages=[{"role": "user", "content": "Summarise this ticket in one line."}],
    )
except openai.APIStatusError as e:
    if e.status_code == 402:
        # monthly_limit_reached, key_budget_exhausted or insufficient_balance
        alert_ops(e.code)
        raise

Three 402 codes look alike and mean different things, so log the code, not just the status:

  • monthly_limit_reached (or the weekly or daily form): this key spent its period limit. Other keys keep working. Raise the cap or wait for the reset.
  • key_budget_exhausted: this key's own budget is used up. Other keys keep working. Raise the budget or move to another key.
  • insufficient_balance: the account's prepaid balance is gone. Every key stops. Top up.

Retrying a 402 in a loop changes nothing; treat it as an alert. A fourth code, spend_cap_reached, applies only to a new account before its first payment settles, part of the spend protection every new account starts with alongside a cap on request rate during the account's first day.

Degrade instead of stop

Budget autopilot is the alternative to a hard stop: a key with a period limit names a cheaper model, and once spend approaches the limit that model answers in place of the one requested. The substitute comes from the same developer, the model field in the body says which model actually replied, and the id the request asked for is recorded in the response headers. It fits a consumer chat feature where a cheaper answer beats an error page; it does not fit an evaluation key, where you want the stop.

The other controls on the same key

A spend cap limits damage in dollars. Three more fields limit damage in other units:

  • Rate and concurrency. Each key carries rpm (requests per minute) and concurrency (requests in flight), and optionally tpm (tokens per minute). Exceeding one returns 429 rate_limited plus a retry-after value. The console shows the key's current figures.
  • Model allowlist. A key narrowed to named models or aliases returns 403 scope_denied for anything else, and GET /v1/models on that key lists exactly what it may call. A key for a classifier has no reason to be able to call a frontier model.
  • Expiry and IP allowlist. expires_at ends a key on a date, which suits demos and contractors; allowed_ips restricts it to your servers' addresses, answering 403 ip_not_allowed from anywhere else.

Keys can also be paused and resumed from the console, and revocation takes effect on the next request.

Splitting one balance across a team

The account has one prepaid balance; keys are free to create, so the pattern is one key per thing that can go wrong, each with its own cap:

KeyCap styleWhy
prod-apiMonthly limit at expected spend plus marginA traffic spike becomes a 402, not a bill
agent-researchDaily limitAn agent loop that runs overnight stops at midnight UTC
contractor-anaBudget plus expiryHard ceiling, ends with the contract
customer-42Budget plus allowlistResold access stops at what they paid for and cannot reach other models
laptop-devSmall monthly limitA script pointed at the wrong model

People get console access separately from keys. An owner invites members by email with a role: owner (everything), billing (member rights plus top-ups and gift cards) or member (keys, chat, usage, aliases, canaries, media). Invite links last 7 days. So a developer can create and cap their own keys without being able to spend the company card, and the billing role can top up without touching production keys.

For an agent that serves many end users on one key, two more fields apply. A user_budget caps what any one end user, identified by the request's user field, may spend in a period (402 user_budget_reached), and session caps (session_max_requests per hour, session_max_spend_usd per UTC day) bound a single conversation, answering 429 session_cap when reached. The observability page covers sessions.

Watching the balance itself

Caps stop keys; two things watch the account. Accounts with an email and recent usage get a low-balance notice when the available balance falls under about one day of recent spend, before requests start failing (it is not sent while auto top-up is on). And the Keys page carries a month-to-date spend figure per key, with the signed monthly statement breaking the closed month down by key, verifiable at /statements/verify. Prices themselves are on the price index; the SDK guide has the full key API section.

Questions and answers

It is refused before any model runs, with a 402 whose code says which ceiling was hit: monthly_limit_reached (or the weekly or daily form) for the period limit, key_budget_exhausted for the key's own budget. Nothing is charged, other keys keep working, and a key with budget autopilot answers with a cheaper same-developer model instead.

Yes. Keys are free, so create one per person, service or agent, each with a monthly, weekly or daily limit or a fixed budget, plus its own rate limit, model allowlist and expiry. Team members sign in with roles, and one key can cap each end user through the user field or each session.

No. A token costs the same whether or not the key has a cap; the limit only decides when requests stop. The counter adds the key's settled charges and open holds for the period, a refused request costs nothing, and the response body's usage.cost still reports each request's exact charge.
Join on Telegram
Help