LLM API Billing and Cost Optimization: Tokens, Model Routing, Prompt Caching, and Observability
This article explains how LLM API billing works around input, output, and cached input tokens, and how teams can reduce costs through tiered model selection, stable prompt prefixes for caching, context and output trimming, and token-level observability and attribution. It presents practical routing, prompt structure, and monitoring patterns while keeping response quality aligned with task value.
1. The Underlying Billing Logic: Everything Is Measured in Tokens
LLM API billing differs fundamentally from traditional billing based on the number of calls or bandwidth. Its core unit of measurement is the token. Whether you send a prompt or system instruction, or receive generated content from the model, the text is split into tokens and priced separately. Understanding this is the first step toward effective cost governance.
The industry commonly divides tokens into three categories, each with a different pricing weight:
- Input tokens: The full context sent to the model, including system prompts, conversation history, retrieved material, and the current question.
- Output tokens: The content generated and returned by the model. Because generation requires autoregressive computation for each token, output is usually priced significantly higher than input.
- Cached input tokens: When multiple requests reuse the same prefix, such as a fixed system prompt or a long document, the cached portion is often billed far below the price of regular input.
A key conclusion: output costs more than input, and cached input costs less than regular input. This means cost optimization should focus on reducing output redundancy, compressing input size, and improving cache hit rates.
2. Tiered Model Selection: Not Every Task Needs the Most Capable Model
The “dual-model plus differentiated pricing” approach reflected on the original page is essentially a common engineering practice: match capability tiers to cost tiers. Providers typically offer both high-capability flagship models and cost-effective lightweight models, and the price difference between them can be several times.
In engineering, this is implemented by building a routing layer that directs requests according to task complexity:
Request enters│├─ Simple tasks (classification, extraction, formatting, short Q&A) ──► Lightweight model (low cost)│└─ Complex tasks (long-document reasoning, code generation, multi-step planning) ──► Flagship model (high capability)
The benefit is clear: send 80% of simple, high-frequency requests to cheaper models, and route only the 20% of requests that genuinely require strong reasoning to flagship models. The overall bill often drops by an order of magnitude, while the user-perceived quality remains nearly unchanged.
3. Prompt Caching: Minimize the Cost of Repeated Prefixes
Cached input is cheaper because the server reuses KV states that have already been computed, avoiding repeated forward computation. To benefit from this, prompts need to be designed deliberately:
- Keep the prefix stable: Place fixed content at the front of the prompt, such as the system role definition, tool instructions, and long reference documents. Place content that changes each turn afterward. The more stable and longer the prefix, the higher the hit rate.
- Do not change the order: Caching usually matches prefixes exactly. Once variable content is inserted at the front, all subsequent cache entries become invalid.
- Reuse in batches: For multiple questions about the same document, keep the document portion exactly the same and replace only the question at the end.
An illustrative structure:
[Fixed system prompt] + [Fixed long document] + [Changing question]└────── Cacheable prefix ──────┘ └─ Different each time ─┘
4. Context and Output Trimming: Cut Tokens at the Source
- Compress retrieved snippets: When using retrieval augmentation, perform reranking and deduplication first, and keep only a small number of the most relevant snippets instead of inserting an entire document into the context.
- Limit output length: Set a reasonable maximum token limit for generation to prevent verbose model output from driving up the bill.
- Use structured summaries instead of full text: In multi-turn conversations, replace the complete history with a rolling summary to significantly reduce input size.
- Write clear instructions to reduce retries: Specify format and constraints clearly in one pass to reduce the consumption caused by “generate, reject, retry” loops.
5. Engineering and Observability: Make Costs Measurable and Attributable
Cost governance cannot rely on intuition; it must be observable. Recommended practices:
- Record the number of input, output, and cached tokens for each request at the application layer, along with the corresponding cost, to create detailed logs.
- Attribute costs by business line, user, and feature to identify high-consumption sources.
- Set budget alerts and rate-limiting thresholds to prevent abnormal calls, such as infinite loops or malicious traffic, from causing uncontrolled bills.
- Introduce local caching or result reuse for high-frequency calls so that cache hits no longer trigger model requests.
When deploying on cloud infrastructure, object storage can archive call details, message queues can smooth traffic peaks, container platforms can host routing services, and logging and monitoring services can provide unified observability. Generic cloud capabilities can support this architecture without binding to proprietary APIs.
6. Conclusion
The cost of LLM APIs is fundamentally the combined result of the pricing weights for input tokens, output tokens, and cached tokens. By mastering four levers, namely tiered model selection, prefix caching, context and output trimming, and observable cost attribution, teams can balance quality and cost. A truly mature solution does not simply pursue the most capable model; it ensures that each type of request runs at a cost tier that matches its value.
