Making LLM Service Costs Visible Through Token-Based Metering
Token metering turns large language model usage from an opaque resource into a measurable, explainable, and manageable cost. This article explains how input, output, and cached tokens are priced; how to build an end-to-end metering and billing pipeline; and how quota governance, peak/off-peak pricing, scheduling, and cost observability can improve both user experience and infrastructure efficiency.
1. Making Costs Visible: From a “Free Black Box” to a Readable Bill
For some time, large language model services have combined a “free trial” experience with opaque resource consumption. Users see the response, but not how much compute was required to produce it. They may care whether an answer is useful, yet have little visibility into the resource difference between a long-context conversation and a short question.
Recently, some mobile applications have started displaying usage and cost information directly in the conversation interface. A short greeting may consume several dozen input tokens and several dozen output tokens, with the calculated cost far below one cent, while the interface still labels the interaction as “free.” At the same time, free-user quotas are becoming more restrictive. Examples include shorter per-request text limits, inactive conversations that can no longer be resumed, and recovery delays after continuous usage reaches a certain threshold.
These changes may appear unrelated, but they point in the same direction: converting compute consumption that was previously hidden in the backend into numbers that ordinary users can see, understand, and manage.
Metering does not necessarily mean that users will be charged immediately. Its more important value is that it builds cost awareness. When users can see that longer context and larger outputs lead to higher costs, they are more likely to optimize prompts, reuse cached content, and control the number of conversation turns. When a platform can accurately measure token usage for each tenant and application, it can implement fair quotas, plan capacity, and detect anomalies.
In this way, AI services move from opaque resources to governable resources.
2. Tokens: The “Energy Unit” of LLM Services
A token is a basic unit that a model uses to process text and is currently the most common unit for measuring large language model usage. Similar to electricity being billed in kilowatt-hours, token metering breaks a request into measurable input and output components.
Input tokens may include:
- System prompts
- Conversation history
- Retrieved documents
- The user’s question
Output tokens are the content generated by the model. Most services price input and output separately, while offering discounts for input tokens served from cache.
A general cost estimate can be expressed as:
cost = (input_tokens - cached_tokens) × P_in_miss+ cached_tokens × P_in_hit+ output_tokens × P_out
Here, P_in_miss, P_in_hit, and P_out represent the current prices for uncached input tokens, cached input tokens, and output tokens for the selected model and time period.
If a platform uses peak and off-peak pricing, the same model may have different prices during busy and idle periods. A representative implementation is:
def estimate_cost(input_tokens, cached_tokens, output_tokens, price):uncached = input_tokens - cached_tokensreturn (uncached * price["input_miss"]+ cached_tokens * price["input_hit"]+ output_tokens * price["output"])
This formula explains several important patterns:
- Long contexts can significantly increase input-token usage, especially in multi-turn conversations where historical messages are repeatedly included.
- Output tokens are often more expensive because generation requires token-by-token decoding.
- Cache hits can reduce the cost of repeated system prompts, fixed knowledge sections, and long documents.
- Peak and off-peak pricing can change the cost of the same request.
Different models use different tokenizers, so the same text may produce different token counts across models. The server-side measurement should therefore be treated as the final authority. Any client-side cost display should clearly indicate that it is an estimate.
3. Metering Architecture: From Requests to Bills
Making costs visible requires an end-to-end metering pipeline. A typical architecture includes the following layers:
- Request ingress and authentication: Identify the tenant, application, user, and request ID, then perform a quota pre-check. The pre-check can use a “reserve and settle” model: reserve quota based on the estimated token count first, then refund or charge the difference after the request completes and the actual usage is known.
- Token counting: Use the same tokenizer as the model on the server to count input and output tokens. For streaming responses, accumulate usage incrementally rather than counting only the first or final chunk.
- Cache-hit detection: Record hits from prefix caches, conversation caches, or other caching layers, and distinguish cached from uncached input tokens. Cache-hit detection must remain consistent with the inference layer; otherwise, both billing and optimization results will be inaccurate.
- Billing rules engine: Calculate costs based on the model, time period, cache status, and price version. Rules should be versioned so historical bills remain traceable. Billing events should be idempotent so that retries do not result in duplicate charges.
- Usage event stream: Write the metering event for each request to a message queue for buffering, then persist it in a logging service or data warehouse. An aggregation service can summarize usage by minute, hour, and day.
- Queries and alerts: Provide APIs for balance, usage, and cost queries, along with budget-threshold alerts, abnormal-usage detection, and quota approval workflows.
- Reconciliation and auditing: Retain raw metering events, rule versions, and aggregation results so that a bill can be traced back to an individual request.
Platforms such as Baidu AI Cloud can use general-purpose components—including logging services, message queues, monitoring and alerting systems, and container platforms—to build this type of pipeline.
In practice, the formula is rarely the most difficult part. Consistency is. The system must ensure that each request is counted exactly once, retries can be deduplicated, event time and billing time use consistent definitions, and estimated costs can be explained against the final bill. Cost transparency has value only when metering is accurate.
4. Quota Governance: Balancing Fair Use and User Experience
Restricting free quotas is a common resource-governance strategy. Typical controls include:
- Setting a maximum number of input tokens per request to prevent oversized documents from consuming excessive capacity
- Expiring inactive conversations after a defined period
- Rate-limiting continuous calls to prevent scripted abuse
- Introducing queues when capacity is under pressure
Technically, a quota service maintains the available allowance for each user or tenant. A rate limiter may use a token bucket or sliding-window algorithm, while dynamic thresholds can be adjusted according to cluster load.
Quota governance must balance fairness and usability. Platforms should display remaining quota, current consumption, and the expected recovery time in advance. When rate limiting occurs, the response should include a clear error code and recommended actions. Degradation strategies can also help, such as shortening the context, switching to a lightweight model, or placing non-real-time tasks in a queue.
A simplified admission check looks like this:
def admit(request, quota):need = estimate_tokens(request)if not quota.try_consume(need):return "queue_or_reject"return "admit"
Estimated token usage may differ from actual usage, so reservation and settlement should include an appropriate buffer. The goal of quota governance is not simply to block users. It is to serve more requests with limited resources while making cost boundaries understandable.
5. Peak and Off-Peak Pricing: Using Price Signals to Shift Workloads
Some platforms apply different prices during weekday peak periods and during idle periods such as nights or weekends, with lower prices during off-peak times.
Implementation typically requires:
- Configurable pricing rules
- A clock service with a consistent time zone
- Rules for assigning requests to time periods
- Price-version management
The rules engine must clearly define whether a request belongs to the time period determined by its start time or completion time. This avoids disputes when a request crosses from one period into another.
For developers, peak and off-peak pricing provides a clear cost-optimization signal. Non-real-time workloads such as offline evaluation, batch document summarization, and data cleaning can be scheduled during idle periods. Online interactions can remain available during peak periods while reducing price sensitivity through cache reuse, context compression, and output-length limits.
For platforms, price signals can help shift demand away from busy periods and improve resource utilization. Combined with elastic scaling and queue-based load smoothing, peak and off-peak pricing becomes not only a billing strategy but also a capacity-management tool.
6. Best Practices for Cost Observability
Cost observability should be treated as a first-class capability in LLM applications. Each request should produce structured logs containing fields such as the model identifier, input tokens, cached tokens, output tokens, time period, estimated cost, tenant ID, and request ID.
For example:
{"request_id": "req-xxx","tenant_id": "tenant-a","input_tokens": 0,"cached_tokens": 0,"output_tokens": 0,"period": "peak","cost_estimate": 0.0}
With this data, teams can build dashboards to track:
- Cache-hit rate
- The proportion of requests using long contexts
- The proportion of output tokens
- Average cost per request
- The rate of budget consumption
Common optimization techniques include keeping system prompts stable to improve prefix-cache hits, using retrieval-augmented generation to avoid injecting entire documents into every request, summarizing historical conversations into memory, setting a maximum output-token limit, and allowing users to stop streaming generation early.
Enterprises should also establish a multi-tenant tagging system that allocates costs to applications, teams, and projects. Combined with budget alerts and auditing, this helps prevent uncontrolled usage from going unnoticed.
7. Conclusion: Transparent Metering Signals Mature AI Infrastructure
The transition from a free black box to a token-based bill resembles the resource-visibility transition that occurred during the early development of cloud computing.
Transparent metering is not merely a step toward charging users. It is the foundation for resource governance, fair usage, capacity planning, and cost optimization. When every request can be accurately counted, attributed, and explained, developers can manage AI spending as a first-class concern. Platforms can also find a sustainable balance between user experience and operational efficiency.
More granular metering, smarter routing, and more capable cost-optimization tools will likely become standard components of AI infrastructure. Making costs visible is only the first step.
