How to Cut LLM API Costs: An Architecture Guide to Caching, Routing, and Observability
A practical engineering guide to lowering large language model API costs after a price cut. Learn how input, cached input, and output tokens shape your bill, how to build a cost estimation model in code, how to raise cache hit rates with stable prefixes, how to route requests across model tiers, and how to control output cost and latency with observability and capacity planning.
1. What the Price Changes Mean for Engineering
A cloud provider recently made a clear adjustment to its LLM service pricing: the flagship tier cut both input and output unit prices by roughly 20%, while cached input dropped by 60%. The next-flagship tier kept the previous generation’s pricing, with input, cached input, and output holding near $2, $0.1, and $10 per million tokens. For developers, this is not just a price-cut headline. It is a reshuffling of the call cost structure.
To understand the value, break the bill apart. The cost of a request usually has three parts: fresh input tokens, input tokens that hit the cache, and generated output tokens. Their unit prices often differ by one to two orders of magnitude. Cached input is the cheapest, and output is the most expensive. So the real benefit of a price cut is not proportional to the “discount percentage.” It depends on how your workload is distributed across these three parts.
A typical long-context scenario shows the point. Suppose a request has 4,000 fresh input tokens, 6,000 cached tokens, and 1,000 output tokens. At the adjusted prices, the flagship tier costs about 0.032 + 0.0024 + 0.04 = $0.0744 per request. If the cache misses and all 10,000 tokens are billed as fresh input, the cost rises to 0.08 + 0.04 = $0.12. Caching cuts the per-request cost by about 38%. But if the output doubles to 2,000 tokens, the cost becomes $0.1144, and the output share climbs from 54% to 70%. At that point, the focus should shift to output control rather than caching.
2. Build Your Own Cost Model
Do not estimate by feel. Turn the billing formula into code so you can make technology choices and plan capacity.
def estimate_cost(in_tokens, cached_tokens, out_tokens, price):fresh = in_tokens - cached_tokensreturn (fresh * price["in"]+ cached_tokens * price["cached"]+ out_tokens * price["out"]) / 1_000_000FLAGSHIP = {"in": 8.0, "cached": 0.4, "out": 40.0}STANDARD = {"in": 2.0, "cached": 0.1, "out": 10.0}
With this function, you can plug in real per-part token stats from production and attribute them by business line, by endpoint, and by tenant. That gives you a core metric: cost per thousand requests. In practice, the output unit price is about 5x the input price, so any cost governance that relies only on “shortening prompts” has a clear ceiling.
3. Cache Hit Rate: Where the Biggest Savings Live
A 60% cut in cached input pricing turns cache hits from a nice-to-have into an architectural must. The key to a higher hit rate is keeping the request prefix stable:
- Put the system prompt, tool definitions, domain knowledge, and few-shot examples at the front, and do not concatenate strings per request;
- Move volatile content such as timestamps, random IDs, and user nicknames to the back so it does not pollute the prefix;
- Keep the prefix within the model’s supported cache length; too long dilutes the benefit;
- Standardize template versions, and treat a template change as a cache invalidation event that needs a staged rollout.
An example of a stable prefix:
SYSTEM = load_versioned_prompt("support_v3") # versioned, content unchangeddef build_messages(user_input, ctx):return [{"role": "system", "content": SYSTEM},{"role": "user", "content": f"{ctx}\n{user_input}"}]
Keep in mind that cache hits are time-sensitive. Fixed prefixes reused at high frequency give the best returns, while long-tail requests should go to the standard tier.
4. Tiered Routing: Match Difficulty to the Right Tier
With two model tiers available, difficulty-based routing is a natural fit. Use a lightweight classifier or rules to judge request complexity: simple tasks go to the standard tier, and complex reasoning goes to the flagship tier. If the flagship tier handles 30% of traffic, overall input cost can drop by about 30%, with a similar reduction in output cost, while the experience loss is usually kept within single-digit percentages.
The routing layer should also include fallback and circuit breaking: automatically downgrade when the flagship tier is rate-limited or times out, and tag downgraded requests so you can backfill quality evaluation later.
5. Cost and Latency Control on the Output Side
Output is both expensive and slow, making it the second battleground. Available measures include: constraining fields and length with structured output, setting explicit word limits for summarization tasks, moving the “think before answering” intermediate process to internal reasoning rather than output content, and adding semantic-level caching for reusable results. Streaming responses also improve time to first byte and prevent users from resubmitting out of impatience, indirectly reducing wasted calls.
6. Observability and Capacity Planning
Cost governance needs a data loop. Recommended metrics: per-part token usage, cache hit rate, call share by tier, cost per request, and failure and retry rates. Pair logging and monitoring with alerts for two cases: a sudden spike in unit cost and a sharp drop in hit rate. For capacity planning, use 1.5x peak load as the stress-test baseline and keep a fallback path in reserve.
7. Implementation Checklist
- Add per-part billing instrumentation to see the cost distribution first;
- Refactor prompts to stabilize the prefix, targeting a hit rate above 60%;
- Ship difficulty routing and timeout fallback;
- Constrain output length and build a result cache;
- Review unit cost and quality metrics weekly, and adjust the tier mix dynamically.
A price cut only enlarges the optimization space. Real cost advantage comes from the engineering combination of caching, routing, and observability. If you already use Baidu AI Cloud capabilities, you can apply these methods directly to its model services and monitoring and alerting system, measuring input against output with the same set of metrics.
