One shared provider key in production means any leak or runaway loop can spend without limit. A gateway key with its own cap turns the same accident into a small, one-key incident you can shut off in a minute.
- A shared provider key has no ceiling of its own, so one leak or one retry loop can spend until the provider cuts you off.
- LiteLLM virtual keys take a max_budget, a budget_duration, a duration (TTL), a models allowlist and rpm_limit and tpm_limit on the same key.
- Cloudflare AI Gateway's rate limiting counts requests per window, not dollars, so it can't replace a spend cap.
- Issue separate keys per environment, per customer and per agent, and set the cap below the damage you could absorb in one bad weekend.
- When a key leaks, revoke the virtual key first, then rotate the provider key only if the master key was exposed.
Take a coding agent stuck in a retry loop. Each call sends 100,000 tokens of context, and it fires once a second. At an illustrative input price of $3 per million tokens, that's $0.30 a second, or $1,080 an hour, and nobody is watching at 3 a.m. If you've been searching for how to set budget limits per API key LLM gateway tools support, that arithmetic is the reason to do it this week and not after the first bad invoice.
Most early teams skip it because the first setup works. One OpenAI or Anthropic key goes into an environment variable, every service reads it, and the product ships. That key has no idea who is calling it. It can't tell a customer request from a test script from a stolen copy pasted into a scraper. The only brake is whatever limit your provider account has, and you should check whether that limit is a hard stop or only an email alert. Providers have offered both over the years, and an alert at 3 a.m. helps nobody who is asleep.
Providers do fight one part of this for you. OpenAI and Anthropic both take part in GitHub's secret scanning program, which means a key committed to a public repository can be flagged and revoked. That only covers one leak route, though. Keys also escape through browser bundles, CI logs, a contractor's laptop, a pasted support screenshot, or a compromised dependency. And a runaway loop isn't a leak at all. It's your own code, with your own valid key, doing exactly what you told it to.
A gateway sits between your code and the model provider. The real provider key lives inside the gateway and nowhere else. Your services, your customers' integrations and your agents each get a different key issued by the gateway, and that key is only a pointer. If it leaks, the attacker holds a key that works against one gateway, with whatever limits you attached, and you can kill it without touching anything else.
How to Set Usage Limits Per Customer for LLM API Spend Before It Hurts Anthropic told Claude Code subscribers in July 2025 it would add weekly usage limits affecting fewer than 5% of them, after one user consumed tens of thousands of dollars in model usage on a $200 plan. Sorting tenants by cost and checking the top 3% against what they pay shows where your margin leaks. - set per-customer usage limits for LLM APIs - prevent heavy users from hurting SaaS margins
LiteLLM, the open source proxy, is the clearest example because the controls are plain parameters. You call its key generation endpoint with the master key and pass the limits in the body. The ones that matter are max_budget, a dollar ceiling for the key; budget_duration, such as 30d, which resets the spend counter on a schedule; duration, which sets a time to live so the key expires on its own; models, an allowlist of model names the key may call; rpm_limit and tpm_limit, requests and tokens per minute; and max_parallel_requests. LiteLLM also lets you hang keys off teams and users, each with their own budgets, so a customer can have a team budget and individual keys beneath it. Its docs describe all of these under virtual keys and budgets.
The models allowlist is the control people forget. A key meant for a cheap summarization job should list one small model. If someone steals it, they can't point it at your most expensive reasoning model and burn through the cap ten times faster than you planned. The TTL does a similar job against slow leaks: a key that dies after 30 or 90 days limits how long an old copy in a forgotten backup stays useful.
Two caveats from how these proxies work. First, spend is recorded after a call completes, so a cap is a tight fence and not a wall to the cent. Several parallel requests can finish past the limit before the counter catches up, which is one more reason to set max_parallel_requests. Second, the proxy can only price what it knows. LiteLLM relies on a model price map, and if you route to a custom or self-hosted model with no price attached, the spend counter can read zero while the bill grows. Add custom pricing for anything off the standard list, then test it by sending one request and watching the key's spend change.
Where Portkey and Cloudflare fit #
Portkey is a hosted gateway that takes a similar approach. Its documentation describes attaching budget limits, either in cost or in tokens, and rate limits to the keys it issues, with periodic resets. Its product naming has shifted over time, with provider credentials now organized differently than the older virtual key term, so read the current docs for the exact object names before you copy a tutorial. The principle carries over: the credential you hand out is not the provider credential, and the limit travels with it.
Cloudflare AI Gateway is the odd one out, and it's worth being direct about that. Its documented strength is observability, caching and rate limiting, set as a number of requests in a fixed or sliding time window. That's useful for stopping a flood of calls. It's a request counter, not a spend counter, so a hundred requests with huge prompts and long outputs can cost far more than a thousand tiny ones. If you run Cloudflare in front of your models, treat its limits as a speed bump and put a real dollar cap somewhere else: a spend limit on the provider project or workspace, or a second gateway layer that prices tokens. Check Cloudflare's current documentation for any budget feature before you rely on this paragraph, because gateway products add controls quickly.
My position is that a dollar cap enforced in the gateway beats any alert you can build. An alert asks a person to wake up, read, decide and act. A cap does all four before the person has opened their eyes.
A per-key policy you can set in an afternoon #
Start by splitting keys by environment. Production, staging and local development each get their own key, and development gets a small one. A developer's laptop should never hold a production credential, and a developer key capped at $20 a month makes a pasted-into-chat leak a non-event. Set a short TTL on development keys, 30 days at most, so stale copies stop working without anyone remembering to delete them.
How to Set AI Agent Spending Alerts That Fire in Minutes, Not at Month-End A $3,000 monthly budget at 80% alerts at $2,400, but a retry loop burning $400 an hour can cost about $1,600 before anyone reads the email at 5:30 a.m. The fix: per-run checks at 2x and 5x p99, plus a per-customer daily cap built from the plan price. - how to set AI agent spending alerts - detect runaway AI agent costs quickly
Next, split by customer, and this is where the numbers get real. If you sell an AI feature at a flat monthly price, one customer's heavy use comes straight out of your margin. Issue each customer, or each plan tier, its own key or team with a monthly budget and a budget_duration that matches your billing cycle. Pick the cap from the plan, not from hope: if a $49 plan leaves you roughly $15 for inference after your other costs, the key's max_budget is $15. When it trips, the customer sees an error from your product, so decide in advance what that error says and whether they can buy more. Don't leave that to a raw 400 response from the proxy.
Third, give every agent its own key. Agents are the likeliest source of runaway spend because they loop, call tools and retry by design. An agent key should carry a small budget, a tight models list, a low max_parallel_requests, and a TTL that matches the job. A research agent that runs for an afternoon doesn't need a key that lives for a year. If you run agents on behalf of customers, nest them: the customer's team budget is the outer wall and each agent key sits inside it with a smaller ceiling.
Fourth, set the numbers from what you can absorb, not from what you expect to use. Look at your real monthly provider bill, take the smallest amount that would hurt, and make that the most any single key could spend before a human sees it. For a pre-revenue startup that might be a few hundred dollars across all keys combined. Then add a soft limit under each hard one. LiteLLM supports a soft budget that triggers an alert before the hard cap blocks calls, which gives you a warning at, say, 70% and a stop at 100%.
Fifth, rate limit each key in step with the budget. A $15 monthly cap with no rpm_limit can still be emptied in four minutes. A tpm_limit sized to your normal peak makes a burst look like a burst, throttles it, and gives your alerting time to fire. The two limits cover different failures: the budget caps total damage, and the rate limit slows its speed.
Leaked LLM API key cost protection in practice #
Write the response down before you need it, because the order of steps matters. When a key leaks, revoke or block the virtual key first. That takes seconds in the gateway and doesn't touch production traffic on other keys. Then read the key's spend log to see what it called, which models, and from where, because a capped key already limits the amount you lost, and the log tells you whether anything was exfiltrated or only spent. Only rotate the real provider key if the gateway's master key or its database was exposed, since the provider key never left the gateway otherwise.
Protect the master key harder than anything. In LiteLLM it creates, edits and deletes every other key. It belongs in your secrets manager, used only by a small admin script or dashboard, never baked into an application that handles customer traffic. A gateway with great per-key limits and a master key in a client bundle is a locked door with the master key taped to the frame.
Test the cap before you trust it. Issue a throwaway key with a $0.05 budget, call a model until it fails, and confirm that the error comes back, that it's logged, and that your product handles it without crashing. Do the same for the TTL by issuing a key that expires in a few minutes. A budget you haven't seen trip is a guess.
The provider limit still matters as the last layer. Set a monthly spend limit on the provider project or workspace that holds your gateway key, at a number you could survive, so a gateway bug or a mispriced model hits a second wall. Anthropic's workspaces and OpenAI's projects both offer spending controls, and each provider's documentation says how firm those controls are. Read that line before you assume the limit stops traffic.
None of this needs a platform team. In LiteLLM it's one proxy, one Postgres database for spend tracking, and a short script that issues keys from a template: environment, customer or agent name, budget, duration, models. Store the template in your repository so every key you create follows the same policy, and so an auditor, an investor or a new hire can read your whole spending policy in one file.
Your first job this week is to take the provider key out of every service except the gateway. Your second is to issue a $20 key to your next agent and watch what it spends.
Also read: Multi currency invoicing for startups without the 3% FX markup • How to Set Usage Limits Per Customer for LLM API Spend Before It Hurts • How to Pass Google OAuth Restricted Scope Verification Before Launch Day
This article is posted in AI News, check it out for more related stories.
Join the discussion #
Open in the community → Almost there. Sign in and your reply posts straight away.