Skip to content
mentoor

Topic 3 of 4 · 5 min read

Enforcing per-user quotas and spend caps

Goal: Implement a per-user token quota that stops runaway usage before the account-wide provider limit is hit.

Count each user's token use on your side, check it before every model call, and stop with a clear message when the budget is gone. The provider's limits protect the provider. Only your own limits protect your users from each other.

Check yourself · 1 of 3

Why count tokens per user instead of only counting requests?

Choose one answer

Why it matters

Provider limits apply to your whole account. If one user burns through the allowance with a loop or a giant paste, every other user gets a 429 error. A workspace spend limit stops the bill but also stops the product. A per-user quota fixes both: one person can hit their own ceiling without touching anyone else.

How to do it

  1. Pick what to count. Tokens are better than requests, because one request may hold ten words or a whole book. The provider's response reports input and output tokens used. Read them from there.
  2. Pick the window and the plan. For example a daily token budget for the free plan and a larger monthly one for paid plans. Store the plan limits in config, not in code scattered across routes.
  3. Check before the call. Load the user's usage for the window and compare with the limit. Reserve an estimate for the coming call (input size plus max_tokens) so one big request cannot jump far past the limit.
  4. Record after the call. Add the real token counts to the user's usage. Use an atomic increment (a database UPDATE ... SET used = used + n, or Redis INCRBY), because two requests at once will otherwise overwrite each other.
  5. Cap each request too. Set a maximum input length and max_tokens, so one call has a ceiling.
  6. Tell the user. Return a specific message and status, and say when the quota resets. Also add an account-wide spend alert and a workspace limit as the last backstop.

Before and after

Before, the route calls the model and hopes:

const out = await provider.chat({ messages });
return Response.json({ text: out.text });

After, it checks and records:

const used = await usage.get(user.id, "day");
const limit = PLANS[user.plan].dailyTokens;
const reserve = estimateTokens(message) + MAX_OUT;
if (used + reserve > limit) {
  return Response.json(
    { code: "QUOTA_REACHED", resetsAt: usage.resetAt("day") },
    { status: 429 },
  );
}
const out = await provider.chat({ messages, max_tokens: MAX_OUT });
await usage.add(user.id, "day", out.usage.input + out.usage.output);
return Response.json({ text: out.text });

What goes wrong

  • Counting requests, not tokens. A user sends five huge requests and stays "under the limit".
  • Read, then write. Two parallel calls both see 900 of 1,000 used and both pass.
  • Silent failure. The user sees "Something went wrong" and retries, which wastes more budget. Say what happened and when it resets.
  • Only an account limit. The first heavy user ends the day for everybody.

Examples

Plan table in config

export const PLANS = {
  free: { dailyTokens: 20_000, maxInput: 4_000 },
  pro: { dailyTokens: 400_000, maxInput: 32_000 },
} as const;

Routes read from this one object. Changing the free allowance is a one-line change, and tests can assert that every plan has a limit.

The loop that ate the day

A user's script calls /api/chat in a loop with a long document each time. Without per-user limits, the account-wide allowance is gone by noon and everyone gets 429 errors. With a per-user daily budget, the script hits its own ceiling after a few calls, receives QUOTA_REACHED with a reset time, and other users are not affected.

Key points

  • Count tokens per user from the usage the provider returns, not just the number of requests.
  • Check the budget before the call, reserving the expected size, and record the real usage after it.
  • Use an atomic increment for the counter so parallel requests cannot both pass on stale numbers.
  • Cap input length and max output tokens on every request as well as the per-user total.
  • Reply with a specific quota message and a reset time; keep a workspace spend limit as the final backstop.

Common mistakes

  • Limiting requests per minute and assuming that also limits cost.
  • Checking the quota with a read and updating it later without an atomic increment.
  • Returning a generic failure when a quota is reached, so users keep retrying.
  • Relying on the provider's account limit as the only guard.

Check yourself · 2 of 3

Two requests from the same user arrive at once, and each reads 900 of 1,000 tokens used before either writes. What fixes this?

Choose one answer

Check yourself · 3 of 3

A user reaches their daily token budget. Which response is best?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic