API Gateway with Per-User Quotas: A Practical Guide
What "per-user quotas" actually means in an API gateway
An API gateway with per-user quotas enforces limits per individual end-user of your application, not just per application-level API key. If you're building a SaaS product on top of an LLM provider like Claude, the distinction matters: a single API key might serve thousands of your customers, but you need to know — and limit — how much each of them consumes. Without per-user quotas, one heavy user can burn through your entire monthly budget while everyone else gets throttled or your bill spikes unexpectedly.
The core requirement is always the same: attribute every request to a user ID, track consumption against that ID (requests, tokens, or cost), and reject or throttle requests once that user crosses a limit — ideally before the request hits your upstream provider, not after. The rest of this article covers the quota models you can choose, how to implement enforcement correctly, and where a managed gateway saves you weeks of work.
Quota models: pick one before you build anything
There are four common ways to define "quota," and mixing them up is the most common design mistake.
- Request count — simplest to implement, worst at predicting cost. A user making 100 tiny requests and a user making 100 huge ones get treated identically.
- Token count — more accurate for LLM workloads since cost tracks tokens, not requests. Requires parsing usage from each response.
- Cost-based (currency) — the most accurate representation of what you actually care about, but requires mapping token counts to provider pricing and keeping that mapping current.
- Concurrency limits — caps how many requests a user can have in flight simultaneously, independent of volume. Useful for preventing abuse patterns (e.g., one user opening 50 parallel streams) even when volume quotas haven't been hit.
Most production systems combine at least two: a token or cost quota for billing-aligned limits, plus a concurrency limit for abuse prevention. If you're metering anything LLM-related, token-based quotas are the right default — they correlate directly with your upstream bill.
Where enforcement should live
Enforcement has to happen at the gateway layer, before the request reaches the upstream API. Checking quotas in application code after the response comes back is too late — you've already paid for the tokens.
A typical flow:
- Request arrives at the gateway with a user identifier (JWT claim, API key suffix, session token — whatever maps to your internal user ID).
- Gateway looks up current usage for that user in this billing period.
- If usage is below quota, the gateway forwards the request upstream and records the resulting token usage against the user's counter.
- If usage is at or above quota, the gateway returns a 429 immediately without calling upstream.
The tricky part is step 3 under concurrency. If ten requests from the same user arrive within milliseconds, you need atomic increment-and-check, not read-then-write — otherwise all ten can slip through before any counter updates. This is why most people reach for Redis (INCRBY + EXPIRE, or a Lua script for atomicity) rather than a plain SQL row with read-modify-write logic.
A minimal Redis-based quota check
// Atomic check-and-increment using a Lua script in Redis
const script = `
local current = tonumber(redis.call('GET', KEYS[1]) or '0')
local limit = tonumber(ARGV[1])
local cost = tonumber(ARGV[2])
if current + cost > limit then
return 0
end
redis.call('INCRBY', KEYS[1], cost)
redis.call('EXPIRE', KEYS[1], ARGV[3])
return 1
`;
const allowed = await redis.eval(script, {
keys: [`quota:${userId}:${periodKey}`],
arguments: [String(monthlyTokenLimit), String(estimatedTokens), String(secondsUntilReset)],
});
if (!allowed) {
return res.status(429).json({ error: "quota_exceeded" });
}
This covers the hard part — atomicity — but you still need to reconcile the estimated token cost (checked before the call) against the actual usage returned by the provider after the call completes, and adjust the counter accordingly. Streaming responses complicate this further since you don't know final token counts until the stream ends.
Build vs. buy
Building this correctly means handling: atomic counters, period resets (daily/monthly), reconciliation between estimated and actual token usage, per-user dashboards for your support team, and graceful 429 responses with retry-after headers. None of this is conceptually hard, but it's a few weeks of work before you write a single line of your actual product.
If your API layer is built on Claude, SubToAPI gives you this as part of turning your existing Claude access into an HTTPS API. You generate scoped sub_live_... keys per application or per customer, and usage metadata — tokens in, tokens out, request counts — is tracked and exposed per key through the dashboard. For teams that need per-seat limits rather than fully custom per-end-user billing logic, this covers the common case without custom gateway code: issue one key per user or per tenant, set your plan tier, and read consumption back through the API instead of building Redis counters yourself.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Summarize this ticket."}]
}'
Each key's usage is visible in the dashboard, so if you're issuing one key per customer, per-user quotas become a matter of plan selection rather than infrastructure. See the quickstart and messages endpoint docs for the full request format, and pricing for plan limits across Solo, Team, and Scale tiers.
What to log regardless of which route you take
Whether you build your own gateway or lean on a managed one, make sure you're capturing:
- User ID, timestamp, and endpoint for every request
- Token counts (input/output) per request, not just totals
- Quota state at time of request (remaining, not just limit)
- 429 events separately from successful requests, so you can tell quota exhaustion apart from provider-side rate limiting
This data is what lets you answer "why did this customer get throttled" six months from now without guessing.
Questions
Does per-user quota enforcement need to happen synchronously on every request? Yes, for the check itself. Asynchronous batch reconciliation is fine for correcting estimates after the fact, but the initial allow/deny decision must happen before the request is forwarded, otherwise users can exceed quota during traffic bursts.
What's the difference between rate limiting and quota enforcement? Rate limiting controls request frequency over short windows (e.g., 10 requests/second) to protect infrastructure. Quotas control total consumption over longer periods (e.g., 1M tokens/month) to control cost and fairness. Most gateways need both, enforced independently.
Can I do per-user quotas with a single shared API key from my LLM provider? Yes, as long as your gateway maps incoming requests to internal user IDs and tracks usage against those IDs itself — the provider never sees per-user identity. Alternatively, issuing distinct keys per user (as with SubToAPI) makes quota tracking and revocation per-user simpler to reason about.