LLM Cost Optimization: Technical Selection and Engineering Practices

    This article breaks down large language model (LLM) cost optimization into measurable dimensions, including cost per effective output, cache hit rate, and task-to-model capability fit. It explains how prefix caching, prompt restructuring, token budget modeling, capability tiering with multi-model routing, observability, and contract-level risk controls help teams keep quality, latency, and billing in balance when upstream prices change. Readers will find request organization patterns, pseudocode for prompt building, cost calculation and routing, plus a practical implementation checklist.

    1. The Core Problem: Turning “Cost-Effectiveness” into a Measurable Metric

    When upstream model prices change by several multiples, debates about “which option is more cost-effective” often stay at the level of impressions. A more rigorous approach is to break cost-effectiveness into three measurable dimensions: cost per unit of effective output, cache reuse rate, and how well the task matches the model’s capabilities. Only when these three are quantified will price fluctuations stop being amplified into billing incidents.

    Cost per unit of effective output is not the same as the list price. What actually drives the bill is the total input and output tokens required to complete the task, multiplied by the cache hit ratio, multiplied by the unit price for the corresponding tier. For the same workload, if the prompt structure is stable and the system instructions are long and repetitive, the cache hit rate can be very high. Conversely, if every request prepends a large amount of changing content, the hit rate approaches zero, and costs can differ by several multiples.

    Therefore, the first priority in cost optimization is not switching models, but restructuring requests: put stable, unchanging content first, and volatile content last.

    2. Cache Hits: The Most Sensitive Cost Lever During Price Increases

    Mainstream inference services commonly offer prefix caching, where the cached portion is billed at a significantly lower unit price than the uncached portion. This means that when cache-related prices are raised several times, the bill structure changes nonlinearly: a hit portion that once accounted for a small share can quickly become the main expense.

    A reusable request organization pattern is as follows:

    1. [Stable prefix] System role, tool definitions, long documents, few-shot examples, output specifications
    2. [Semi-stable section] Conversation summary, structured context
    3. [Volatile suffix] Current user input, timestamps, random IDs

    Corresponding pseudocode:

    1. def build_prompt(system_block, summary, user_input):
    2. # system_block must be byte-for-byte stable; avoid any timestamp or random value polluting the prefix
    3. stable = system_block # the key region for cache hits
    4. semi = summary or ""
    5. volatile = user_input # always place changing content last
    6. return f"{stable}\n{semi}\n{volatile}"

    Engineering practice requires three supporting measures. First, monitor the cache hit rate and the share of cached tokens, treating them as core cost metrics rather than secondary ones. Second, maintain change records for prompt versions, since any prefix change invalidates the entire cache. Third, set budget alerts with thresholds by day and by tenant, so anomalies are not discovered only at month-end.

    3. Token Budget Modeling: Calculate First, Then Select

    It is advisable to produce a budget table during the architecture review, with fields including average daily requests, average input length, average output length, cache hit rate, peak concurrency, and acceptable latency. With this table, any price adjustment can be converted into a monthly cost range within minutes, instead of relying on gut feeling.

    Illustrative calculation logic:

    1. def monthly_cost(reqs_per_day, in_tok, out_tok, hit_ratio,
    2. price_in, price_out, price_cached, days=30):
    3. total_in = reqs_per_day * in_tok * days
    4. cached = total_in * hit_ratio
    5. uncached = total_in - cached
    6. return cached * price_cached + uncached * price_in + reqs_per_day * out_tok * days * price_out

    The key conclusion here is that when the cached unit price is raised several times, the gains from improving the hit rate and shortening the prefix far outweigh the gains from repeatedly comparing model tiers. In other words, the main battlefield for cost governance is the request construction layer, not the procurement layer.

    4. Capability Tiering and Multi-Model Routing: Avoid a One-Size-Fits-All Approach

    Different tasks vary greatly in their demand for model capability. Mixing high-difficulty reasoning tasks with simple classification, extraction, and formatting tasks in the same tier is the most common source of waste. A practical approach is to establish capability tiers: complex reasoning and code generation go to a stronger tier; summarization, tagging, and structured extraction go to a lightweight tier; latency-sensitive online paths set a smaller output limit.

    The routing layer can use dual channels of rules and confidence:

    1. def route(task):
    2. if task.kind in ("code", "math", "multi_hop"):
    3. return "strong"
    4. if task.kind in ("extract", "classify", "format"):
    5. return "light"
    6. return "strong" if task.risk == "high" else "light"

    A fallback path must also be designed: when the primary tier encounters rate limiting or a pricing policy change, degrade in the order of “next-best option with the same capability → lightweight tier plus prompt compensation → queuing or asynchronous processing,” ensuring business availability takes priority over cost optimality.

    5. Observability and Governance: Making Costs Attributable

    Cost overruns are usually not a unit price problem but a lack of attribution. It is recommended to collect at least four types of data: token consumption by business line or tenant, cache hit distribution, per-request cost percentiles (P50/P95), and the extra consumption caused by failed retries. Retries are often a hidden cost driver and require a maximum retry count and idempotency controls.

    On the data side, invocation logs and usage metrics can be delivered to logging services and monitoring and alerting systems, with cost budget thresholds and period-over-period anomaly detection configured. For unstructured context, object storage can be used for hot and cold tiering to reduce repeatedly carrying large content in every request, lowering input tokens at the source.

    6. Contract and Process-Level Risk Control

    Price adjustments are the norm, so the architecture should assume that unit prices will change. Therefore, it is recommended to abstract a unified model invocation gateway that shields upper-layer business from differences between specific tiers; make unit prices, quotas, and cache policies configurable with hot updates; keep at least two viable technical routes for critical paths; and clarify invoicing, billing cycles, and quota change notification mechanisms in the procurement process, avoiding a disconnect between finance and engineering information.

    7. Implementation Checklist

    1. Identify the top 10 high-consumption scenarios, noting input and output lengths and cache feasibility;
    2. Refactor prompts to stabilize the prefix, and prohibit injecting timestamps or random values into the prefix;
    3. Build a budget table and a monthly cost conversion script, and incorporate them into the review process;
    4. Launch three core dashboards: hit rate, P95 per-request cost, and retry rate;
    5. Implement capability-tiered routing and fallback paths, and drill them regularly;
    6. Make unit prices and quotas configurable, and form an emergency response plan for price changes.

    With these steps, a team can turn a one-time procurement judgment about the “most cost-effective choice” into a sustainable cost engineering capability: no matter how upstream prices change, it can find a controllable balance among quality, latency, and billing.