Metering and capping model usage for every account you serve

APIClaudeKeyFree · Updated 2026-11-24 · 8 min read

A row of utility meters on a wall
Per-user meters make shared consumption visible before it runs out.

It happens more often than anyone admits: a company rolls out an AI coding tool or an internal assistant, usage takes off, and on some ordinary day in the middle of the month the whole organisation hits its limit. Nobody saw it coming because nobody was counting. In consumer apps the pattern is similar, with a handful of heavy users or a single buggy integration consuming most of the budget.

This guide is for developers who put a model behind their own app or internal tool and want to control how much each user, team or API client can consume. You will learn how to read token usage from responses, store it per user, enforce daily and monthly quotas, and switch heavy users to a cheaper route instead of cutting them off. The code uses an OpenAI-compatible client and works with Claude-compatible gateways, other providers or the keyless endpoint on this site.

Frequently asked questions

What is a token budget?

A token budget is a limit on how many input and output tokens a user, team or client may consume in a period, such as a day or a month. It is enforced by your application before sending requests to the model provider.

How does a token budget differ from a rate limit?

A rate limit caps how fast requests arrive, for example one per second. A budget caps the total amount consumed over a period. You usually need both: rate limits protect against bursts, budgets protect against steady overuse.

Should I count tokens or requests?

Tokens, in most cases. Requests vary enormously in size, from a ten-token question to a 30,000-token document. Counting requests treats them as equal and lets large requests slip through.

Where do I get exact token counts?

Most OpenAI-compatible APIs return a usage object with prompt_tokens, completion_tokens and total_tokens in each non-streaming response. For streaming, some providers include usage in the final chunk.

Which is better: hard cutoffs or soft limits?

Soft limits with a downgrade path usually give a better experience. When a user exceeds the budget, switch them to a smaller model or a slower queue rather than refusing outright, and reserve hard cutoffs for abuse.

Do output tokens cost more than input tokens?

With many commercial providers, output tokens are priced higher than input tokens. Check your provider's current pricing page and weight your budget accordingly if cost is the main concern.

How do I budget for agents that loop?

Give each agent run its own budget in addition to the user's, and stop the run when it is exceeded. Runaway loops are one of the most common causes of sudden budget exhaustion.

Does the free endpoint need per-user budgets?

It has its own per-IP limits, but if your server calls it on behalf of many users, they all share your server's IP. A per-user budget in your app keeps one user from exhausting the shared daily allowance.

Step by step

  1. Centralise model calls — Route every request through one function so usage can be measured and limits enforced in a single place.
  2. Record usage per call — Store prompt and completion tokens with user, feature, model and time from each response's usage object.
  3. Define budgets — Choose per-request, per-run, daily and monthly limits that match your provider's quotas and your costs.
  4. Check before sending — Estimate the request's cost and compare it with the user's remaining budget before calling the model.
  5. Degrade gracefully — Warn near the limit and route over-budget users to a cheaper or free model instead of blocking them.
  6. Report and alert — Send daily usage summaries and alerts when totals or individual users cross thresholds.

Why organisations run out unexpectedly

Provider limits are usually set at the organisation or workspace level. Individual usage is invisible unless you track it, so the first sign of trouble is often the limit itself. Agents and coding tools make this worse because a single task can use far more tokens than a person typing questions would, and several agents running in parallel multiply the effect.

Budgets do not need to be restrictive to be useful. Even generous per-user limits with alerts give you visibility, turn a surprise outage into a planned conversation, and protect everyone else from one runaway process.

Shared pools hide individual usage

When everyone draws from one balance, nobody feels responsible for it. Per-user tracking makes consumption visible and fair.

Agents consume in bursts

An agent exploring a codebase can send dozens of large requests in minutes. Without a cap per run, one task can use a day's worth of budget.

Reading usage from every response

The foundation is accurate measurement. Each non-streaming chat completion response from an OpenAI-compatible API includes a usage object with prompt and completion token counts. Record those numbers with the user ID, model, timestamp and feature name every time you call the model.

For streaming responses, check whether your provider can include usage in the final chunk. If not, estimate output tokens from the text length and correct with periodic reconciliation against the provider's usage reports.

Log at the call site

Put metering in the one function that all model calls go through. Scattered calls in different parts of the code are where untracked usage hides.

Record the feature too

Knowing that summaries use five times more tokens than chat replies helps you decide where to optimise, not just who to limit.

A nearly empty shared cookie jar
A shared pool with no tracking empties faster than anyone expects.

Choosing budget units and periods

Decide what you are protecting. If it is money, weight output tokens more heavily than input tokens according to your provider's price list, and budget in cost units. If it is a provider's token quota, budget in raw tokens. If it is the free endpoint's daily allowance of 10,000,000 tokens or 10,000 requests per IP, budget in both tokens and requests and reset at 00:00 UTC to match.

Periods should match how users think. Daily budgets prevent single-day blowouts, monthly budgets match billing cycles, and per-run budgets contain agents. Many apps use a daily and a monthly limit together.

Match the provider's reset

If your provider's quota resets at a specific time, align your daily budgets to it so your numbers and theirs agree.

  • Per-request cap: limits max_tokens and input size for any single call.
  • Per-run cap: limits the total for one agent task or workflow.
  • Daily cap per user: prevents single-day spikes.
  • Monthly cap per user or team: aligns with billing.
  • Global safety cap: stops all non-essential traffic before the organisation limit is hit.

A simple budget store and check

For a small app, a database table or even a key-value store with one counter per user and period is enough. Before each call, check the user's remaining budget. After each call, add the actual usage. The example below uses SQLite and the free endpoint to illustrate the pattern; swap the client configuration for your provider.

The check happens before sending the request, using a conservative estimate of the cost. The update happens after, using the real numbers from the response.

Estimate conservatively

The pre-check uses input length divided by four plus the maximum output. It overestimates slightly, which is the safe direction for a budget.

Use atomic updates

With concurrent requests, update counters in a single statement or transaction so two parallel calls cannot both slip under the limit.

import sqlite3, datetime
from openai import OpenAI

client = OpenAI(base_url="https://api.apiclaudekeyfree.com/v1", api_key="none")
db = sqlite3.connect("usage.db")
db.execute("CREATE TABLE IF NOT EXISTS usage (user TEXT, day TEXT, tokens INT, PRIMARY KEY (user, day))")
DAILY_LIMIT = 200_000

def today():
    return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")

def used(user):
    row = db.execute("SELECT tokens FROM usage WHERE user=? AND day=?", (user, today())).fetchone()
    return row[0] if row else 0

def add(user, n):
    db.execute("INSERT INTO usage VALUES (?, ?, ?) ON CONFLICT(user, day) "
               "DO UPDATE SET tokens = tokens + excluded.tokens", (user, today(), n))
    db.commit()

def chat(user, messages, max_tokens=800):
    estimate = sum(len(m["content"]) for m in messages) // 4 + max_tokens
    if used(user) + estimate > DAILY_LIMIT:
        raise PermissionError("daily budget reached")
    r = client.chat.completions.create(model="free-ai", messages=messages, max_tokens=max_tokens)
    add(user, r.usage.total_tokens if r.usage else estimate)
    return r.choices[0].message.content

print(chat("alice", [{"role": "user", "content": "Give me one tip for naming variables."}]))
Measuring cups of different sizes on a counter
Budgets work at several scales: per request, per run, per day and per month.

Degrading instead of refusing

Hard cutoffs frustrate users, especially in internal tools where the work still has to get done. A better pattern is tiered degradation. When a user passes, say, 80 percent of their budget, warn them. At 100 percent, route their requests to a cheaper model or a free backup rather than blocking. Only at a much higher threshold, or on signs of abuse, refuse outright.

The keyless endpoint here can serve as that lower tier. It serves free-ai, an independent open-weight model of about 35B parameters; it is not Claude, and this site is not affiliated with Anthropic. Quality on hard tasks will be lower than a top commercial model, so tell users when they are in reduced mode.

Warn early

A notice at 80 percent gives users time to prioritise. Most people use budgets more carefully once they can see them.

Downgrade transparently

Label responses from the fallback tier. Users accept lower quality more readily when they know why it changed.

Budgets for agents and automations

Agents need their own limits because they do not stop by themselves when they get stuck. Give each run a maximum number of model calls and a maximum token total, and end the run with a clear message when either is reached. Log the run's usage so you can see which tasks are expensive and why.

Automations such as scheduled reports or bulk processing jobs should have budgets too, separate from interactive users, so a nightly job cannot exhaust the allowance that people need during the day.

Cap iterations, not just tokens

A loop that makes many small calls can stay under a token cap while still wasting time. A maximum number of steps catches it.

Separate service accounts

Give each automation its own identity in your budget system, so its usage is visible and limited independently.

A highway exit leading to a slower road
Over-budget traffic can move to a slower lane instead of being stopped.

Dashboards and alerts

Budgets are only useful if someone looks at them. A simple daily report of the top users, top features and total consumption against the organisation's limit is often enough. Add alerts when total usage crosses thresholds, and when any single user or job consumes an unusual share.

Users appreciate seeing their own numbers, too. A small usage indicator in the interface, similar to the widgets people build to watch their subscription windows, reduces surprise and support questions.

Review the numbers regularly with the people who use the tool. Budgets that are too tight push users toward workarounds, while budgets that nobody ever approaches may be hiding waste that a closer look at per-feature usage would reveal.

Alert on the trend

Projecting the month's total from the first week's usage gives you time to adjust budgets or buy more capacity before the limit hits.

Protecting your provider account

Per-user budgets also protect the provider relationship. If one of your users abuses your service, their traffic appears as yours to the provider. Caps and per-user rate limits contain the damage and make your traffic pattern look like a well-run product. The article on what to do if an AI account is suspended covers why that matters.

Budgets keep your billing predictable as well. Combined with low-balance alerts, they prevent the scramble described in why API credit purchases fail, where a depleted balance meets a payment problem at the worst possible time.

Per-user rate limits too

Pair budgets with a per-user request rate, so a script hammering your endpoint is throttled before it consumes its whole budget in minutes.

A fuel gauge near empty on a car dashboard
Early warnings give users time to adjust before the limit hits.
Try the free API

Send a test request to the keyless, OpenAI-compatible endpoint on the home page and see how it fits your project.

Read also