Why per-user token budgets beat one global rate limit
Freemium AI apps rarely fail because the model is too costly in aggregate. They fail because one user can consume a disproportionate share of the budget before anyone notices. A global requests-per-minute limit does not protect you: a single script can send long prompts, receive long completions, and drain the pool meant for everyone. Per-user token budgeting turns a vague fair-use policy into an enforceable product rule.
Token budgets also make the experience predictable. Users can see what remains, know when the window resets, and choose to wait, shorten the request, or upgrade. That is far better than an opaque error after a failed call.
A budget model that survives real traffic
Separate buckets for free daily allowance, paid monthly allowance, and feature-specific caps such as chat, summaries, and code review.
Use a calendar or rolling window, store reset timestamps in UTC, and display them in the user's timezone.
Reserve tokens before the call and reconcile with actual usage after it. Charging only after the response lets concurrent requests overshoot.
Derive max_tokens from the remaining budget. A gate that allows a long completion when little budget remains is not a gate.
Return used, remaining, and reset_at in your own API and UI so clients can degrade before the provider returns an error.
Runnable: SQLite-backed per-user token gate
The snippet below uses SQLite for clarity. In production, use Postgres or Redis with the same reserve-then-reconcile pattern. The prompt-token estimate is deliberately rough; the provider's usage object is the source of truth after the call.
import os
import sqlite3
from datetime import datetime, timezone
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
DB = 'token_budgets.db'
FREE_DAILY_TOKENS = 20_000
MAX_OUTPUT_TOKENS = 800
def init_db():
with sqlite3.connect(DB) as con:
con.execute('''
CREATE TABLE IF NOT EXISTS usage (
user_id TEXT NOT NULL,
day TEXT NOT NULL,
tokens INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, day)
)
''')
def today():
return datetime.now(timezone.utc).strftime('%Y-%m-%d')
def used_today(user_id):
with sqlite3.connect(DB) as con:
row = con.execute(
'SELECT tokens FROM usage WHERE user_id=? AND day=?',
(user_id, today()),
).fetchone()
return row[0] if row else 0
def reserve(user_id, amount):
with sqlite3.connect(DB) as con:
con.execute('BEGIN IMMEDIATE')
row = con.execute(
'SELECT tokens FROM usage WHERE user_id=? AND day=?',
(user_id, today()),
).fetchone()
used = row[0] if row else 0
if used + amount > FREE_DAILY_TOKENS:
con.rollback()
raise RuntimeError('Daily token budget exceeded')
con.execute(
'''INSERT INTO usage(user_id, day, tokens) VALUES(?,?,?)
ON CONFLICT(user_id, day) DO UPDATE SET tokens=tokens+excluded.tokens''',
(user_id, today(), amount),
)
con.commit()
def release(user_id, amount):
with sqlite3.connect(DB) as con:
con.execute(
'UPDATE usage SET tokens=MAX(0, tokens-?) WHERE user_id=? AND day=?',
(amount, user_id, today()),
)
con.commit()
def reconcile(user_id, reserved, actual):
delta = actual - reserved
if delta == 0:
return
with sqlite3.connect(DB) as con:
con.execute(
'UPDATE usage SET tokens=MAX(0, tokens+?) WHERE user_id=? AND day=?',
(delta, user_id, today()),
)
con.commit()
def chat_with_budget(user_id, prompt):
remaining = FREE_DAILY_TOKENS - used_today(user_id)
estimated_prompt = max(1, len(prompt) // 4)
if remaining <= estimated_prompt:
raise RuntimeError('Not enough daily budget for this prompt')
max_out = min(MAX_OUTPUT_TOKENS, remaining - estimated_prompt)
reserved = estimated_prompt + max_out
reserve(user_id, reserved)
try:
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=max_out,
)
except Exception:
release(user_id, reserved)
raise
reconcile(user_id, reserved, response.usage.total_tokens)
return response.choices[0].message.content
if __name__ == '__main__':
init_db()
print(chat_with_budget('demo-user', 'Explain fair-use token budgeting briefly.'))
The gate refuses prompts that cannot fit, caps output to the remaining budget, and corrects the reservation with actual usage. Replace SQLite with your database and the policy logic stays the same.
Throttling behavior that feels fair
Throttling should degrade in steps, not snap shut. Shorten output, route low-stakes requests from deepseek-v4-pro to deepseek-v4-flash, queue non-urgent jobs, and only then show a hard stop. Users tolerate limits when the product explains them and offers a next step.
Warn early with a one-click shorter answer, not just a paywall.
Hard-cap the free bucket; let paid users top up or move to a higher bucket.
Use an async queue for bulk work so interactive chat keeps its budget.
Use idempotency keys for retries so a network error does not charge the same request twice.
Abuse patterns that per-user budgets do not fix
Per-user budgets are only as good as user identity. Free-tier abuse often looks like many accounts, not one heavy account. Watch sign-up velocity from the same device or IP, identical prompts across accounts, and retry loops that burn budget after model errors. Require email verification, rate-limit account creation, and keep a looser per-IP and per-device budget alongside the per-user budget. Do not punish shared offices or schools with a single tight IP cap; layer signals instead.
Budget by feature as well. A code-linting feature and a chatbot have different token profiles. One shared bucket makes the cheap feature pay for the expensive one, and it hides which feature is actually driving usage.
Cost-aware routing without hardcoding rates
Use deepseek-v4-flash as the default for interactive and high-volume work. Reserve deepseek-v4-pro for tasks where the extra capability changes the outcome, and check the user's remaining budget before escalating. Off-peak usage costs less, and cache hits are cheaper, so batch non-urgent work when possible and design prompts with stable prefixes to improve cache reuse. Do not hardcode rates; they change. Read current numbers at aicreditsapi.com/deepseek-prices and keep routing rules qualitative.
AiCredits sells DeepSeek API credits to international developers with card or PayPal, no Chinese phone or bank required, which simplifies the billing side. Your application still owns the fair-use policy.
| Tier | Budget source | Default model | Overflow behavior |
|---|---|---|---|
| Free | Daily per-user allowance | deepseek-v4-flash | Hard stop with reset time and shorter-answer option |
| Paid | Monthly per-user allowance | deepseek-v4-flash; deepseek-v4-pro for approved tasks | Queue or prompt top-up |
| Team/admin | Shared pool with per-member caps | deepseek-v4-pro for heavy tasks | Alert owner and require approval |
Instrumentation that pays for itself
Log user_id, feature, model, prompt tokens, completion tokens, cache hit flag if available, and whether the request was throttled. Track budget exhaustion by feature and cohort. High exhaustion on a core feature means the free allowance is too small or the prompt is too verbose. High exhaustion on a secondary feature often means abuse.
Expose a usage endpoint that returns used, remaining, and reset_at. Client apps can disable the send button before the API returns an error, which is a better experience than showing a failure after a long wait.
A fair-use policy is a product promise. If users cannot see the budget, they will experience it as a bug.
FAQ
Both. Reserve a conservative estimate of prompt plus max output before the call, then reconcile with the provider's total usage. If you count only completion tokens, long prompts can slip past the cap.
There is no universal number. Start from the usage you can absorb per active free user, then measure exhaustion and conversion. Token counts are a product decision; current rates are at aicreditsapi.com/deepseek-prices.
Yes. Pro costs more than flash, so give it a smaller sub-budget or require a paid tier or approved task. Route by task type, not by user request.
Combine email verification, device and IP velocity limits, prompt similarity checks, and a per-IP budget that is looser than the per-user budget. Do not rely on one signal.