Engineering Practices to Cut LLM Calling Costs by 90%

    This article explains how engineering teams can reduce large language model calling costs by around 90% without sacrificing quality. It covers building a unified gateway for cost attribution, improving cost transparency, compressing and governing context, adding exact and semantic caching, routing requests across model tiers, applying batching and rate limiting, and protecting quality with evaluation guardrails. A phased rollout path and expected savings are also included.

    1. Start With the Bill: Where the Cost Actually Goes

    Many teams feel that LLM calling costs rise for no clear reason. The root cause is usually the lack of an attribution model that can break the bill down by driver. The cost of a single call typically comes from three parts: input context (prompts, retrieved snippets, conversation history), output generation (the content returned by the model), and repeated consumption caused by retries and failures. In engineering terms, the controllable factors are the character scale of the first two and the share of wasted calls in the third.

    The first step is to build a unified gateway layer that logs the model identifier, input length, output length, latency, business identifier, and tenant identifier for every request into a logging service. This produces a cost dashboard that can be aggregated by dimension. Without this data layer, every later optimization is guesswork.

    1. request_id | tenant | scene | model | in_tokens | out_tokens | latency | retry_cnt | cost

    2. Transparency: Turning Opaque Billing Into Predictable Variables

    The original point about the value of “more transparent information” means three things in an engineering context: measurable, attributable, and predictable.

    • Measurable: aggregate input and output scale at the gateway instead of relying on after-the-fact invoices.
    • Attributable: tag every call with its business scenario and tenant to locate the largest consumers.
    • Predictable: build a cost model from historical distributions and produce a budget range plus alert thresholds before launch.

    Illustrative budget validation logic:

    1. def estimate_cost(in_tokens, out_tokens, price_in, price_out):
    2. return in_tokens * price_in + out_tokens * price_out
    3. if estimate_cost(ctx_len, max_out, p_in, p_out) > scene_budget:
    4. return degrade_or_truncate(ctx_len)

    3. Context Governance: The Most Direct Cost Lever

    The input side usually accounts for the largest share of total cost. Common sources of waste include repeatedly stuffing whole documents into the prompt, never trimming conversation history, and long, duplicated system prompts.

    1. Layer the prompts: separate stable system instructions from dynamic data so the stable part can be cached and reused.
    2. Compress retrieved snippets: rerank and remove redundancy first, keeping only the passages strongly related to the question.
    3. Trim history on a rolling basis: keep key information using both turn-based and summary-based strategies rather than concatenating everything.
    4. Prefer structure over long text: use fields when they can express the information instead of natural-language prose.

    4. Caching and Reuse: Making Repeated Requests Free

    Caching splits into exact caching and semantic caching. Exact caching keys on the hash of the normalized prompt. Semantic caching reuses a previous answer when vector similarity exceeds a threshold, with a validity period and invalidation policy. Include the scenario and permission dimensions in the cache key to avoid cross-tenant or unauthorized hits.

    1. key = hash(f"{tenant}:{scene}:{normalize(prompt)}")
    2. if hit := cache.get(key):
    3. return hit

    5. Model Routing: Matching Compute to Difficulty

    Not every request needs the strongest model. A three-tier routing setup works well: simple classification and extraction go to a lightweight model, routine question answering goes to the main model, and complex reasoning goes to a high-capability model. Routing decisions can rely on rules, small-model scoring, or confidence-based fallback, combined with quality spot checks to prevent drift.

    6. Batching and Rate Limiting: Better Output per Unit of Cost

    Merge offline-style tasks into batch requests to raise throughput and lower unit price significantly. For online paths, use token-bucket rate limiting, queue-based peak shaving, and timeout degradation to avoid uncontrolled retries during traffic spikes. Retries must use exponential backoff with an upper bound; otherwise failures multiply the bill.

    7. Quality Guardrails: Cost Cuts Must Not Cost Quality

    Maintain an offline evaluation set and an online spot-check mechanism, monitoring accuracy, refusal rate, and human rewrite rate. Every cost-reduction strategy ships through a canary release with a control group, and rolls back immediately if metrics regress. Cost optimization is continuous experimentation, not a one-time project.

    8. Rollout Path and Expected Savings

    In the first phase, connect the unified gateway and cost dashboard; this alone usually reveals obvious waste. In the second phase, apply context compression and caching. In the third phase, introduce routing and batching. Most teams can push wasted and duplicate consumption very low in the first two phases, and combined with routing and batching, total spending can drop by around 90%. If managed infrastructure is needed, general capabilities such as object storage, message queues, container platforms, logging services, and monitoring and alerting from Baidu AI Cloud can be used to build the system while keeping the metering and governance loop closed.