LLM API Cost Optimization: A Practical Guide to Prefix Caching, Output Control, and Model Routing

    A recent price cut on a flagship LLM API reveals where inference cost actually sits: cached input can be 100x cheaper than generated output. This guide breaks down the three token types (uncached input, cached input, output) and their billing semantics, then walks through four practical levers—stabilizing prompt prefixes so caching hits, trimming retrieved context, governing output length with structured schemas, and routing requests across model tiers. It also covers the observability metrics and capacity planning needed to keep cost and quality in balance, plus common pitfalls and a deployment checklist.

    1. What a Price Cut Reveals About Inference Cost Structure

    A cloud provider recently adjusted pricing for its flagship LLM service. The new high-tier version cut input and output unit prices by roughly 20% versus the previous generation, while cached input dropped by 60%. The three tiers now sit at $8, $0.40, and $40 per million tokens. The lightweight version kept the previous generation’s pricing: $2 for input, $0.10 for cached input, and $10 for output per million tokens.

    The technical signal here is not “it got cheaper.” It is that a two-order-of-magnitude gap now separates cached input from output.

    That gap dictates where architectural effort should go. For the high-tier version, output costs 100x a cached input token and 5x a standard input token. Context that is resent and hits the cache carries a negligible marginal cost, while every additional generated token costs one hundred times a cached read. The engineering conclusion is clear: the main battleground for cost reduction is structural reuse on the input side and length control on the output side, not simply switching to a cheaper model.

    2. Billing Semantics and Cost Weight of the Three Token Types

    Reading the bill starts with understanding the billing model. Requests are commonly split into three token categories:

    • Uncached input tokens: context added in this request that matches no reusable prefix, billed at the standard input rate.
    • Cached input tokens: context whose prefix is byte-for-byte identical to a prior request and is reused by the server, billed at a significantly lower cached rate.
    • Output tokens: the generated completion, at the highest unit price.

    Let a request have $u$ uncached input tokens, $c$ cached input tokens, and $o$ output tokens, priced at $p_u, p_c, p_o$. The cost per request is:

    1. cost = u * p_u + c * p_c + o * p_o

    Plugging in the high-tier prices ($p_u=8$, $p_c=0.4$, $p_o=40$, in USD per million tokens), a typical long-context request with 10,000 input tokens and 2,000 output tokens costs:

    • No cache hit: 10000×8/1e6 + 2000×40/1e6 = 0.08 + 0.08 = $0.16
    • 90% cache hit: 1000×8/1e6 + 9000×0.4/1e6 + 2000×40/1e6 = 0.008 + 0.0036 + 0.08 = $0.0916

    Input-side optimization saves about 43%, yet output still accounts for 87% of total cost. The takeaway: when output is long, any input-only optimization has a low ceiling.

    3. Four Actionable Optimization Levers

    3.1 Prefix Stability: Make the Cache Actually Hit

    Cache reuse requires a byte-for-byte identical prefix. The most common causes of misses in practice: prepending timestamps, random request IDs, or usernames to the system prompt; field-order drift from iterating over a dictionary in a template; and “in-place summarization” rewrites of history in multi-turn conversations.

    Layer the prompt into stable, semi-stable, and volatile sections:

    1. [Stable] role definition, output spec, safety policy, tool descriptions ← first, rarely changes
    2. [Semi-stable] domain knowledge, retrieved document chunks ← updated by version
    3. [Volatile] current user question, timestamp, session ID ← last

    Also maintain conversation history by appending rather than rewriting, so a modified history prefix does not invalidate the whole cached segment.

    3.2 Context Pruning: Shrink Input Volume

    For retrieval-augmented scenarios, rerank first and then truncate, keeping only the chunks most semantically relevant to the question. For long documents, extract structure first (headings, tables, conclusion sentences) before feeding them to the model. Deduplicate repeated citations. In practice, cutting noise chunks from 50% to 20% reduces input cost by roughly the same proportion, and answer accuracy typically holds or improves.

    3.3 Output Length Governance: Target the Largest Cost Driver

    Output carries the highest unit price and must be constrained explicitly. Combine these tactics: state word or item limits in the prompt; use structured output (for example, a JSON Schema constraint) to cut pleasantries and redundant explanation; replace long “reason then answer” chains with brief internal reasoning plus a concise conclusion; and validate generated length with automatic truncation and retry.

    1. {
    2. "type": "object",
    3. "properties": {
    4. "answer": { "type": "string", "maxLength": 800 },
    5. "citations": { "type": "array", "maxItems": 5 }
    6. },
    7. "required": ["answer"]
    8. }

    3.4 Tiered Model Routing: Match Compute to Difficulty

    The lightweight version’s output price is one quarter of the high-tier version, and so are its input and cached input prices. A routing layer is therefore the more sensible design: run a lightweight classifier first (a small model or rules will do), send simple requests to the lightweight model, and route complex reasoning and long-form generation to the high-tier model.

    1. def route(req):
    2. # Complexity signals: input length, need for multi-step reasoning, code/math involvement
    3. if req.est_output_tokens < 500 and req.complexity == "low":
    4. return "light_model"
    5. return "pro_model"

    Routing thresholds must be set from offline evaluation on real business samples, with “quality degradation stays within an agreed threshold” as the constraint, not intuition.

    4. Cost Observability and Capacity Planning

    Optimization has to be measurable. A minimal observability setup covers four metric groups: cache hit rate, average input/output token length, cost per request and cost per unit of business (such as cost per thousand Q&A turns), and quality metrics (accuracy, human adoption rate). Putting all four on one dashboard is what prevents the hidden loss of “cost went down but quality collapsed.”

    For capacity planning, estimate an upper bound as peak QPS × average tokens × unit price, and leave headroom for bursts. Set budget alerts and quota isolation so a single workload or tenant’s long-context requests cannot exhaust the overall budget. Logs, metrics, and tracing can rely on general-purpose logging, monitoring and alerting, and message queue capabilities to perform asynchronous metering, keeping billing logic off the critical path.

    5. Common Pitfalls

    • Watching unit price instead of structure: a 20% price cut is smaller than the gain from moving cache hit rate from 0% to 80%.
    • Switching everything to the lightweight model unconditionally: it typically has capability limits on long-chain reasoning and code tasks, so validate with a canary rollout.
    • Cache versus personalization conflict: putting personalized user content first keeps breaking prefix consistency; move it to the end.
    • Ignoring output governance: with long outputs, the ceiling on input-side optimization is very low.

    6. Deployment Checklist

    1. Is the prompt layered, with the stable layer first and free of volatile fields?
    2. Is conversation history maintained by appending?
    3. Are retrieved chunks reranked and deduplicated?
    4. Are structured output and length limits enabled?
    5. Is tiered routing in place, with the offline evaluation report retained?
    6. Are cache hit rate, cost per unit of business, and quality metrics visible on the same screen?
    7. Are budget alerts and tenant-level quota isolation configured?

    Following this framework, most long-context workloads can achieve meaningful cost reduction while keeping quality stable. In its model services and engineering practice, Baidu AI Cloud likewise recommends that enterprises optimize in this order—structural reuse first, output governance as the backstop, tiered routing for adjustment, and observability to close the loop—so that price benefits turn into a sustainable advantage in unit business cost.