LLM Cost Optimization: A Practical Guide to Reducing Token Spend

    This guide presents a vendor-neutral framework for understanding and reducing large language model API costs. It breaks the bill into four components—input, output, cache reads, and cache writes—and shows how discounts affect unit price rather than usage structure. It then covers four optimization paths: compressing input context, achieving real cache hits, routing tasks across model tiers with asynchronous batching, and building an observability loop for ongoing cost governance.

    1. Why the Experience Ultimately Shows Up on the Bill

    When teams evaluate a large language model service, they tend to focus on capability dimensions such as answer quality, time to first token, and long-context support. But once an application goes live and call volume grows from a few dozen requests a day to tens of thousands, what determines whether the solution is sustainable is often not a benchmark score but the monthly billing curve.

    A typical scenario looks like this: a team needs an intelligent coding assistant that can read the codebase of a mid-sized project, understand the dependencies between modules, and then output modification suggestions along with runnable code snippets. For this kind of task, a single request usually carries a context on the order of hundreds of thousands of tokens and produces output on the order of tens of thousands of tokens. Everything goes smoothly during functional validation, but once it is wired into a CI pipeline and runs hundreds of times automatically each day, the cost shifts from “negligible” to “needs a project proposal to discuss.”

    This article therefore does not discuss the pricing of any specific vendor. Instead, it abstracts the cost structure of LLM calls into a general model and provides transferable optimization techniques. The approach applies to any token-billed model service, and it also helps readers judge, when facing a limited-time discount, “how much the discount actually saves and whether it is worth adjusting the architecture for it.”

    2. The Cost Model: Do the Math Before Optimizing

    Mainstream LLM services generally bill by token usage, and the cost items can usually be broken into four categories:

    • Input cost: all context carried in the request, including system prompts, conversation history, retrieved material, and the code being analyzed;
    • Output cost: the answer generated by the model, usually priced higher than input;
    • Cache read cost: the read fee after a repeated prefix (such as a fixed system prompt or an unchanged knowledge fragment) hits the cache, generally significantly lower than normal input;
    • Cache write cost: the extra fee incurred when writing to the cache for the first time, which some services price separately.

    Writing these four items into a reusable estimation function is far more reliable than estimating by hand every time:

    1. def estimate_cost(input_tokens, output_tokens,
    2. cached_tokens=0,
    3. price_in=0.8, price_out=2.8,
    4. price_cache_read=0.23, price_cache_write=0.0):
    5. """Estimate the cost of a single call by token usage (unit: CNY, tokens priced per million)"""
    6. uncached_in = max(input_tokens - cached_tokens, 0)
    7. cost = (uncached_in * price_in
    8. + cached_tokens * price_cache_read
    9. + output_tokens * price_out
    10. + cached_tokens * price_cache_write)
    11. return cost / 1_000_000

    Take “500,000 input tokens, 20,000 output tokens, no cache hit” as an example. At a common price point (0.8 CNY input, 2.8 CNY output per million tokens), the single-call cost is about 0.456 CNY; if a similar service offers 50% off in a limited-time promotion, it drops to about 0.228 CNY. The key conclusion here is not “you saved half,” but rather: a discount only acts on unit price; it does not change the usage structure. If you make thousands of calls a month, the discount is indeed substantial; but if the input size balloons tenfold due to poor context management, any discount will be canceled out.

    3. Optimization Path 1: Compress the Input and Control Context Bloat

    Input is usually the main source of the bill, especially in scenarios like code analysis and long-document Q&A, where the input-to-output token ratio can reach 20:1 or even higher. Actionable practices include:

    1. Layered retrieval instead of full-volume feeding. First use keyword or vector retrieval to recall candidate fragments, then have the model answer within the candidate set, avoiding stuffing the entire codebase into the context.
    2. Structured trimming. For code, keep only signatures, type definitions, and key call chains; for logs, keep only exception stacks and a few adjacent lines.
    3. Summarization up front. For an unchanging long document, produce a one-time summary first, and have subsequent requests carry only the summary plus incremental content.
    4. Rolling compression of conversation history. In multi-turn scenarios, keep the most recent few turns verbatim and replace earlier content with summaries.

    Illustrative implementation:

    1. def build_context(full_text, max_chars=60000):
    2. if len(full_text) <= max_chars:
    3. return full_text
    4. head = full_text[: max_chars // 3]
    5. tail = full_text[-max_chars // 3:]
    6. middle_budget = max_chars - len(head) - len(tail)
    7. return head + "\n...(middle content omitted)...\n" + full_text[len(head): len(head) + middle_budget] + tail

    It must be emphasized that trimming must be premised on “not losing task-critical information.” It is advisable to build an offline evaluation set for the compression strategy, with dual checks from accuracy metrics and manual spot checks.

    4. Optimization Path 2: Make the Cache Actually Hit

    The cache read unit price is usually only 30% to 50% of normal input, making it the most cost-effective optimization point, but the hit rate depends on request structure. Engineering practice should follow three principles:

    • Stable prefix: put the system prompt, tool descriptions, and fixed knowledge at the very front, and do not change them frequently;
    • Variables last: put easily changing content such as timestamps, random IDs, and user input at the tail of the request;
    • Homogeneous batching: merge requests of the same task type into structurally consistent batches to increase the probability of prefix reuse.

    A counter-example is writing the current time into the first line of the system prompt, which makes the prefix of every request different and causes the cache to fail entirely.

    5. Optimization Path 3: Model Tiering and Asynchronous Batching

    Not every request needs the strongest model. You can route by task difficulty: give intent recognition, format conversion, and field extraction to a lightweight model; give complex reasoning and code generation to a more capable model. Combined with asynchronous and batch interfaces, non-real-time tasks (nightly code scans, offline report generation) can be run off-peak, which usually also yields extra unit-price discounts and a smoother concurrency curve.

    1. def route(task):
    2. if task["type"] in ("classify", "extract", "format"):
    3. return "light_model"
    4. return "strong_model"

    6. Optimization Path 4: Build an Observable Cost Governance Loop

    Cost optimization cannot rely on one-off parameter tuning; it needs to form a loop: at the gateway layer, uniformly record the input/output/cache token counts and cost of each call, tagged by business line, scenario, and caller; use monitoring alerts to set thresholds for day-over-day anomalies; output a weekly ranking of the top cost scenarios and prioritize the two or three scenarios with the highest share. Also set an “expiration reminder” for limited-time discounts to avoid a sudden bill spike after the promotion ends going unnoticed.

    7. Conclusion

    The cost experience of an LLM application is essentially the product of “usage structure + unit-price strategy.” Rather than chasing short-term discounts, it is better to make context compression, cache reuse, model tiering, and cost observability into default capabilities. Once this mechanism is in place, no matter how prices fluctuate, the team can maintain predictable, explainable, and optimizable control over the next bill.