Per-User API Keys for AI Agents: The Proxy Pattern

🤖 Agents 2026-07-17 5 min read

If your agent calls a paid model API on behalf of users, one shared key means one quota, one revocation for everyone, and no way to tell which customer costs the most.

📜 Table of Contents

📖 Keep reading

If your AI agent has users, and it calls a paid model API, the question of whose key is being spent gets answered badly by default. Most projects ship with one key in an environment variable, and every user's request draws from it. That works until it doesn't, and when it stops working the failure is expensive.

A machined brass key suspended in a dark chamber, lit by a narrow amber beam
Store the hash and a display prefix, never the key itself — the same pattern Stripe and GitHub use.

What a shared key costs you

No per-user limit. A single key means a single quota. One user running a loop over your endpoint can exhaust the whole budget, and nothing in the provider's dashboard will tell you who did it.

No revocation granularity. If a key leaks, you rotate it and every user is logged out at once. There is no way to cut off one abuser.

No attribution. Your provider bill is one line. You cannot answer "which customer costs me the most," which is the first question any pricing decision needs.

Shared blast radius. A prompt injection that extracts the key from one conversation gets the key for everyone.

The proxy pattern

The fix is architectural, not a library: your users never see the upstream provider key. They authenticate to you, and you hold the provider key server-side.

client → your API (user key) → your proxy → provider API (your key)

Three things happen at the proxy layer:

  1. Resolve the incoming user key to an account.
  2. Check that account's allowance and rate limit.
  3. Forward the request with the real provider key attached server-side.

The user key never has to be a provider key. It can be an opaque token you generate, which means you can revoke, scope, and expire it independently of anything upstream.

Storing the keys

Treat user API keys like passwords, because that is what they are. Specifically:

CREATE TABLE api_keys (
  id           uuid PRIMARY KEY,
  user_id      uuid NOT NULL REFERENCES users(id),
  key_prefix   text NOT NULL,          -- "sk_live_a1b2" for display
  key_hash     bytea NOT NULL UNIQUE,  -- sha256 of the full key
  monthly_cap  integer,                -- in cents
  revoked_at   timestamptz,
  created_at   timestamptz DEFAULT now()
);

Per-key metering

Every request through the proxy needs to increment a counter keyed by user_id and the current billing period. Two reasons this cannot be optional:

Enforcement. Without a counter there is no cap, only a hope. Check the counter before forwarding, not after — post-hoc accounting means the overspend already happened.

Attribution. The provider's token counts come back in the response. Record them against the user, not against the whole site. Prompt tokens and completion tokens are priced differently and should be stored separately if you intend to bill accurately.

Redis with an expiry set to the end of the billing period is the usual implementation. An atomic INCRBY followed by a comparison against the cap is enough; you do not need a distributed lock.

Rate limiting per key

Quota and rate limit are different controls and you need both. Quota is monthly spend. Rate limit is requests per minute, and its purpose is protecting your upstream account from being throttled on behalf of one noisy user.

Return 429 with a Retry-After header. An agent that receives a bare 429 will usually retry immediately, which makes the problem worse. Telling it how long to wait is the difference between a client that backs off and one that hammers you.

Revocation and rotation

A revocation is a row update: set revoked_at. The proxy rejects any key whose account row has a non-null revoked_at, and the user is unaffected beyond that one key.

Rotation matters because keys leak through logs, screenshots, and repos. Two rules:

What this does not solve

Prompt-injected exfiltration of the provider key. The whole point of the proxy is that the model never sees a key it could leak. If you are passing the provider key into a tool result or a system prompt, the proxy is decorative.

Abuse by a legitimate user. Per-user keys tell you who spent the money. They do not stop that person from spending it if your cap is too high. Set the cap from your pricing, not from what feels generous.

Cost estimation. Token counts vary per request and per model. If you pre-charge users, you will be wrong sometimes; decide in advance whether you round up or absorb it.

Minimum viable implementation

  1. Add api_keys with hash, prefix, and scopes.
  2. Put a proxy route in front of every provider call.
  3. Meter prompt and completion tokens per user per period.
  4. Enforce the cap before forwarding.
  5. Return 429 with Retry-After.
  6. Support two live keys so rotation does not require a cutover.

Six steps, and the first one is the only irreversible decision — if you start by storing keys in plaintext because it is easier, migrating later means every user regenerates.

Related Articles
2026-08-07
World's First AI Agent Ransomware Attack Exposed: It Found the Vulnerability Itself, Stole the Keys Itself, Encrypted the Database Itself—Then Screwed It Up
2026-07-16
AI Agent Context Window Management 2026
2026-07-16
AI Agent Permissions: Greater Access, Greater Risk
2026-07-26
OpenAI Agent Goes Rogue During Safety Test, Hacks Hugging Face
2026-07-19
AI Agent Frameworks 2026: LangChain vs CrewAI vs AutoGen
2026-08-06
MCP TypeScript SDK (13,080 Stars) 2026: Build Your First Model Context Protocol Server in TypeScript

Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.

💬 Comments (0)

No comments yet. Be the first!

Login to comment