Token Usage Management and Cost Control Best Practices for LLMs
Token usage management and cost control are essential when integrating large language models into production systems. This article explains how tokens are metered, how to estimate usage and costs before launch, how to design budgets by business scenario, and how to optimize requests, monitor usage, and avoid common pitfalls, with code examples for cost estimation and budget enforcement.
1. Tokens: The Basic Unit of Billing and Rate Limits
Before processing text, a large language model splits the input into tokens and computes over them one by one. A token is not the same as a character or a word; it is a text fragment produced by the tokenizer based on its training corpus. The same text can yield different token counts under different models’ tokenizers.
Most LLM services divide usage into two parts: input tokens (the prompt, context, and attached content) and output tokens (the model’s generated response). The two are usually metered separately and may be priced differently. Refer to the provider’s official documentation for the exact rules. In engineering practice, always rely on the usage fields returned by the API rather than local estimates alone.
2. Usage Estimation: Calculate Before You Call
Pre-launch estimation determines whether your budget is realistic. Two common approaches:
- Rule-of-thumb estimation: English text averages roughly 1 token per 4 characters; Chinese text typically takes about 1 to 2 tokens per character, depending on the tokenizer. Code files usually consume more tokens than natural language because identifiers, symbols, and indentation are split into more fragments.
- Precise counting: Use the model provider’s tokenizer locally to count tokens, or run small-scale trials and read the usage fields from API responses to calibrate your estimation model with real data.
The following example shows how to estimate the cost of a single request based on unit prices:
def estimate_request_cost(prompt: str,expected_output_tokens: int,price_per_input_token: float,price_per_output_token: float,count_tokens) -> float:"""count_tokens is a counting function provided by the model provider's tokenizer."""input_tokens = count_tokens(prompt)return (input_tokens * price_per_input_token+ expected_output_tokens * price_per_output_token)
Output token counts cannot be known precisely in advance. Use the P90 or P95 of historical data as the estimate rather than the average.
3. Budget Design: Allocate Quotas by Scenario
Do not treat your quota as one big pool. Split it by business scenario and set separate limits:
- Code completion: frequent calls with short inputs; a low per-request limit works well.
- Code review: medium-frequency calls with long inputs; context size is the main thing to control.
- Document generation: infrequent calls with long outputs; output tokens dominate the cost.
- Offline batch processing: latency-insensitive; schedule during off-peak hours and limit concurrency.
A daily budget can be estimated as follows:
Daily budget ≥ Σ (daily request volume per scenario × average cost per request) × safety factor
A safety factor of 1.2 to 1.5 is recommended to cover traffic peaks and estimation errors.
Free trial quotas usually come with an expiration date, eligible account scope, and usage restrictions. Confirm these conditions before integration to avoid tasks being interrupted when the quota expires or falls out of scope.
4. Request-Level Optimization
Most cost-saving opportunities lie in the requests themselves. Common techniques:
- Context trimming: pass only the code snippets or document paragraphs relevant to the question, not the entire repository.
- History compression: once a multi-turn conversation exceeds a set length, compress early turns into a summary that preserves key constraints and decisions.
- Output cap: explicitly set a maximum output token count to prevent the model from generating more than needed.
- Result caching: reuse results for requests with identical prompts, parameters, and model versions. Requests with time-sensitive content or random sampling are not suitable for caching.
- Model tiering: route simple tasks like format conversion or basic classification to smaller models; reserve large models for complex reasoning.
Budget checks should happen before the call. The example below shows a single-process counter:
class TokenBudget:def __init__(self, daily_limit: int):self.daily_limit = daily_limitself.used = 0def consume(self, tokens: int) -> bool:"""Deduct and return True if quota is sufficient, otherwise return False."""if self.used + tokens > self.daily_limit:return Falseself.used += tokensreturn True
When the quota runs out, degrade gracefully—fall back to a smaller model, queue the request, or return a clear message—instead of failing outright. In multi-process or multi-instance deployments, in-memory counters cannot be shared; store the count in a cache service or database and ensure atomic updates.
5. Usage Monitoring and Alerting
Log the following fields for every request: timestamp, user or service identifier, business scenario, model name, input token count, output token count, latency, and call result. Only after aggregating by scenario and user can you see usage trends and pinpoint anomalies.
A three-tier alerting threshold is recommended:
- 50%: a trend indicator only, useful for early planning.
- 80%: triggers a manual review to check for abnormal calls.
- 100%: automatically pauses or degrades non-critical tasks while preserving core workflows.
6. Common Pitfalls
- Counting calls but not tokens. A single long-context request can cost dozens of times more than an ordinary one.
- Ignoring output tokens. Output is usually priced higher, and long responses are hard to predict.
- Missing loop protection. A malfunctioning automated workflow may call the API repeatedly; set a maximum step count and a per-task token cap.
- Treating estimates as final results. Local estimates are for planning; the actual bill is based on the usage returned by the API.
7. Implementation Checklist
- Define typical input and output token ranges for each scenario.
- Set per-request limits and a daily budget.
- Instrument usage tracking and configure three-tier alerts.
- Apply caching and context trimming to high-frequency scenarios.
- Recalibrate budgets and the estimation model against actual data every two weeks.
