Track LLM Token Usage Per User: A Practical Guide
If you're building a product on top of an LLM and more than one person uses it, you need to know how many tokens each individual user consumes — not just your total API bill. This matters for three reasons: you can enforce per-user quotas, you can bill usage-based pricing fairly, and you can spot abuse or runaway costs before they show up on your invoice.
The short answer: every LLM response includes token counts in its metadata, so you need to (1) tag every request with a user identifier, (2) capture the usage object from the response, (3) write it to a database keyed by user and timestamp, and (4) aggregate it for dashboards, quotas, or billing. None of this requires a separate analytics product — it's a logging problem with a cheap storage backend.
Why "total usage" isn't enough
Anthropic's and OpenAI's billing dashboards show you organization-wide totals. That's useless if you're running a SaaS where 500 users share one API key. You can't tell which customer is burning through 2M tokens a day versus which one sends three requests a week. Without per-user attribution you can't:
- Enforce a free-tier limit (e.g. 50K tokens/month per user)
- Charge usage-based add-ons accurately
- Detect a single compromised account hammering your API
- Explain to a customer why their bill is higher than expected
Per-user tracking turns a single API bill into a ledger you can actually query.
Step 1: Attach a user ID to every request
The cleanest pattern is to generate a stable internal user ID (not an email, which can change) and pass it alongside every LLM call — either in your own request wrapper or as metadata in the API call itself. If you're calling the LLM provider directly, you typically store this association in your own backend logic since the provider has no concept of your end-users.
async function callModel(userId, messages) {
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages
})
});
const data = await response.json();
await logUsage(userId, data.usage);
return data;
}
The userId never goes to the model itself — it's your own tracking key, used only in logUsage.
Step 2: Capture the usage object
Every well-formed LLM response includes input and output token counts. With SubToAPI, every /v1/messages call returns a usage field with input_tokens and output_tokens — the same structure you'd get from calling Claude directly, since SubToAPI is just Claude behind your own API key. See the messages docs for the exact response shape.
{
"id": "msg_01...",
"usage": {
"input_tokens": 412,
"output_tokens": 187
}
}
If you're streaming responses, the usage totals usually arrive in the final event of the stream rather than per-chunk — check the streaming docs for how that's delivered so you don't double-count or miss it.
Step 3: Store it against the user
You don't need a specialized time-series database to start. A simple table works fine:
CREATE TABLE token_usage (
id SERIAL PRIMARY KEY,
user_id TEXT NOT NULL,
input_tokens INT NOT NULL,
output_tokens INT NOT NULL,
model TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
Write a row on every call. Index on (user_id, created_at) so monthly rollups and quota checks stay fast even at millions of rows.
async function logUsage(userId, usage) {
await db.query(
`INSERT INTO token_usage (user_id, input_tokens, output_tokens, model)
VALUES ($1, $2, $3, $4)`,
[userId, usage.input_tokens, usage.output_tokens, "claude-sonnet-4-5"]
);
}
Step 4: Aggregate for quotas and billing
Once you're logging per request, aggregation is just SQL:
SELECT
user_id,
SUM(input_tokens) AS total_input,
SUM(output_tokens) AS total_output
FROM token_usage
WHERE created_at >= date_trunc('month', now())
GROUP BY user_id
ORDER BY total_output DESC;
Run this on a schedule (cron, or on-demand before each request) to enforce quotas. For real-time enforcement — blocking a request before it's sent — check the user's running total against their limit first, and reject or downgrade the request if they're over.
async function checkQuota(userId, monthlyLimit) {
const { rows } = await db.query(
`SELECT SUM(input_tokens + output_tokens) AS total
FROM token_usage
WHERE user_id = $1 AND created_at >= date_trunc('month', now())`,
[userId]
);
const used = Number(rows[0].total) || 0;
return used < monthlyLimit;
}
Handling multiple models and pricing tiers
If you call more than one model (say Haiku for cheap tasks and Sonnet for complex ones), store the model name per row, since input and output tokens are priced differently per model. Calculate cost at read time, not write time — pricing changes, and you want to re-derive historical cost without rewriting old rows. A lightweight cost-per-token lookup table joined against token_usage at query time keeps this flexible.
Where SubToAPI fits
If you're already routing LLM traffic through SubToAPI, you get per-key usage metadata on every response without building your own proxy layer. Each application key behaves like a normal API key, so you can issue one key per user or per tenant, or keep a single key and do the user-level attribution in your own logs as described above. Either way, the usage object on every response is your source of truth — you're just deciding where to store and aggregate it. Check pricing if you're evaluating whether to run this logging layer yourself or let it ride on top of an existing API gateway, and the quickstart if you want to see the full request/response cycle before wiring up your database.
questions
Do I need a separate analytics tool to track per-user token usage? No. A single table with user ID, token counts, model, and timestamp is enough to start. You only need something more sophisticated once you're aggregating across millions of rows or need real-time dashboards.
Should I count input and output tokens separately? Yes. Most providers price input and output tokens differently, often by a factor of 3-5x, so lumping them together makes cost calculations inaccurate. Store them as separate columns and compute cost at query time.
What if I'm streaming responses — can I still track usage per user? Yes. Streaming responses typically include the final token usage in the last event of the stream rather than per-chunk, so capture it when the stream closes and log it the same way you would a non-streaming response.