How to Cut LLM Inference Costs: A Practical Guide to Caching, Routing, and Context Compression

    Rising LLM service prices often expose a bigger problem than unit price: structural waste in how requests are made. This article breaks down inference cost into its four components and presents four reusable cost-reduction techniques—prompt and result caching, tiered model routing by task difficulty, context and output compression, and usage observability with quota governance. It includes sample code, structured logging fields, and a capacity estimation approach to help teams bring cost per task down to an acceptable range.

    When LLM service prices change, the cost pressure usually does not come from the unit price itself. It comes from structural waste in how requests are made. This article looks at inference cost from an engineering perspective and presents four reusable cost-reduction techniques: prompt and result caching, tiered scheduling by difficulty, context and output compression, and usage observability with quota governance. Sample code and a capacity estimation approach are included to help teams bring the cost per task into an acceptable range.

    1. Start by Breaking Down the Bill: Where Inference Cost Actually Goes

    When prices go up, many teams’ first reaction is to switch to a cheaper model. But without understanding the cost structure first, switching models often just moves the waste somewhere else. The cost of a single request typically has four components:

    1. Input side: system prompts, tool definitions, conversation history, and retrieved document fragments.
    2. Output side: the generated content itself, usually priced higher than input.
    3. Duplicate side: identical or highly similar requests computed repeatedly.
    4. Failure side: retries and reruns caused by truncation, invalid formatting, and timeouts.

    In engineering practice, the duplicate side and the failure side often account for a substantial share, and neither produces business value. So the first step in cost reduction is not cutting the unit price, but identifying the money that should not be spent.

    A simple self-check is to attach structured tags to every call so costs can be attributed later:

    1. {
    2. "trace_id": "req-8f3a",
    3. "scene": "code_review",
    4. "model_tier": "large",
    5. "input_tokens": 18240,
    6. "output_tokens": 960,
    7. "cache_hit": false,
    8. "retry_count": 2,
    9. "latency_ms": 7300
    10. }

    With this data, you can answer which scene, which model tier, and which retry the money went to.

    2. Technique 1: Cache Reuse, Turning Repeated Computation into Zero Cost

    Caching is the layer with the fastest payoff and the lowest risk. It falls into three types:

    • Exact caching: hash the normalized request body as the key and return the stored result directly on a hit. Suited to deterministic tasks such as classification, tagging, and format conversion.
    • Prefix caching: place stable prefixes such as system prompts, tool descriptions, and long documents at the beginning of the request, so the server can reuse the attention computation for the prefix and bill only the changing part. In practice this requires “stable content first, variable content last.”
    • Semantic caching: use vector nearest-neighbor matching for semantically equivalent questions and reuse the answer above a hit threshold. This requires a similarity threshold and manual spot checks to avoid incorrect reuse.

    Whether the prefix is stable directly determines the hit rate. A common anti-pattern is putting a timestamp or random ID at the very front of the prompt, which changes the prefix every time:

    1. # Bad example: unstable prefix
    2. Current time 2026-08-11 03:14:22, request ID r-9921
    3. You are a code review assistant...
    4. # Good example: stable prefix + trailing variables
    5. You are a code review assistant. Output according to the following rules:...
    6. --- Content to review for this request ---
    7. [Request ID r-9921] diff: ...

    In coding scenarios, repository rules, dependency lists, and code snippets are referenced repeatedly, so the hit rate can usually be pushed quite high. Each step up in hit rate multiplies the usable token volume relative to the resource package. This is also the fundamental reason a resource package lasts longer than pay-as-you-go billing: you buy a nominal allowance, and actual consumption depends on caching efficiency.

    3. Technique 2: Tiered Scheduling, So Strong Models Only Handle Hard Problems

    Having a single model handle all traffic is the most typical cost waste. A more reasonable approach is to tier tasks by difficulty:

    Tier Tasks handled Characteristics
    Lightweight tier Rewriting, summarization, field extraction, intent recognition Short context, small answer space
    Standard tier Routine business generation, single-file code changes Requires some reasoning and format adherence
    Heavy reasoning tier Cross-module refactoring, complex troubleshooting, solution design Long chains, multiple constraints, error-prone

    In practice, combine rule-based routing with confidence-based routing: first judge difficulty with low-cost means, then decide whether to escalate.

    1. def route(task):
    2. if task["need_cross_file"] or task["est_steps"] > 6:
    3. return "reasoning" # heavy reasoning tier
    4. if task["schema_strict"] and task["input_tokens"] < 2000:
    5. return "light" # lightweight tier, structured output
    6. return "standard" # standard tier

    A combination that has repeatedly proven effective is “strong model plans, economical model executes, strong model spot-checks”: the planning stage has few calls but high value, the execution stage has large token volume but low difficulty, and spot checks sample only high-risk cases. This controls total volume while keeping a quality safety net.

    Note that some models tend to show “insufficient initiative” on long tasks—they do not fill in missing steps on their own, so the caller must break the flow down to a fine enough granularity. The engineering response is to make the planning output explicit as a step list and dispatch it step by step:

    1. {
    2. "plan_id": "p-114",
    3. "steps": [
    4. {"id": 1, "action": "locate_entry", "acceptance": "provide file and function name"},
    5. {"id": 2, "action": "patch", "acceptance": "diff passes syntax check"},
    6. {"id": 3, "action": "verify", "acceptance": "all unit tests green"}
    7. ]
    8. }

    4. Technique 3: Context and Output Compression

    Both input tokens and output tokens are billed, so compression works in both directions.

    On the input side, you can rerank retrieval results and keep only the Top-K fragments, produce a structured summary of long documents before passing them in, apply rolling summaries to conversation history, and trim tool definitions on demand rather than injecting all of them. A practical approach is to set a “budget cap” for context and evict by importance when the budget is exceeded, instead of letting requests grow without limit.

    On the output side, you can constrain output to structured fields rather than long natural-language text, prohibit restatements that carry no information, and separate “explanation” from “result,” requesting the explanation only when needed.

    1. def build_context(chunks, budget=6000):
    2. chunks = sorted(chunks, key=lambda c: c["score"], reverse=True)
    3. picked, used = [], 0
    4. for c in chunks:
    5. if used + c["tokens"] > budget:
    6. continue
    7. picked.append(c)
    8. used += c["tokens"]
    9. return picked, used

    5. Technique 4: Usage Observability, Quotas, and Failure Governance

    Without observability there is no cost reduction. Collect at least five metrics—call volume, token distribution, cache hit rate, retry rate, and cost per task—and aggregate them by scene and user dimension to form a cost dashboard with alert thresholds.

    Governance on the failure side is equally important: set limited retries with backoff for timeouts and format errors to avoid avalanche-style duplicate billing, and use sampled review rather than full review for high-risk outputs.

    1. for attempt in range(3):
    2. try:
    3. resp = call_model(payload, timeout=20)
    4. if validate(resp):
    5. return resp
    6. except TimeoutError:
    7. sleep(2 ** attempt)
    8. raise FallbackError("fall back to rule-based template")

    6. Capacity Estimation: How Long a Resource Package Actually Lasts

    To judge whether a resource package is worthwhile, use the following estimation:

    1. usable tokens ≈ nominal allowance ÷ (1 - cache hit rate)
    2. monthly consumption ≈ daily tasks × average tokens per task × 30

    For example, 2,000 tasks per day at an average of 8,000 tokens per task gives roughly 480 million tokens per month. If the cache hit rate is high, the actual capacity corresponding to the nominal allowance can be multiplied several times. When selecting a plan, treat “hit rate” and “retry rate” as first-class metrics in the evaluation rather than comparing only the listed price.

    7. Rollout Path and Common Pitfalls

    A four-step rollout is recommended: first add structured instrumentation, then add prefix and exact caching, then implement tiered routing, and finally add context budgets and quota alerts.

    Common pitfalls include: writing variable content into a stable prefix and collapsing the hit rate; setting the semantic cache threshold too loose and causing incorrect reuse; compressing only the input without constraining the output; retries without a limit inflating the bill; and lacking per-scene attribution, so cost-reduction measures cannot be traced to real gains.

    Overall, the pressure from a price change is essentially a reminder to build inference calls as an engineering capability that needs governance. Do caching, tiering, compression, and observability solidly, and an order-of-magnitude reduction in cost per task is an expected result. If you use Baidu AI Cloud services, you can also combine general capabilities such as monitoring and alerting and log services to complete the cost attribution chain.