LLM Inference Cost Optimization: A Practical Guide to Tiered Pricing and Prompt Caching
This guide explains why inference cost often becomes the first bottleneck when generative AI applications move from demo to production. It breaks down the three billable layers of LLM inference (input encoding, output decoding, and cache hits), shows how prefix-based caching can cut repeated-context cost by an order of magnitude, and lays out a layered prompt structure that keeps prefixes stable. You will also find a tabular method for capacity planning and cost estimation, three guardrails for balancing cost against availability, and four common mistakes that quietly inflate token spend.
1. Why Inference Cost Becomes the Make-or-Break Variable
When generative applications move from demo to production, the cost structure often becomes a bottleneck earlier than model quality does. Unlike traditional request-response services, every LLM inference call consumes two kinds of billable resources: encoding computation for the prompt and context (the input side), and autoregressive decoding computation for the generated result (the output side). Because decoding produces tokens serially, one by one, the compute cost per output token is typically much higher than on the input side. That is why the industry generally uses tiered pricing where the input rate is lower than the output rate.
The pricing structure given in the source material is 3 CNY per million input tokens, 6 CNY per million output tokens, and 0.3 CNY per million cached tokens. The engineering implication behind these numbers is worth unpacking: the cache rate is roughly one tenth of the input rate, which means that when repeated context is correctly reused, that portion of the cost is compressed by an order of magnitude. Understanding this matters more than memorizing the numbers, because it determines where architectural effort should go: toward context reuse rather than simply switching to a cheaper model.
2. Breaking Down the Billing Model into Three Layers
2.1 Input Side: The Encoding Cost of Prompts and Context
Input cost scales linearly with the total volume of text you assemble into a request, including system instructions, few-shot examples, document chunks retrieved through retrieval augmentation, and multi-turn conversation history. Many teams focus only on how short the user’s question is, while overlooking the fact that the system prompt and accumulated history are the main consumers of tokens.
2.2 Output Side: The Serial Cost of Decoding
Output cost corresponds to the number of tokens the model actually generates. Control measures include capping the maximum generation length, using structured output (for example, restricting fields and enumerations), and avoiding prompts that make the model restate the input. One caveat: output that is truncated or that hits the length limit is still billed, so “set a very large limit just in case of truncation” is not free insurance.
2.3 Cache Side: The Order-of-Magnitude Drop from Prefix Reuse
Cache billing applies when the request prefix is exactly identical. The condition is that the prefix matches token for token; the moment you insert a timestamp, a random ID, or any changing content at the beginning, everything after it degrades to ordinary input billing. This is the most common cause of cache failure in practice.
3. Designing for a Controllable Cache Hit Rate
Putting stable content first and volatile content last is the core principle for improving the hit rate. The recommended layered structure is:
[Fixed layer] System role definition, safety policy, output format constraints[Semi-fixed layer] Domain knowledge, glossary, few-shot examples[Session layer] Multi-turn history[Volatile layer] Current user input, timestamps, request trace ID
A sketch of the corresponding request construction logic:
def build_prompt(system: str, knowledge: str, history: list, query: str, trace_id: str):# Keep the fixed and semi-fixed layers at the front to keep the prefix stableprefix = f"{system}\n{knowledge}"session = "\n".join(history)# Always place volatile content last to avoid breaking prefix consistencyreturn f"{prefix}\n{session}\nUser question: {query}\nTrace ID: {trace_id}"
Three engineering constraints go with this. First, put prompt templates under version control and treat any template change as a full cache invalidation event whose cost impact must be assessed. Second, in retrieval-augmented scenarios, apply stable sorting and length truncation to retrieved chunks to avoid ordering jitter. Third, explicitly instrument the cache hit rate in your monitoring metrics and treat it as a core dashboard item on the same level as latency and error rate.
4. Capacity Planning and Cost Estimation
For estimation, the recommended approach is a table that combines structured output with tiered unit prices: split each type of call into input, output, and cache columns, calculate them separately, then multiply by the daily call volume. Example (unit prices follow the figures above and serve only to demonstrate the method):
| Scenario | Input (10k tokens) | Output (10k tokens) | Cache hit (10k tokens) | Cost per call |
|---|---|---|---|---|
| Single-turn Q&A | 0.2 | 0.05 | 0 | ~0.09 CNY |
| Long-document summarization | 3.0 | 0.3 | 0 | ~1.08 CNY |
| Multi-turn customer support (good hit rate) | 1.0 | 0.1 | 0.8 | ~0.36 CNY |
The table shows that long-context scenarios act as cost amplifiers, while multi-turn scenarios can significantly dilute unit cost when caching takes effect. Capacity planning also needs headroom for peak traffic, along with consideration of how rate limiting and queuing affect user experience.
5. Stability and Cost Guardrails
Cost control must not come at the expense of availability. Three types of guardrails are recommended:
- Budget guardrails: set daily or monthly token quotas per business line; when approaching the threshold, first downgrade the model tier, then throttle non-core traffic.
- Quality guardrails: keep a fallback path for critical flows, switching to a smaller model tier when a cache miss causes a sudden spike in cost or latency.
- Observability guardrails: combine logging with monitoring and alerting to track trends in token consumption, cache hit rate, and cost per request, so anomalies can be detected within hours.
When deploying on the cloud, you can run the inference gateway on a container platform, use a message queue to smooth out traffic peaks, archive long text in object storage to reuse summarization results, and manage credentials with a key management service. These are general capability categories; for specific specifications and pricing, refer to the official Baidu AI Cloud documentation.
6. Common Pitfalls
- Assuming that switching to a cheaper model solves the cost problem: if the context is redundant, the lower unit price is offset by token inflation.
- Concatenating dynamic content at the beginning of the prompt: this directly invalidates the entire cache.
- Counting only the number of calls and not tokens: this makes it impossible to locate the real source of cost.
- Opening up the maximum generation length all at once: paying a long-term cost for extreme cases.
7. Summary
The essence of inference cost optimization is converting “uncontrollable call volume” into a “context structure you can design.” First capture the caching benefit through layered prompts and stable prefixes, then quantify with tiered unit prices, and finally close the loop with quotas, downgrades, and monitoring. Only then can you achieve a sustainable balance between quality and cost.
