LLM API Cost Optimization: How to Cut Bills with Prefix Caching, Routing, and Budget Controls

    This article breaks down why a recent LLM API price cut can lower bills even as token usage grows, then shows how to model request cost, raise prefix cache hit rates, and control spending through tiered routing, context compression, batching, and budget governance. It includes practical code examples, engineering checklist items, and advice for handling limited-time discounts without baking temporary pricing into long-term architecture.

    1. Why a Price Cut Made the Bill Smaller

    A recent industry development: a flagship model’s official API introduced a limited-time discount while permanently reducing cache pricing to roughly one-tenth of the previous rate. One developer’s billing record is representative. On launch day, the model consumed about 3.9 million tokens at a cost of about 75 CNY. The next day, with the limited-time discount in effect, consumption rose to 4.1 million tokens but the cost fell to about 41 CNY. On the third day, with the cache price reduction stacked on top, consumption reached 6.5 million tokens at a cost of less than 10 CNY.

    Usage nearly doubled while spending dropped to one-tenth. This is not a billing error. Three variables changed at the same time: the discount factor, cache pricing, and cache hit rate. Understanding how these three interact is more valuable than memorizing the unit price on any single day, because discounts expire while a lower cache pricing structure is a long-term benefit.

    2. Cost Model: Breaking the Bill into Four Computable Terms

    For any token-based API, the cost of a single request can be abstracted as:

    1. Cost = (P_in * T_in_miss + P_in * c * T_in_hit)
    2. + (P_out * T_out)

    Here T_in_miss is the number of input tokens that miss the cache, T_in_hit is the number of input tokens that hit the cache, and c is the cache discount factor. A common industry practice is to charge the cached portion at a lower fraction of the original price; some providers also charge separately for cache writes. P_out is typically significantly higher than P_in.

    This yields three engineering conclusions:

    1. The input side is the main battleground for long-context scenarios. When the input-to-output ratio reaches dozens to one, improving the input hit rate pays off far more than compressing the output.
    2. Cache savings are non-linear. Raising the hit rate from 70% to 90% saves more than 20 percentage points; it moves the vast majority of repeated prefixes into the low-price range.
    3. Output cannot be cached. To reduce output cost, you can only cut unnecessary generation, cap the maximum output length, and move deterministic logic out of the model.

    3. Cache Hit Rate: From Guesswork to Measurement

    Many teams complain that caching is “hit or miss.” The root cause is usually an unstable request prefix. Mainstream inference services implement prefix caching on the premise that the prefix is byte-for-byte identical, so patterns like the following drive the hit rate to zero:

    1. # Bad example: timestamp and random ID at the front change the prefix every time
    2. prompt = f"Current time {now()} Request ID {uuid4()}\n" + SYSTEM + user_input

    The correct approach is to put stable content first and volatile content last:

    1. SYSTEM = "You are a code review assistant that follows these rules..." # long and constant
    2. def build_messages(system: str, history: list, query: str):
    3. return [
    4. {"role": "system", "content": system},
    5. *history, # keep prior turns as-is; do not rewrite summaries
    6. {"role": "user", "content": query},
    7. ]

    Four supporting practices:

    • Layer the prefix: system prompt -> tool and API definitions -> long-term knowledge snippets -> conversation history -> current input. Once the layer order is fixed, do not change it casually.
    • No dynamic injection: do not concatenate fast-changing fields such as the current time, random numbers, rollout flags, or user nicknames into the system prompt; if truly necessary, place them at the end of the conversation.
    • Control cache lifetime: most implementations evict cached entries after a period of inactivity, so a fixed prefix only pays off when called frequently; a low-frequency long prefix may end up paying write costs for nothing.
    • Make it observable: log hit and miss tokens for every request on the client side and build a hit-rate time series, so you can tell whether an optimization actually works.
    1. def log_usage(resp, ctx):
    2. u = resp.usage
    3. hit = getattr(u, "prompt_cache_hit_tokens", 0)
    4. miss = getattr(u, "prompt_cache_miss_tokens", 0)
    5. total = hit + miss or 1
    6. metrics.histogram("llm.cache.hit_ratio", hit / total, tags=ctx)
    7. metrics.counter("llm.cost.estimated", estimate_cost(u), tags=ctx)

    4. Architecture-Level Savings: Routing, Compression, and Batching

    Price is only one lever; architecture sets the floor.

    Tiered routing. Split tasks by difficulty: send simple requests to a lightweight model and complex reasoning to the flagship model, using rules or a small classifier for the upfront decision:

    1. def route(task):
    2. if task.kind in {"classify", "extract", "format"}:
    3. return "light"
    4. if task.requires_long_context and task.stakes == "high":
    5. return "pro"
    6. return "standard"

    Context compression. For long documents, apply retrieval-based trimming or structured summarization first, replacing “stuff the whole thing in” with “include only relevant snippets.” This improves both hit rate and accuracy.

    Batching and asynchrony. Merging requests and running offline jobs off-peak can significantly improve throughput and unit cost; for online paths, streaming output reduces duplicate charges caused by timeout retries.

    Retries need a circuit breaker. Unlimited retries are a common cause of runaway bills; always set a maximum attempt count, a timeout, and an idempotency key.

    5. Handling Discount Periods Rationally

    A limited-time discount is essentially a customer acquisition tactic, and it can easily lead teams to bake temporary low prices into long-term architecture. Recommendations:

    • Model the monthly budget with two sets of parameters, discounted and original, and confirm the business still holds at the original price;
    • Make model names, unit prices, and cache factors configurable instead of scattering them across the code;
    • Keep an abstraction layer so switching providers or self-hosting inference stays manageable in cost;
    • Check whether a dedicated channel and stability commitment are offered; third-party resale paths are typically weaker than direct official connections in rate limiting and availability.

    6. Bill Governance and Alerting

    Set up three gates: a daily budget, week-over-week spike detection, and a per-request cap, along with a cost attribution dashboard tagged by business line. When a path’s hit rate drops sharply or output tokens spike, alerts should point to the specific caller rather than the aggregate. If an organization already runs inference services in the cloud, it can use object storage for corpora, a message queue for peak shaving, a container platform for elastic replicas, and logging and monitoring services for cost visibility. These are general capability categories and do not imply dependence on any specific product.

    Conclusion

    Discounts expire; cache price reductions do not. Lasting advantage comes from stable prefix design, measurable hit rates, tiered routing, and strict budget governance. Treat cost as an engineering metric that needs continuous profiling rather than a one-time procurement decision, and you will keep the initiative through the next round of price swings.