LLM Cost Optimization: A Framework for Model Selection and Architecture

    As LLM pricing shifts from a simple per-token rate to a structural concern, cost control becomes an architecture problem. This article breaks down the three core variables that drive real spending—cache hit rates, tiered model routing, and quota allocation across task types—and explains why the lowest listed price per million tokens is often misleading. It presents a reusable cost-efficiency framework, a prefix caching cost formula, a sample routing skeleton, a capacity planning template, and the observability metrics needed to close the governance loop, helping developers make stable technical decisions under pricing uncertainty.

    LLM call costs are shifting from a “price per token” problem to an “architecture” problem. Across the original discussion, only three core variables keep recurring: the marginal cost change driven by cache hits, hybrid scheduling across different capability tiers, and the allocation efficiency of plan quotas across task types. When upstream pricing structures change, any approach that relies on a single model or a single calling pattern will see severe cost volatility. This article abstracts away specific products and lays out a reusable cost-efficiency evaluation framework and an engineering practice path, so developers can make more robust technical decisions in an environment of pricing uncertainty.

    1. Why the Lowest Unit Price Is Not the Best Value

    When selecting models, many teams focus on the listed price per million tokens. It is the easiest metric to obtain and the most misleading one. A real bill is determined by four factors together:

    1. The ratio of input to output. Code comprehension and documentation generation tasks have inputs far larger than outputs, while summarization and rewriting tasks are the opposite; the two have completely different effects on the bill.
    2. The cache hit rate. Services with prefix caching offer an order-of-magnitude cost advantage for repeated system prompts, long repository context, and fixed tool descriptions; once the caching policy or billing method changes, the cost structure changes immediately.
    3. Failures and retries. Retries caused by timeouts, truncation, and non-compliant formatting are often a hidden expense on the bill that goes unnoticed.
    4. Model tier allocation. Using a high-capability model for exploratory work that a lightweight model could handle is the most common form of waste.

    Therefore, the correct definition of cost-efficiency is: the total cost consumed per unit of effective output (for example, each merged code change or each successfully parsed response) under the premise of meeting quality and latency constraints.

    2. Cache Hits: The Most Sensitive Variable in the Cost Model

    The essence of prefix caching is to reuse the computed result of the unchanged portion and recompute only the newly added part. Its impact on cost can be approximated as:

    1. effective input cost ≈ fixed prefix × hit-rate discount + incremental input × original price + output × output unit price

    From the formula, when the fixed prefix accounts for a high proportion (for example, unified system instructions, long-term unchanged project context, and a stable tool schema), the overall cost is almost determined by the hit rate. This also explains why, once caching billing rules are adjusted, the overall available quota can shrink by a multiple—it is not that the model became more expensive, but that the most sensitive item in the cost model was amplified.

    Three disciplines to maintain in engineering:

    • Prioritize prefix stability. Put volatile content (timestamps, random IDs, user input) at the end of the prompt to avoid polluting the cacheable prefix.
    • Layer the context. Strictly partition long-term project conventions, short-term task context, and one-off input, so that hits and invalidation are easier to control.
    • Bring the hit rate into monitoring. Report the cache hit rate as a first-class metric, place it on the same dashboard as token usage and failure rate, and make sure abnormal fluctuations can be traced back to specific prompt changes.

    3. Tiered Model Routing: Spend “Expensive” Where It Counts

    Mature cost-control approaches almost always move toward hybrid scheduling: lightweight, low-latency models handle exploration and filtering, while high-capability models handle final decisions and complex reasoning. A practical routing skeleton is as follows:

    1. def route(task):
    2. # Tier 1: lightweight model for exploration, retrieval-style Q&A, candidate generation
    3. if task.kind in {"explore", "summarize", "classify"}:
    4. return light_model, {"temperature": 0.2, "max_tokens": 2048}
    5. # Tier 2: mid-capability model for structured generation and routine coding
    6. if task.risk == "low" and task.context_tokens < 8000:
    7. return mid_model, {"temperature": 0.3, "max_tokens": 4096}
    8. # Tier 3: high-capability model only for high-risk, long-chain reasoning
    9. return strong_model, {"temperature": 0.1, "max_tokens": 8192}

    The key to a routing strategy is that it must be “fallback-capable” and “measurable.” Every downgrade or upgrade should record its reason, forming an analyzable sample set; otherwise cost optimization degenerates into tuning parameters by feel. It is also advisable to set independent budget caps and circuit-breaker thresholds for each tier, so that when a certain class of tasks amplifies abnormally, it will not break through the overall quota.

    4. Quota Planning: From “How Long It Lasts” to “How to Allocate”

    A common mistake with plan-based quotas is estimating only the total volume and not the structure. A more reliable approach is to profile tasks first, then allocate by proportion:

    • Exploratory tasks usually consume a large amount of input tokens and a small amount of output, making them suitable for cache-friendly, low-unit-price lightweight models;
    • Generation and refactoring tasks have a high output proportion, so the output unit price should be evaluated closely;
    • Low-frequency tasks such as high-risk review and complex defect localization can tolerate a higher unit price, but a call limit must be set.

    A simple capacity estimation template:

    1. monthly demand = Σ(task type token usage × share of that task type × safety factor 1.3)
    2. allocation ratio = lightweight 60% / mid 30% / high-capability 10% (adjust based on measurements)

    The safety factor is used to absorb retries, context expansion, and demand fluctuations. If upstream prices or caching rules change, you only need to recompute the affected items rather than overturn the entire architecture.

    5. Observability and the Governance Loop

    Cost governance ultimately comes down to observability. It is recommended to collect at least the following dimensions: tokens and cost by model tier, cache hit rate, time to first token and overall latency, failure and retry rate, and cost per task. With this data, you can answer questions like “did this bill increase come from call volume, cache invalidation, or a model upgrade.”

    For the governance process, a lightweight admission mechanism can be introduced: run a cost regression test before a new prompt template goes live, comparing cost per unit of output against a fixed sample set; require an explanation for changes that exceed the baseline. This turns cost from “checking the bill at the end of the month” into “verifiable at every change.”

    6. Architecture Principles for Volatility

    In the face of continuous changes in upstream prices and rules, what is truly stable is not a low-price choice but four principles: capability tiering, prefix stability, structured quotas, and observable metrics. By explicitly modeling the cost-sensitive points, any price adjustment will only trigger a local parameter recomputation rather than an architecture-level rebuild. For teams, this both preserves room to adopt a better cost-efficiency option at the right time and avoids being locked into a single supplier relationship. If a unified resource foundation is needed, you can combine general capabilities such as the container platform, log service, and monitoring and alerting offered by Baidu AI Cloud to consolidate cost accounting and call governance into a sustainable engineering process.