An Architecture Playbook for Cutting LLM API Costs
As LLM API prices fall, cost control shifts from unit price to structure. This guide explains how to build a token-level cost model, maximize prompt cache hit rates, route requests between mid-tier and flagship models, control output length, and use batch processing. It also covers observability and governance practices to keep unit costs from rebounding, plus a four-week rollout plan. If you want to implement these practices on Baidu AI Cloud, you can combine general-purpose logging, monitoring and alerting, message queues, and container platforms to build a complete cost governance loop.
1. The Signal: From Unit-Price Sensitivity to Structure Sensitivity
A cloud provider recently released a new generation of LLM services. For the flagship tier, input and output unit prices dropped by roughly 20% compared with the previous generation, while the cached-input price fell by 60%. The mid-tier model kept the previous generation’s pricing: $2 per million tokens for input, $0.1 for cached input, and $10 for output. The flagship tier is priced at $8 for input, $0.4 for cached input, and $40 for output.
The informative part of these numbers is not how much prices dropped, but the ratio between the three tiers. For the flagship tier, the output price is 5x the input price, while the cached-input price is only 5% of the input price. This makes the bill extremely sensitive to which bucket a token falls into: for the same call, whether the prompt hits the cache and whether the generation length gets out of control can produce cost differences of several multiples. The mid-tier shows a similar ratio (output at 5x input, cached input at 5% of input), which suggests this is a common industry pricing structure rather than a one-off strategy from a single provider.
The conclusion is straightforward: lower unit prices are an external windfall, while optimizing the cost structure is an internal capability. If call volume scales with business growth, the savings from price cuts can easily be offset.
2. Do the Math First: Build a Token-Level Cost Model
Optimization starts with measurement. Break cost down into the smallest attributable unit instead of looking only at the monthly total bill.
A practical cost formula looks like this:
Cost per request =input tokens × input unit price+ cached-hit tokens × cached-input unit price+ uncached input tokens × input unit price+ output tokens × output unit price
Cached-hit and uncached tokens must be counted separately; otherwise you cannot evaluate the effect of your caching strategy. In engineering terms, add instrumentation along the call path to record the four token counts per request, the model tier used, latency, and the number of failed retries. Write these to a logging service or a time-series database, then configure thresholds through monitoring and alerting.
Attribution dimensions should include at least: business line, API path, tenant/user ID, model tier, and whether the cache was hit. Missing any of these dimensions will reduce later optimization to “tuning parameters by feel.”
3. Cache Hit Rate: The Biggest Reduction Is Worth the Most Investment
The cached-input price is only about 5% of the input price, making it the highest-leverage optimization item. The core principle for improving hit rate is “stable prefix, variable content last”:
- Put the system prompt, tool definitions, few-shot examples, and long-document background at the very front of the prompt, and keep them byte-for-byte stable. Do not insert timestamps, random IDs, or request sequence numbers.
- Put the user’s current input and dynamically retrieved fragments at the end.
- Version-control your templates. A template change counts as cache invalidation, so evaluate how often changes occur.
- For long-document scenarios, prefer structured chunking and fixed-order concatenation to avoid jitter in the order of retrieval results.
An illustrative structure:
[Stable prefix: role setup + output spec + tool schema + fixed examples][Semi-stable section: product docs/knowledge base fragments, concatenated in a fixed order][Variable section: this turn's user question + context summary]
Note that whether the cache takes effect, at what granularity, and under what invalidation rules is determined by the specific platform implementation. In engineering, rely on measured hit rates and do not assume that “an identical prefix guarantees a hit.” Launch a hit-rate dashboard, track trends by business line, and set alerts for sudden drops in hit rate. Common causes include accidental template edits, jitter in retrieval order, and gateways rewriting request bodies.
4. Model Routing: Not Every Request Deserves the Flagship Tier
There is roughly a 4x unit-price gap between the mid-tier and flagship tiers ($2 vs. $8 for input, $10 vs. $40 for output). Layering requests by difficulty is a key way to balance cost and quality.
Actionable signals include: input length, whether the input contains structured data, task type (extraction/classification/rewriting vs. multi-step reasoning/code generation), and historical confidence (e.g., escalate only low-confidence samples in classification tasks).
def route(req):# Simple, short, structured tasks go to the mid tierif req.task in {"classify", "extract", "rewrite"} and req.input_tokens < 2000:return "mid"# Low confidence or complex reasoning escalates to flagshipif req.confidence is not None and req.confidence < 0.6:return "flagship"return "mid"
Routing needs a fallback mechanism: keep request fingerprints and sample responses for quality checks, and periodically assess whether the escalation ratio is drifting. If the flagship-tier call share keeps rising without improvement in business metrics, the routing rules need to be tightened.
5. Output Length and Batching: Two Easily Overlooked Sources of Waste
The output price is 5x the input price, so controlling generation length is often more effective than compressing the input. Practices include: explicitly limiting output format and word count, using structured output to constrain fields, separating the “reasoning process” from the “final answer” and keeping only the latter, and applying semantic caching to reusable results (returning a historical answer directly for the same question).
Batching is another cost-reduction path. Scenarios such as offline summarization, log labeling, batch translation, and content moderation can aggregate requests into batches and run them asynchronously within a business-acceptable time window, usually in exchange for a better billing tier. In engineering, design a task queue, idempotency keys, and timeout retries to avoid duplicate billing.
Online path: low latency, small batches, strong cachingOffline path: large batches, deferrable, cost-first
6. Observability and Governance: Keeping Costs from Rebounding
After a price cut, the most likely outcome is a retaliatory surge in usage. Governance has three layers:
- Quota layer: set token budgets and rate limits per tenant and per API; when exceeded, downgrade to the mid tier or queue the request.
- Observability layer: establish unit business cost metrics (e.g., cost per thousand Q&A turns, cost per moderation job) rather than only looking at total token volume.
- Review layer: compare three metrics weekly—hit rate, routing distribution, and average output length—to locate the source of anomalies.
Also factor failed retries into cost accounting. Timeouts, rate limiting, and content blocks all trigger retries; without backoff and deduplication, the bill can rise nonlinearly during peak hours. Set a cap on retry counts and record the distribution of retry reasons.
7. Suggested Rollout Order
- Week 1: Complete token-level instrumentation and the cost dashboard; define the four token categories and attribution dimensions.
- Week 2: Restructure prompts, stabilize the prefix, and measure changes in cache hit rate.
- Week 3: Launch model routing and output-length constraints, and watch unit business cost.
- Week 4: Integrate the batch-processing path and quota governance, and establish a weekly review cadence.
Overall, lower unit prices only reduce the intercept of the cost curve. What really determines the bill are three controllable variables: cache hit rate, tier selection, and output length. Making these three into sustainably observable engineering metrics is what keeps unit cost declining steadily as business scale expands.
