LLM Cost Optimization and Model Selection: A Practical Guide

    This guide explains how to reduce large language model (LLM) inference costs without sacrificing output quality. It covers building cost observability with fine-grained logging, setting up tiered model routing, compressing context and using caching, enforcing quotas and budget guardrails, and running quality regression checks. The recommended rollout order helps teams lower spending while keeping quality under control.

    1. The Real Problem: From “Which Model Is Best” to “How to Combine Models”

    In production, teams rarely care about a single model’s absolute capability. What matters is the quality ceiling that can be delivered reliably within a given budget. When call statistics are broken down by model, a common pattern emerges: the models with the highest call volume are not the same ones with the highest cost. A few top models may handle most requests, but spending is concentrated in a small number of higher-priced models. A single high-priced model can account for more than 30% of total expenditure.

    This reveals two things. First, cost is not determined by how many models you use, but by how many times expensive models are called and how much context each call carries. Second, optimizing only for unit price yields limited gains. The effective lever is traffic structure.

    2. Build Cost Observability: Measure Before Optimizing

    Without fine-grained instrumentation, any optimization is guesswork. Log at least the following fields for every call:

    1. {
    2. "trace_id": "unique request trace identifier",
    3. "scene": "business scenario, e.g., summarization/extraction/chat/code completion",
    4. "model_tier": "high | mid | low",
    5. "prompt_tokens": 0,
    6. "completion_tokens": 0,
    7. "latency_ms": 0,
    8. "cache_hit": false,
    9. "fallback_from": "model tier before fallback",
    10. "result": "success | timeout | rejected"
    11. }

    The key is to bind token consumption to business scenarios, not just to models. This lets you answer “which scenario is burning money,” not only “which model is burning money.” Also convert cost into cost per unit of business output, such as cost per thousand ticket summaries or cost per valid extraction result, so that costs become comparable.

    3. Tiered Routing: Reserve Expensive Models for Requests That Need Them

    The core idea is a three-tier model pool: low-cost models handle high-frequency simple requests, while high-capability models handle complex ones.

    • High-capability tier: long-document reasoning, complex multi-step logic, low-tolerance generation;
    • Mid tier: routine Q&A, structured extraction, code completion;
    • Lightweight tier: intent recognition, tag classification, format conversion, batch summarization.

    Routing decisions should rely on rules and lightweight classifiers first, rather than letting a high-capability model make the judgment. Otherwise, routing itself becomes a cost center.

    1. def route(req):
    2. if req.estimated_tokens > 30000 or req.need_deep_reasoning:
    3. return "high"
    4. if req.scene in ("intent", "tag", "format"):
    5. return "low"
    6. return "mid"

    Combine this with automatic fallback based on timeouts and quality checks: if the lightweight tier’s output fails validation, escalate and retry. This avoids “one failure, expensive end to end.”

    4. Context and Caching: The Two Most Overlooked Sources of Waste

    Cost is roughly linear in token volume, so compressing context is often more effective than switching models. Actionable measures include: reranking retrieved snippets and keeping only highly relevant passages, applying rolling summaries to conversation history, turning stable system instructions and knowledge snippets into reusable prefixes to hit the cache, and merging requests for batch tasks.

    Semantic caching suits scenarios with high repetition, but you should set a similarity threshold and expiration policy, and explicitly skip the cache for requests that are strongly time-sensitive or highly personalized.

    1. if (hit := cache.get(sim_key(req))) and hit.score > 0.92:
    2. return hit.answer

    5. Quotas, Rate Limiting, and Budget Guardrails

    Encode budget constraints into the system instead of relying on manual monthly reviews. Set daily token quotas at the tenant and scenario levels, a per-request context limit, and concurrency and rate limits. When approaching thresholds, automatically switch to a lower model tier or queue requests. Every fallback should be flagged so you can later assess whether the quality loss is acceptable.

    6. Quality Regression: Cost Reduction Should Not Rely on Guesswork

    After each change to routing thresholds, caching strategy, or prompts, run a fixed evaluation set and track accuracy, structured-output compliance rate, long-document recall, and satisfaction from manual spot checks. Plot “cost per unit of business output” and quality metrics on the same dashboard. Only then can you tell whether an optimization is a real gain or a hidden liability.

    First, complete instrumentation and the cost dashboard. Second, segment scenarios and implement rule-based routing. Third, compress context and introduce caching. Fourth, add quotas and fallback guardrails. Fifth, establish a periodic evaluation and threshold-tuning mechanism. Following this order typically yields meaningful cost reductions without changing model capability, while keeping output quality under control. If you need elastic compute and supporting capabilities, you can build the pipeline above on your own using general product categories such as the container platform, object storage, log service, and monitoring and alerting offered by Baidu AI Cloud.