LLM API Cost Reduction: Cache Hits and Tiered Pricing Explained
This article breaks down how modern LLM API pricing works and why lower unit prices do not always lead to lower bills. It explains a three-tier billing model covering regular input, cached input, and output tokens, then shows how to improve cache hit rates through byte-stable prefixes, deterministic serialization, and prompt versioning. It also covers model routing across pricing tiers, four levers for reducing output costs, the observability metrics needed to attribute spending, and a practical rollout order for turning price cuts into real savings.
1. The Real Problem Behind the Headline: Lower Unit Prices ≠ Lower Bills
A recent price adjustment from a major cloud provider is a good example. For its flagship tier, both input and output unit prices dropped by roughly 20%, while cached input dropped by 60%, landing at $8, $0.40, and $40 per million tokens respectively. The lightweight tier stayed at the previous generation’s levels: $2 for input, $0.10 for cached input, and $10 for output per million tokens.
Many teams see “price cut” and expect their bill to fall year over year. In practice, bills often stay flat or even rise. The reason is simple: a bill is unit price multiplied by usage, and usage is driven by business growth, context length, and retry strategy. What deserves attention is not the price numbers themselves, but the cost structure exposed by this three-tier pricing — there is a 20x unit price gap between cached input and regular input, which means the design space around how you call the API is usually more valuable than waiting for the next price cut.
2. Breaking Down the Three-Tier Billing Model
Splitting a request’s token consumption into three categories is the starting point for all optimization work:
| Billing category | Flagship tier (USD / million tokens) | Lightweight tier (USD / million tokens) | Description |
|---|---|---|---|
| Regular input | 8 | 2 | Prompt portion that misses the cache |
| Cached input | 0.4 | 0.1 | Portion that hits the prefix cache |
| Output | 40 | 10 | Content generated by the model |
Two conclusions directly drive architecture choices:
- Output is the most expensive resource. On the flagship tier, output costs five times more than regular input, so “making the model say less” usually pays off more than “making the model read less.”
- Cached input is the cheapest input. Once a cache hit occurs, the marginal cost of the same context drops to one twentieth of regular input. Fixed prefixes such as long system prompts, long documents, and long tool definitions are natural beneficiaries.
It is worth stressing that caching is not a free lunch: it typically works on a “valid for a period after write” basis, there is a minimum cacheable length threshold, hits are determined server-side, and providers differ on expiration policies and whether storage is billed separately. In engineering terms, treat it as a probabilistic discount, not a guaranteed number on paper.
3. Engineering for a High Hit Rate
Cache benefits depend entirely on the hit rate, and the hit rate depends on whether the prefix is byte-for-byte stable. Any of the following changes will invalidate the entire prefix:
- Concatenating timestamps, random request IDs, or user nicknames into the system prompt;
- Building context from unsorted dictionaries or hash sets, causing serialization order to drift;
- Inserting a mutable field before a long document, truncating the shared prefix;
- Mixing multiple prompt versions, so the cache space gets crowded out by low-frequency prefixes.
The recommended structure is to split the prompt into a “stable layer” and a “volatile layer”:
[stable prefix] system role definition + tool/function schema + domain knowledge docs + a few examples[volatile suffix] current user input + retrieved snippets + dynamic info such as timestamps
At the code level, the key is deterministic serialization:
import jsondef build_prompt(system_tpl: str, tools: list[dict], query: str) -> list[dict]:# Stable layer: fixed key order, no dynamic fields, guaranteeing a byte-identical prefixstable = json.dumps(tools, ensure_ascii=False, sort_keys=True,separators=(",", ":"))return [{"role": "system", "content": system_tpl + stable},{"role": "user", "content": query}, # volatile layer goes last]
The accompanying operational practices matter just as much: put prompts under version control and roll them out gradually, avoiding multiple competing prefixes within the same day; and set separate quotas for low-frequency long prefixes so high-traffic workloads cannot flush the cache slots.
4. Tiering by Task: Tier Selection and Routing
The lightweight and flagship tiers differ by 4x on output unit price, which gives routing design a clear economic motive. A workable approach is to classify tasks by determinism:
- Rule-decidable tasks (classification, extraction, format conversion, intent recognition) go to the lightweight tier, with output constrained to enums or short structures;
- Tasks needing multi-step reasoning or long tool-call chains go to the flagship tier, with caching carrying their long prefixes;
- When uncertain, start lightweight and escalate, using confidence or validation results as the escalation signal rather than defaulting to the flagship tier for everything.
def route(task: dict) -> str:if task["max_reasoning_steps"] > 3 or task["needs_long_context"]:return "flagship"return "lightweight"
5. Four Levers on the Output Side
Since output carries the highest unit price, compressing output length is the most direct way to save money:
- Constrain the structure: use a JSON Schema or enums to limit fields, and forbid explanatory padding;
- Cap the length: set a reasonable maximum generation length so abnormal inputs cannot trigger runaway generation;
- Stream responses: validate while generating and cut off low-quality answers early, saving not just cost but also latency;
- Semantic caching: build a result cache for frequent similar questions and skip inference entirely on a hit. This is the only lever that can bring a single call’s cost to zero, but it requires a similarity threshold and an expiration window to control the error rate.
6. Observability: No Measurement, No Optimization
Cost optimization has to rest on attributable data. At minimum, collect the following dimensions and tie them to business identifiers:
- Token usage across the three categories per request (regular input, cached input, output) plus a cache hit flag;
- Hit rate, average prefix length, and number of prefix changes;
- Cost per request and cost per successful task (excluding retries and failed requests);
- Call share by tier and escalation rate.
With these metrics in place, questions like “why didn’t the bill drop after a 20% price cut” become answerable — and the answer is usually usage growth, insufficient hit rate, or output bloat, not price.
7. Capacity and Reliability Considerations
Cost optimization for inference services reaches into infrastructure. The common pattern is to keep long documents and knowledge bases in object storage, use a message queue to smooth traffic peaks and troughs, run an elastically scalable inference gateway on a container platform, and close the loop with logging and monitoring with alerting. For the cache and result-reuse layer, plan capacity around hit rate and expiration latency as core metrics, and prepare fallback paths for server-side rate limiting, timeouts, and degradation, so availability is not sacrificed to save money.
Baidu AI Cloud’s general capability set for these scenarios (object storage, container platform, logging and monitoring services) can serve as a reference for implementation; refer to the official documentation for specific billing and quotas.
8. Suggested Rollout Order
- Instrument first and get the real distribution of the three token categories — no guess-based optimization;
- Refactor prompts into a stable prefix plus a volatile suffix, and watch the hit rate change;
- Compress output structure, set generation caps, and add streaming validation;
- Turn on task routing and gradually raise the lightweight tier’s share;
- Introduce semantic caching last, continuously monitoring error rate and cost per successful task.
Following this order is what turns the benefit of a price adjustment into an actual drop on the bill, rather than having it cancelled out by usage growth.
