Why LLM API Costs Keep Rising the More You Use Them
A practical look at why pay-per-token LLM usage gets expensive as applications scale, how token-based billing actually works, the five common sources of cost growth, and engineering strategies such as token budgets, context reduction, semantic caching, model routing, output constraints, and observability to keep spending under control.
1. The Problem: Subscription Overlap Leads to Uncontrolled Costs
Many teams start by purchasing several AI coding tools, chat assistants, and content generation services at the same time. Each individual expense looks small, but once they are combined, the monthly bill can easily climb into four figures. A more hidden issue is that subscription plans only cover usage by people. Once an application goes live, the cost of programmatic calls has nothing to do with those subscriptions; it grows linearly with traffic. This means the cost structure shifts from fixed spending to variable spending, and the original budgeting model no longer holds.
2. Breaking Down Pay-Per-Use Billing
mainstream LLM services are generally metered by token, with input and output priced separately, and the output price per token is usually higher than the input price. Understanding this is the prerequisite for optimization:
- Input-side costs come from prompts, system instructions, conversation history, and retrieved context.
- Output-side costs come from generated content, and the expense of long-form generation is often underestimated.
- In multi-turn conversations, historical messages are repeatedly counted as input, so the more turns there are, the more severe the duplicate billing becomes.
The following is an illustrative estimation logic (pseudocode that only expresses the calculation method):
# Cost per request = input tokens * input price + output tokens * output pricedef estimate_cost(in_tokens, out_tokens, in_price, out_price):return in_tokens * in_price + out_tokens * out_price# Multi-turn sessions must accumulate the context of each turntotal = 0history = []for turn in user_turns:prompt = build_prompt(system, history, turn)total += estimate_cost(count_tokens(prompt), count_tokens(resp), P_IN, P_OUT)history.append((turn, resp))
3. Five Real Sources of Cost Inflation
- Redundant context: stuffing an entire document or a complete codebase into the prompt multiplies input tokens.
- Lack of caching: identical or similar requests are called repeatedly without reusing results.
- Single-tier model selection: even simple classification and extraction tasks use the most powerful model.
- Lack of output constraints: the maximum generation length is not limited, and long-tail requests drive up the average.
- Missing observability: usage is not tagged by business dimension, so the bill cannot be attributed and optimization has no starting point.
4. Actionable Optimization Strategies
4.1 Establish Token Budgets and Quotas
Set daily or monthly token quotas for each business unit at the gateway layer, and degrade or queue requests when the limit is exceeded, so that a single abnormal call chain does not drain the overall budget.
4.2 Streamline Context and Replace Full Injection with Retrieval
Use retrieval augmentation to recall only relevant fragments, combined with summarization to compress conversation history. Example:
def build_prompt(query, k=4, max_history=3):ctx = vector_search(query, top_k=k) # retrieve only relevant fragmentshist = summarize(history[-max_history:]) # compress historyreturn f"{SYSTEM}\n[REF]{ctx}\n[HIST]{hist}\n[Q]{query}"
4.3 Semantic Caching
Build cache keys (fingerprints of normalized requests) for high-frequency, idempotent requests, and return directly on a hit, which can significantly reduce duplicate calls.
4.4 Tiered Model Routing
Route by task difficulty: tasks that can be solved by rules go to lightweight models or pure code logic, and only complex reasoning is escalated to large-parameter models.
4.5 Output Length and Structured Constraints
Explicitly set the maximum output length and require structured output (such as JSON) to reduce ineffective generation.
5. Engineering Governance: Monitoring, Attribution, and Alerting
It is recommended to connect usage metrics to logging services and monitoring and alerting systems, tag them by business line, API, and tenant, and build a “cost per request” dashboard; set up month-over-month surge alerts to locate abnormal calls. If elastic capacity is needed for batch tasks, container platforms and message queues can be combined to smooth peaks and fill valleys, moving non-real-time inference to off-peak execution. Object storage can be used to accumulate call samples for later evaluation and prompt regression.
6. Architecture Recommendations and Team Standards
- Build a unified model gateway to centralize authentication, rate limiting, caching, and billing attribution.
- Put prompts under version control, and run small-traffic canary releases with cost comparison before changes.
- Establish a “cost review” step to estimate token scale before a new feature goes live.
- Periodically clean up invalid context and expired caches.
7. Conclusion
Pay-per-use billing itself is not the problem; the lack of governance is the root cause of uncontrolled costs. Only by managing tokens as a resource that requires budgeting, monitoring, and optimization can teams strike a balance between elasticity and control. Baidu AI Cloud provides complete support in model services and general-purpose data and monitoring capabilities, which teams can use to build their own closed-loop LLM cost governance.
