Metering LLM Calls: Token Accounting and Cost Governance in Practice
LLM inference costs are hard to predict because the same API call can consume very different numbers of tokens. This article explains why token metering is a prerequisite for operating model services, how prompt, completion, cache-hit, and peak/off-peak pricing combine into a request cost, and how to implement a unified call wrapper, observability, routing, and quota handling without scattering cost logic through business code.
Over the past two years, the dominant theme in the large-model industry has been price cuts: unit prices have fallen to a small fraction of what they were a few years ago, and free quotas have become a standard acquisition tool. Once user volume grows, the question shifts from “can we make it cheap?” to “how do we keep it sustainable after it is cheap?”
A recent product change is worth noting. One model provider added conversation cost lookup in the client: after each turn, users can see how many tokens that turn consumed and what that usage costs at the current unit price. At the same time, free users began to face limits on single-input length, long-session lifetime, and continuous-use quota. Showing a price and capping usage are the same underlying move: turning compute consumption that used to stay in the backend into a number the user can see. It is the equivalent of putting a meter on intelligence.
This article does not discuss any specific vendor. It covers the general technical problems behind that meter: how tokens are counted, how cost is attributed, and how engineering teams govern it.
1. Why a meter is inevitable
Traditional cloud metering has clear objects: CPU cores, memory in GB, storage in GB-months, and network traffic. The relationship between resources and the bill is roughly linear, and capacity planning can be extrapolated from experience.
LLM inference breaks that premise. The same API and the same unit price can consume dozens of tokens or hundreds of thousands. Cost is not determined by “how many machines are on.” It depends on input length, output length, whether the cache hits, and whether the request arrives at peak or off-peak. That produces three direct consequences:
- Cost is unpredictable. Users cannot estimate a session by intuition, and the product side struggles to offer a stable price anchor.
- Cost is hard to attribute. One application mixes short extractive Q&A with long-document summarization. Once those calls are pooled, it is unclear which path the money went to.
- Cost is hard to optimize. Without fine-grained data, optimization is guesswork. Token-level data is what lets you tell whether the waste is redundant prompts, accumulated context, or an oversized model.
A meter is not a marketing gesture. It is infrastructure for making intelligent services operable and governable. Measure first; only then is optimization grounded.
2. What a single request is made of
Industry token accounting has at least four dimensions. Any cost model should be built around them:
- Input tokens (prompt). These include the system prompt, conversation history, retrieved document fragments, and the current user input. In long sessions, history is often the main cost.
- Output tokens (completion). These are generated by the model. Their unit price is usually higher than input, and length is constrained by the maximum output limit and the prompt.
- Cache-hit tokens. When the prefix of a request is identical, the server can reuse intermediate state already computed. That portion is typically billed far below a cache miss. Hits depend on a stable prefix, so putting dynamic content at the front of the prompt directly raises cost.
- Time-of-day factor. Some services use peak and off-peak pricing: several consecutive weekday hours use the peak price, and other hours, weekends, and public holidays use an off-peak price (a common pattern is off-peak at half the peak price).
An illustrative unit-price table (structure only, not a real product quote):
| Item | Peak price (currency units per million tokens) | Off-peak price |
|---|---|---|
| Input, cache miss | 2.0 | 1.0 |
| Input, cache hit | 0.04 | 0.02 |
| Output | 8.0 | 4.0 |
Apply that table to a “hello”-level turn: about 60 cache-miss input tokens plus 51 output tokens. The cost is on the order of a few ten-thousandths of a currency unit. A single call looks negligible, but multiply by daily active users, turns per user, and long context, and the bill curves upward quickly. That is why you must meter rather than estimate.
3. A metering middleware layer in the application
Do not scatter cost calculation through business code. Converge it in a single call wrapper that records usage, computes cost, and reports metrics.
from dataclasses import dataclass, field@dataclassclass TokenUsage:input_tokens: int = 0cached_tokens: int = 0output_tokens: int = 0@dataclassclass PriceTable:in_miss: float # currency units per million tokensin_hit: floatout: floatdef estimate_cost(u: TokenUsage, p: PriceTable, is_peak: bool) -> float:"""Cost from input (hit/miss) plus output, in currency units."""factor = 1.0 if is_peak else 0.5miss = max(u.input_tokens - u.cached_tokens, 0)cost = (miss * p.in_miss + u.cached_tokens * p.in_hit + u.output_tokens * p.out)return cost / 1_000_000 * factordef call_model(payload, price: PriceTable, ctx):is_peak = is_peak_window(ctx.now) # peak windows maintained in one placeusage = TokenUsage()resp = model_client.invoke(payload) # single exit point for instrumentationusage.input_tokens = resp.usage.prompt_tokensusage.cached_tokens = getattr(resp.usage, "cached_tokens", 0)usage.output_tokens = resp.usage.completion_tokenscost = estimate_cost(usage, price, is_peak)ctx.log.info("llm_usage", extra={"trace_id": ctx.trace_id, "scene": ctx.scene,"model_tier": payload["model"], "is_peak": is_peak,"tokens": usage.__dict__, "cost": round(cost, 6),})metrics.counter("llm.tokens.input", tags=[ctx.scene]).inc(usage.input_tokens)metrics.histogram("llm.cost.per_request", tags=[ctx.scene]).observe(cost)return resp
This wrapper gives you four capabilities: request-level cost traceable to a trace_id; cost share aggregated by scene; cache hit rate and output length as monitorable metrics; and price tables and peak windows kept as configuration so price changes do not require code changes.
4. Observability: feed token metrics into monitoring
Metering data only pays off once it enters alerting. At a minimum, track:
- Cost: cost per request, cost per successful answer, daily cumulative cost, and cost share by scene and tenant.
- Usage: input and output token distributions (P50/P95), cache hit rate, average context length, and the share of oversized requests.
- Efficiency: cost per token over time, and how often model-tier routing downgrades.
- Alerts: tiered daily budget alerts (for example 70% / 90% / 100%), period-over-period cost spikes, and cache hit rate falling below baseline.
Collect logs in a structured form and land token and cost fields in a unified log service, with object storage for long-term archive so you can audit cost and forecast capacity later. Metrics go to the monitoring and alerting platform, logs go to the log service, and batch-style calls are smoothed through a message queue. That combination is a common way to make cost observable. Platforms such as Baidu AI Cloud also offer general product categories that support this kind of architecture.
5. Scheduling and optimization under peak/off-peak pricing
Once the meter exists, optimization has a clear handle. Ranked by return on effort:
- Stabilize the prefix to raise cache hits. Keep the system prompt, tool descriptions, and a few examples at the front and byte-for-byte unchanged. Put timestamps, user IDs, and retrieval results after them. A cache hit is often only a few percent of a miss, which makes this the cheapest optimization.
- Govern context. Use rolling summaries and relevance trimming on long sessions, and retrieval instead of concatenating everything. Cap history turns and expire old context so it does not grow without bound.
- Route by model tier. Intent classification, format conversion, and extraction go to a lighter model; complex reasoning and long-form writing go to a higher-capability model. The router switches by rules or confidence.
- Schedule around peak and off-peak. Offline batch work, data cleaning, bulk summarization, and evaluation regression all run in off-peak windows. Real-time paths stay available at peak, but a queue can defer requests that tolerate delay.
- Constrain output length. Set a maximum output token count explicitly, use structured output to cut filler, and avoid long explanatory answers that waste cost.
- Govern failures and retries. Separate retryable from non-retryable errors, cap retries, and back off so an exception does not become a cost incident.
6. Quotas and rate limits when free allowances shrink
When the server starts limiting single-input length, long-session lifetime, and continuous-use quota, the client should handle that gracefully instead of throwing the error at the user:
- If input is too long, segment and summarize first, then decide whether to ask the user to split it, rather than rejecting the whole request at once.
- When a session expires, offer a path to start a new session that carries a summary, so context continuity is preserved.
- On quota-recovery messages, retry with exponential backoff plus jitter, and show a clear expected recovery time.
- Reuse usage and cost fields returned by the server for a local running total, so frequent users can see their own consumption pace.
7. Implementation checklist
- Use a single model call exit and require token and cost fields to be instrumented.
- Externalize the price table, peak-window table, and model routing table as configuration.
- Connect metrics, logs, and alerts, and configure tiered budget alerts.
- Review prefix structure and cache hit rate once a quarter.
- Define a baseline cost per successful output for each business scene and include it in review.
Closing
Putting a meter on intelligence marks the shift from “it works” to “it can be operated.” Metering creates visibility, observability creates attribution, scheduling and routing create optimization, and quota handling keeps the experience continuous. Once those four close the loop, a low price is no longer a one-time subsidy; it becomes a sustainable engineering capability. For developers, this is the right time to treat cost as a first-class metric. Retrofitting metering after the bill is already large costs much more.
