To track LLM token usage and cost in your own application, write one append-only row for every model call: who called, which feature, which model, the input and output token counts from the provider’s response, the latency and the outcome. Compute cost from those tokens and a price table that you keep as data, then aggregate with plain SQL per user, per feature and per day. The same table answers “is this user within budget?” before the next call.
The schema and queries below ran on PostgreSQL 16, and every number is an example.
Where do the token counts come from?
From the response, not from your own tokenizer. Every major API returns a usage block with the call:
{
"model": "example-model",
"usage": { "input_tokens": 1200, "output_tokens": 350 }
}
Field names differ between providers (prompt_tokens and completion_tokens are also common), so
map them to your own two columns in one place. If a response ever arrives without the block, a
rough estimate from text length is a usable fallback, and better than recording zero.
Three details to check in your provider’s documentation:
- Streaming. Usage arrives at the end of the stream. OpenAI’s Chat Completions API sends it in
an extra final chunk when you set
stream_options.include_usage, and you may not receive that chunk if the stream is interrupted. Anthropic’s streaming events carry cumulative counts inmessage_delta. - Cached tokens. Input read from a prompt cache is billed at a lower rate and reported in its own field. Whether that field is part of the input count or sits next to it depends on the provider. Anthropic’s prompt caching guide defines total input as the sum of three fields.
- Reasoning tokens. Tokens a model spends thinking are billed as output even when you never see the text. OpenAI’s reasoning guide reports them as a detail of the output count.
If you use caching or reasoning models, add columns for those counts. Two columns are enough until then.
What should the usage table look like?
One row per call or per refused attempt, never updated:
CREATE TABLE llm_usage_event (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
feature VARCHAR(32) NOT NULL,
model VARCHAR(160),
plan VARCHAR(8),
input_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
cost_micros BIGINT NOT NULL DEFAULT 0,
latency_ms INTEGER,
outcome VARCHAR(24) NOT NULL,
blocked_reason VARCHAR(255),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT chk_llm_usage_outcome CHECK (
outcome IN ('ok', 'provider_error', 'blocked_rate_limit', 'blocked_budget')
)
);
CREATE INDEX idx_llm_usage_created ON llm_usage_event (created_at);
CREATE INDEX idx_llm_usage_user_created ON llm_usage_event (user_id, created_at DESC);
CREATE INDEX idx_llm_usage_plan_created ON llm_usage_event (plan, created_at);
The indexes match the reads: a time window for dashboards, one user’s history, and spend per plan
for the budget check. Add (model, created_at) if you break costs down by model.
Two columns deserve a comment. plan is the user’s plan at the time of the call. Store it on the
event so that a user who upgrades in the middle of the month does not move their earlier spend
from one bucket to the other. cost_micros is money as an integer, in millionths of a dollar, so
sums stay exact. Useful additions are a reference to the session the call belongs to and a flag
for calls answered by a fallback.
How do you record a call without breaking the request?
Record after the call, and never let the bookkeeping decide whether the user gets an answer:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(UsageEvent event) {
try {
repository.insert(event);
} catch (RuntimeException e) {
log.warn("Failed to record LLM usage for user {}", event.userId(), e);
}
}
Both parts matter. The try/catch means a failed insert
costs you one row of statistics, not a 500 for a request that worked. REQUIRES_NEW covers the
opposite case: a refused request throws, the caller’s transaction rolls back, and the event that
says “blocked” must survive that rollback. The annotation only works when the method is called
from another bean, as explained in
why @Transactional does not work.
Refusals and errors get a row too, with zero tokens and an outcome that says why. Without those
rows you cannot tell a quiet day from a day when half the requests hit a limit.
How do you turn tokens into cost?
Providers publish prices per million tokens, separately for input and output, and they change them.
Keep prices as data with a start date, and use BigDecimal, not double:
record ModelPrice(String model, LocalDate effectiveFrom,
BigDecimal inputUsdPerMillion, BigDecimal outputUsdPerMillion) {}
final class CostCalculator {
private final List<ModelPrice> prices;
CostCalculator(List<ModelPrice> prices) {
this.prices = prices;
}
// USD per million tokens times tokens is already micro-USD.
long costMicros(String model, LocalDate day, int inputTokens, int outputTokens) {
return prices.stream()
.filter(p -> p.model().equals(model) && !p.effectiveFrom().isAfter(day))
.max(Comparator.comparing(ModelPrice::effectiveFrom))
.map(p -> p.inputUsdPerMillion().multiply(BigDecimal.valueOf(inputTokens))
.add(p.outputUsdPerMillion().multiply(BigDecimal.valueOf(outputTokens)))
.setScale(0, RoundingMode.HALF_UP)
.longValueExact())
.orElse(0L); // unknown model: keep the tokens, cost stays zero
}
}
With invented prices of 0.50 and 1.50 USD per million tokens from January, lowered to 0.40 and 1.20 from 1 July, a call with 1200 input and 350 output tokens costs:
2026-06-30 1125 micro-USD (0.001125 USD)
2026-07-01 900 micro-USD (0.000900 USD)
A simpler variant also works: integer prices per model in configuration, long arithmetic, zero
for a model without a price, and the result stored on the event when it is written. Storing the
cost freezes it at the price of that day, which is what a budget needs.
Tokens are the facts and cost is derived from them, so always store the tokens. With a dated price
table you can recompute any period after you discover a wrong price.
How do you enforce a budget per user or per plan?
Check before the call, because afterwards the money is spent. Month-to-date spend is one query over the event table:
SELECT COALESCE(SUM(cost_micros), 0) AS total,
COALESCE(SUM(cost_micros) FILTER (WHERE plan = 'free'), 0) AS free_plan
FROM llm_usage_event
WHERE created_at >= ? AND created_at < ?
A layered setup has each AI request pass these checks, with every refusal recorded as an event:
- A monthly budget for the whole platform, with a switch that decides whether reaching it blocks requests or only raises an alert.
- A separate monthly pool for the free plan, so free usage cannot consume the budget that paying users rely on.
- A per-user daily request limit and a short cooldown between requests, kept in a small counter table.
Make the limits settings an admin can change at runtime, not constants in the code. A scheduled job can compare spend with the budget and notify admins once when it crosses a warning threshold and once when it is exceeded.
A sum followed by a call is not atomic, so parallel requests can overshoot the budget by a few calls. For a spend cap that is acceptable. For a hard per-user quota, count requests in a row you update atomically.
Which queries should an admin overview have?
Cost per day, in UTC:
SELECT (created_at AT TIME ZONE 'UTC')::date AS usage_day,
SUM(input_tokens) AS input_tokens,
SUM(output_tokens) AS output_tokens,
SUM(cost_micros) / 1000000.0 AS cost_usd
FROM llm_usage_event
WHERE created_at >= ? AND created_at < ?
GROUP BY usage_day
ORDER BY usage_day
The most expensive users:
SELECT user_id,
COUNT(*) AS calls,
SUM(input_tokens + output_tokens) AS tokens,
SUM(cost_micros) / 1000000.0 AS cost_usd
FROM llm_usage_event
WHERE created_at >= ? AND created_at < ?
GROUP BY user_id
ORDER BY SUM(cost_micros) DESC
LIMIT 20
Cost, refusals and latency per feature:
SELECT feature,
COUNT(*) FILTER (WHERE outcome = 'ok') AS ok_calls,
COUNT(*) FILTER (WHERE outcome LIKE 'blocked_%') AS blocked,
SUM(cost_micros) / 1000000.0 AS cost_usd,
ROUND(AVG(latency_ms)) AS avg_latency_ms
FROM llm_usage_event
WHERE created_at >= ? AND created_at < ?
GROUP BY feature
ORDER BY SUM(cost_micros) DESC
An admin panel needs little more than these aggregates: totals for a period, a series per day and a breakdown per model.
Should you store the prompts as well?
Not in this table. Counts and metadata are enough for cost tracking, and they are far less sensitive than what users type. If you need prompts for debugging or evaluation, put them in a separate table with a stated purpose and a retention period.
A usage event is still personal data, because it carries a user id. Delete the rows together with the account and include them in the user’s data export.
Summary
- Write one append-only event per model call and per refused attempt.
- Take token counts from the provider’s usage block, and read the documentation for streaming, cached and reasoning tokens.
- Record in a separate transaction, and swallow recording failures.
- Keep prices as dated data, compute with
BigDecimalor integer micro-units, and always store the tokens. - Check budgets before the call: per plan in money, per user in requests.
- Keep prompts out of the usage table, and include the table in the user data export.