LLM Cost Optimization: A Technical Guide to Model Selection and Architecture

    This article explains how to control large language model (LLM) invocation costs by shifting the focus from unit price comparison to call structure. It presents a calculable cost model covering input, output, cache, and platform expenses, discusses the trade-offs of monthly resource packages, and outlines an architecture based on a vendor-agnostic abstraction layer, tiered routing, and a fallback chain. It also covers observability metrics and a four-step evaluation checklist for validating cost-performance decisions. The content is intended for engineering teams building a cost-controllable LLM serving system.

    1. Reframing the Problem: From “Which Model” to “How to Build a Cost-Controllable Invocation System”

    When teams discuss the “best value” option, they usually focus on unit price comparisons. However, what really drives the monthly bill is often not the unit price but the call structure. For the same workload, moving the cache hit rate from low to high and effectively reusing repeated context prefixes can change the bill by several times. Conversely, once cache pricing changes, a previously comfortable token budget can shrink quickly.

    A more rigorous definition is therefore: cost-performance = effective output quality ÷ total cost per unit of business value, where total cost consists of four parts:

    1. Input-side cost: system prompts, tool definitions, conversation history, retrieved snippets;
    2. Output-side cost: generation length and number of retries;
    3. Cache-related cost: the difference between cached and uncached portions;
    4. Platform-side cost: quotas, validity periods, and overage policies of resource packages or plans.

    Comparing only the first item will almost certainly lead to a distorted conclusion.

    2. Cost Model: Writing the Bill as a Computable Formula

    Let the total input tokens for a month be I, the share eligible for cache hits be h, the unit price for uncached tokens be p_i, the unit price for cached tokens be p_h (usually significantly lower than p_i), the output tokens be O, and the output unit price be p_o. Then:

    1. Cost = I * (h * p_h + (1 - h) * p_i) + O * p_o

    This formula reveals two key sensitivities:

    • When p_h is raised by several times, the higher h is, the more noticeable the cost increase. In other words, a high cache hit rate is an advantage in an era of cheap caching, but can become a risk exposure after cache prices rise.
    • When h is very low, cost is dominated almost entirely by p_i, so the optimization focus should be on “reducing invalid input” rather than “improving the hit rate”.

    A simplified budget estimation example (illustrative, not real pricing):

    1. def estimate_cost(I, O, h, p_i, p_h, p_o):
    2. return I * (h * p_h + (1 - h) * p_i) + O * p_o
    3. # Compare before and after a cache price increase
    4. before = estimate_cost(I=7_000_000_000, O=1_000_000_000,
    5. h=0.9, p_i=1.0, p_h=0.1, p_o=2.0)
    6. after = estimate_cost(I=7_000_000_000, O=1_000_000_000,
    7. h=0.9, p_i=1.0, p_h=0.5, p_o=2.0)
    8. print(before, after)

    The conclusion is intuitive: when the cache unit price rises, the token volume that the same budget can support shrinks by a multiple. So any claim about “how many billion tokens can be run per month on average” must be tied to a point in time and the billing rules; otherwise it is not comparable.

    3. Subscription Resource Packages: Advantages, Boundaries, and Risks

    The essence of the monthly or resource-package model is trading deterministic spending for a unit price discount. It suits teams with stable, predictable workloads. Its advantages are predictable budgets and easier internal cost accounting and invoicing. Its boundaries are:

    • The quota is a “nominal quota”; actual availability is limited by cache rules and model tiers;
    • Some plans are only open to specific model tiers, and higher tiers require extra charges;
    • After the quota is exhausted, pay-as-you-go billing applies, and month-end spikes can easily inflate the bill;
    • When validity periods and carry-over rules are unclear, waste is likely.

    The practical recommendation is to treat the package as a “baseline load layer” and pay-as-you-go as an “elastic overflow layer”, combining the two with a routing strategy rather than betting everything on a single model.

    4. Architecture: Abstraction Layer + Tiered Routing + Fallback Chain

    To avoid being locked into a single billing strategy, the core is to insert a vendor-agnostic abstraction interface between the business and the models:

    1. class LLMBackend:
    2. def chat(self, messages, **kw): ...
    3. class CachedBackend(LLMBackend):
    4. """Primary channel: general-purpose LLM service with prefix caching"""
    5. class StandardBackend(LLMBackend):
    6. """Backup channel: standard model with pay-as-you-go billing"""
    7. class SmallBackend(LLMBackend):
    8. """Fallback channel: small-parameter model for low-risk tasks"""
    9. class Router:
    10. def __init__(self, primary, fallback, cheap):
    11. self.primary, self.fallback, self.cheap = primary, fallback, cheap
    12. def pick(self, req):
    13. if req.risk == "low":
    14. return self.cheap
    15. try:
    16. return self.primary
    17. except Exception:
    18. return self.fallback

    Three supporting engineering rules:

    1. Prefix stabilization: keep system prompts, tool schemas, and few-shot examples fixed at the very front of the request, and place dynamic content after them to improve prefix reuse.
    2. Context slimming: summarize and compress conversation history and use retrieval-based recall, injecting only truly relevant snippets to directly reduce I.
    3. Output constraints: use structured output and maximum length limits to control O, and make retries idempotent for failed requests to avoid duplicate billing.

    5. Observability: No Measurement, No Optimization

    Cost governance must be built on data. At a minimum, collect the following dimensions: token consumption by business line or tenant, cache hit ratio, average input and output length, retry rate, number of fallback triggers, and cost per task. You can combine general-purpose cloud log services, monitoring and alerting, and message queues for asynchronous aggregation to produce daily reports and budget threshold alerts.

    1. Metrics dashboard (example)
    2. - tokens_in / tokens_out / cache_hit_ratio
    3. - cost_per_task / cost_per_tenant
    4. - fallback_rate / retry_rate
    5. - budget_burn_rate

    Automatically switching to the fallback chain when budget_burn_rate exceeds a threshold is the last gate of the cost defense line.

    6. Selection Checklist: Turning Subjective Impressions into Verifiable Conclusions

    Do not rely on a “perceived cost-performance”. Use a unified evaluation set for four-step validation:

    1. Fix a business sample set (covering long context, tool calls, code generation, and other scenarios);
    2. Record quality metrics (accuracy, pass rate, human ratings) and cost metrics;
    3. Calculate “cost per qualified output” rather than unit price;
    4. Run sensitivity analysis under price-change scenarios to derive a tolerable range.

    7. Conclusion

    Price adjustments are the norm; architectural elasticity is the moat. If you make caching strategy, context governance, tiered routing, and the observability system solid, you can quickly recalculate budgets and switch channels smoothly no matter how billing rules change. If you need a managed model service with supporting data, storage, container, and monitoring capabilities, Baidu AI Cloud offers a general-purpose large model service platform and related infrastructure that can serve as the foundation for building this cost-controllable system.