LLM Token Usage Tracking: Measure & Control API Spend

LLM Token Usage Tracking: Measure & Control API Spend

What if the biggest line item in your AI budget was something you never actually counted? For most teams building on large language models, that is exactly the situation. Every prompt, every reply, every retried request is billed in tokens, yet many products ship with almost no visibility into how many tokens they consume until the monthly invoice arrives and surprises everyone.

This guide walks through how token tracking actually works, where the numbers come from, which traps catch people out, and what a workable tracking setup looks like in practice.

Why Tokens Are the Only Unit That Matters

LLM providers do not bill by word or by character. They bill by token, which is a chunk of text that usually corresponds to a few characters or a partial word. The same sentence can produce different token counts under different models, because each model family uses its own tokenizer. OpenAI’s documentation describes tokens as common character sequences and offers a public tool that shows exactly how a piece of text splits into tokens.

That matters for tracking because you cannot reliably estimate usage by counting words and multiplying. A rough rule of thumb (about four characters per token in English) is fine for back-of-envelope math, but it drifts badly with code, JSON, non-Latin scripts, and long identifiers. The only trustworthy number is the one the API itself reports.

Tokens also govern context windows, the maximum amount of text a model can consider at once. A long chat thread accumulates tokens with every turn, so a conversation that starts cheap can quietly approach the limit. Tracking therefore serves two purposes: cost control and preventing requests that fail because the input no longer fits.

Where the Numbers Come From

Where the Numbers Come From

The good news is that providers hand you the data. Every API response typically includes a usage object describing how many tokens went in and how many came out. The exact field names differ by vendor, so any tracking code needs a small adapter layer. (News)

Provider style Typical input field Typical output field Notes
OpenAI-style chat APIs `prompt_tokens` `completion_tokens` Usually also returns `total_tokens`
Anthropic-style message APIs `input_tokens` `output_tokens` Reported in a usage field per response
Self-hosted or open models Depends on server Depends on server Often mirrors one of the above formats

The practical rule: read the usage object from the response rather than recomputing counts locally. Local tokenizers are useful for pre-flight checks, but they can drift from the server’s count when model versions change. If you want to understand how text is split into tokens before sending a request, the interactive tokenizer explanation from OpenAI shows the mechanics clearly.

The Streaming Problem Nobody Warns You About

Streaming responses are where naive tracking breaks. When you stream tokens to the user for a faster interface, the response arrives in fragments, and usage figures may only appear at the very end of the stream, sometimes in a final chunk. If your code reads the first chunk and moves on, you may record zero usage for a request that cost real money.

What actually works in practice:

  • Always consume the stream to completion, even if the user closes the tab, so the final usage chunk is captured.

  • Log a fallback estimate when no usage data arrives, and mark that record as estimated so it does not pollute exact totals.

  • Version your logging schema, because providers have changed streaming usage behavior across API versions.

The last point is easy to underestimate. Teams that hard-coded assumptions about streaming usage in early 2023 found their dashboards silently wrong after an API update. A schema version field costs nothing and saves a painful audit later.

Counting Is Not the Same as Costing

Raw token counts are necessary but not sufficient. Turning them into money requires per-model pricing, and pricing has grown complicated. Several providers now offer prompt caching, where repeated input prefixes are billed at a discount, and some offer cheaper rates for batch jobs. A simple tokens-times-price calculation will overstate spend for any workload with heavy prompt reuse, such as a chatbot with a long fixed system prompt.

A more accurate model looks like this:

  • Separate cached input tokens from fresh input tokens.

  • Separate output tokens, which are usually priced higher.

  • Apply the correct per-model rate for the date of the request, not today’s price.

  • Store the computed cost alongside the raw counts so historical reports stay stable when prices change.

Storing cost at write time, rather than recomputing it at read time, is one of the small design choices that separates a dashboard people trust from one they argue about.

Building a Tracking Pipeline That Survives Contact With Production

Most teams start with logs and graduate to something structured. A pipeline that holds up under real traffic usually has four layers.

Layer one: per-request capture

Wrap every model call in a single function that records the model name, the feature or endpoint that triggered the call, the user or tenant identifier, input and output token counts, latency, and whether the response was streamed. Centralizing this prevents the classic failure where three different services each log tokens slightly differently.

Layer two: attribution

Tokens mean little without knowing who spent them. Attribute usage to a tenant, feature, and request type at minimum. Without attribution, a spike in spend is just a number; with it, you can see that one customer’s batch job doubled overnight.

Layer three: aggregation and storage

Write raw events to a store that handles time-series queries well, then roll up hourly and daily totals. Keep raw events long enough to investigate anomalies, but be realistic about cost: token-level event logs can grow fast.

Layer four: alerting and budgets

Set thresholds on spend per tenant, per feature, and overall. Alert on rate of change, not just absolute totals, because a gradual creep is harder to notice than a cliff. Many teams also enforce hard caps per tenant so a runaway loop cannot burn through a month’s budget in an hour.

For teams that want a standard rather than a bespoke format, the OpenTelemetry project has published semantic conventions for generative AI spans, including attributes for input and output token usage. These conventions were still marked experimental at the time of writing, so treat them as a sensible target shape rather than a frozen standard. Instrumentation libraries built on OpenTelemetry can record token usage automatically, which saves a lot of hand-written logging code.

Common Mistakes and What to Do Instead

A few patterns show up again and again in post-mortems about AI spend.

Counting only successful requests. Failed and retried calls still consume tokens, especially when a request times out after the model has already generated output. Log attempts, not just successes.

Ignoring retries and agent loops. An agent that calls a model five times per user action multiplies usage invisibly. Tag each call with a trace or conversation identifier so a single user action can be reconstructed end to end.

Trusting estimates for billing. Estimates are fine for dashboards and terrible for invoicing customers. If you pass costs through, reconcile against provider invoices monthly.

Forgetting the context growth curve. A chat that appends full history every turn grows quadratically in token cost over a long session. Summarizing or truncating history is a product decision with a direct cost consequence.

No ownership. Token spend that belongs to nobody gets optimized by nobody. Assign each feature an owner who sees its usage weekly.

If you want a concrete example of how teams restructure reporting around transfer and usage costs, this walkthrough of a clearer way to track cloud data transfer costs covers a parallel problem in cloud billing and the reporting habits that fix it.

Tooling Options, Briefly

The market splits into three rough categories. Provider dashboards show aggregate usage and are fine for a first look, but they rarely break spend down by your product features. Open-source observability tools such as Langfuse record prompts, responses, and token usage, and can be self-hosted, which matters if prompts contain sensitive data. General APM and tracing platforms increasingly accept generative AI spans, so token usage sits next to latency and error rates in one place. (NIST AI Risk Management Framework)

There is no single cross-vendor standard for token accounting yet. That is the honest state of things. The closest thing to a shared convention is the OpenTelemetry work mentioned above, and it is worth watching. In the meantime, the safest design is a thin internal schema you control, with adapters that translate each provider’s usage fields into it.

Practical Tips That Save Real Money

Beyond instrumentation, a handful of habits consistently reduce token spend without hurting quality. Trim system prompts and remove examples that no longer earn their place. Cap output length where the product allows it. Use smaller models for classification and routing tasks. Cache repeated prompt prefixes where the provider supports it. Batch non-urgent work. And review the top ten most expensive requests each week, because they almost always reveal a fixable pattern.

Tracking is not a one-time setup. Model versions change, prices change, and usage patterns shift as features ship. A tracking system that is easy to update beats an elaborate one that nobody maintains. For ongoing notes on tooling and cost reporting, the news section at 9481.org and the blog at 9481.org are worth a periodic read. (Blog)

Conclusion

LLM token usage tracking comes down to a few disciplined choices: read usage from the API response rather than guessing, handle streaming carefully, attribute every token to a tenant and feature, store cost at write time, and alert on change rather than absolutes. None of this is exotic engineering. It is the same observability discipline teams already apply to latency and errors, applied to a new and unusually elastic cost driver.

The teams that get this right rarely have cleverer models than everyone else. They just know, at any moment, what they are spending and why.

Frequently Asked Questions

What exactly is a token in an LLM?

A token is a chunk of text, often a few characters or part of a word, that the model processes as one unit. Providers bill and set context limits in tokens rather than words or characters. Because each model family uses its own tokenizer, the same text can produce different token counts across models, which is why per-model counting matters. (Large language model)

How do I get accurate token counts for each request?

Use the usage data the API returns with each response instead of counting locally. Most providers include input and output token fields per call. Local tokenizer libraries are useful for estimating before you send a request, but they can drift from server counts when model versions change, so treat them as a pre-flight check rather than the source of truth.

Why does streaming break token tracking?

With streamed responses, usage figures often arrive only at the end of the stream, sometimes in a final chunk. Code that stops reading early may record no usage for a request that cost money. The fix is to always consume the stream to completion, log a clearly marked estimate when usage is missing, and version your logging schema because providers have changed streaming behavior across API versions.

Why is token count not the same as cost?

Cost depends on per-model pricing, and pricing has grown complex. Cached input tokens are often discounted, output tokens usually cost more than input, and batch jobs may be cheaper. A simple tokens-times-price calculation overstates spend for workloads with heavy prompt reuse, so store the computed cost at write time alongside raw counts.

Is there a standard format for token usage telemetry?

Not a finalized one. The OpenTelemetry project publishes semantic conventions for generative AI spans that include input and output token attributes, but these were still experimental at the time of writing. The practical approach is a thin internal schema you control, with adapters translating each provider’s usage fields into it.

How do I stop one customer or feature from blowing the budget?

Attribute every call to a tenant and feature, set alerts on the rate of change rather than only absolute totals, and enforce hard caps per tenant. Also log retries and agent loops, since a single user action that triggers several model calls multiplies usage invisibly. Reviewing the most expensive requests weekly usually reveals a fixable pattern quickly.

Latest articles

Scroll to Top