Cost Governance for LLM APIs: Managing Token Costs Under Usage-Based Billing
As major LLM providers shift from daily free quotas to usage-based pricing, where a small free allowance is followed by per-token charges, cost control becomes an engineering problem rather than a pricing issue. This article presents a generic token billing model and a practical governance framework: the four main sources of cost drift (prompt bloat, unbounded context growth, uncontrolled output length, and retries), five engineering countermeasures (budgets and quotas, layered prompt trimming, context compression, semantic caching, and model tier routing), the observability metrics required to make spending visible, architecture-level savings, and a migration and validation workflow. It is vendor-neutral and focuses on treating tokens as a budgeted, monitored, and optimized resource.
1. Technical Background of the Billing Change
Several major LLM services have recently revised their pricing strategies. The previous model, centered on a daily free quota, is gradually moving toward pay-as-you-go billing: a small free allowance, with usage beyond it metered per token. For developers, this is not merely a price change but a systemic challenge spanning how you call the API, how you design the architecture, and how you govern cost.
Note that the specific allowances, unit prices, and billing cycles differ across providers. This article does not cover the rules of any particular vendor. Instead, it abstracts a generic billing model and the methods for dealing with it.
1.1 The Basic Token Billing Model
mainstream LLM services use the token as the unit of measurement. A token is the smallest unit of text the model processes after segmentation. One Chinese character typically maps to one or two tokens, while an English word may be split into several subword tokens. Billing usually distinguishes two types of consumption:
- Input tokens (prompt): the allowance consumed by the user request and system prompts;
- Output tokens (completion): the allowance consumed by the generated content.
Most services price output tokens higher than input tokens, so long-form generation scenarios have greater cost elasticity.
1.2 The Basic Cost Formula
A single call can be described with a simplified formula:
cost per call = input tokens × input unit price + output tokens × output unit pricemonthly cost ≈ Σ(cost per call) + platform add-ons (e.g., retrieval, storage, logging)
This formula reveals three levers for cost governance: compress the input, constrain the output, and reduce ineffective calls.
2. Four Sources of Cost Volatility
2.1 Prompt Bloat
If system prompts, few-shot examples, and tool definitions are all concatenated into every request, they become a fixed cost. A 2,000-token system prompt, at 10,000 calls per day, adds up to 20 million input tokens per month.
2.2 Unbounded Context Accumulation
In multi-turn conversations, sending back the full history each time makes the token count grow linearly, or even quadratically, with the number of turns. The input of the 10th request may already be more than five times that of the 1st.
2.3 Uncontrolled Output Length
Without a max_tokens constraint or structured output limits, the model may generate redundant explanations, directly inflating the more expensive output side of the bill.
2.4 Retries and Failed Calls
Timeout retries, rate-limit backoffs, and regeneration after validation failures all produce waste: money spent without a usable result. Without idempotency and caching, this waste is often severely underestimated.
3. Five Engineering Practices for Cost Governance
3.1 Establish Budgets and Quotas
At the application layer, set a token budget for each business line and each tenant, using a token bucket to enforce both rate and quota limits:
class TokenBudget:def __init__(self, monthly_limit):self.limit = monthly_limitself.used = 0def acquire(self, est_tokens):if self.used + est_tokens > self.limit:raise BudgetExceeded("Monthly token budget exhausted")self.used += est_tokensreturn True
The estimated token count should be computed before the request is sent, avoiding “spend first, find out later.”
3.2 Layer and Trim Prompts
Split prompts into a static layer and a dynamic layer. Version the static layer and keep it as lean as possible; inject only the fragments relevant to the current request into the dynamic layer. In retrieval-augmented scenarios, retrieve first and rerank second, keeping only the Top-K fragments rather than stuffing an entire document into the context.
3.3 Context Compression Strategies
- Sliding window: keep only the most recent N turns;
- Summary compression: generate a structured summary of earlier conversation to replace the original text;
- Externalized state: store structured state in a cache or database and fetch it on demand instead of sending everything back each time.
3.4 Cache Reuse
Build a semantic cache for high-frequency repeated requests. A cache hit returns immediately without a model call. The cache key can be a hash of the normalized prompt, with a TTL and invalidation policy.
cache_key = hash(normalize(prompt) + model_id + temperature)
3.5 Model Tier Routing
Route by task difficulty: simple classification, extraction, and rewriting go to smaller models; complex reasoning and long-form generation go to larger models. The routing layer makes dynamic decisions based on task labels, confidence, and historical accuracy. This typically reduces cost significantly without sacrificing overall quality.
4. Building Observability
Cost governance starts with visibility. Collect the following metrics and connect them to a monitoring and alerting system:
- Call volume and input/output token distribution (P50/P95/P99);
- Cost per request, cost per business line, and cache hit rate;
- Failure rate, retry rate, and number of rate-limit triggers;
- Cost per unit of business output (e.g., cost per thousand Q&A turns).
Logging services and object storage can retain raw call records over long periods for traceability and bill reconciliation. Alerts should use dual thresholds, day-over-day change and budget progress, to avoid a sudden spike at month end.
5. Architecture-Level Cost Reduction
- Asynchronous processing and batching: merge requests for non-real-time tasks to improve throughput utilization;
- Streaming output: return content as it is generated to reduce the probability of timeout retries;
- Small-model pre-validation: filter obviously unqualified requests first using a low-cost method;
- Result reuse: persist generated and stable content to avoid repeated generation;
- Capacity and elasticity: use container platforms’ elastic scaling to handle peaks, reducing resources permanently reserved for peak load.
6. Migration and Validation Workflow
- Inventory: measure the token distribution of existing calls and rank them by business value;
- Baseline: establish baselines for cost, latency, and accuracy in a test environment;
- Canary: ramp up gradually from 5% to 20% to 50% while watching the cost curve;
- Regression: use a fixed evaluation set to verify that quality has not degraded;
- Lock in: write budgets, caching, and routing policies into a configuration center and include them in the release process.
7. Conclusion
The shift from free to usage-based billing essentially makes compute cost explicit. If a team manages tokens as a resource that needs budgeting, monitoring, and optimization, it can maintain predictability through pricing changes. Baidu AI Cloud provides complete support across model services and general-purpose capabilities such as data, storage, and monitoring. On this foundation, enterprises can build their own cost governance system and unify technology selection and cost management within a single engineering standard.
