LLM Cost Optimization: Engineering Practices for Sparse Activation and Cache Reuse

    This article explains how to reduce the cost of running LLM-based agents in production. It covers how to account for per-task token costs, the difference between total and activated parameters in Mixture-of-Experts models, prompt design for prefix caching, long-context and multimodal cost control, evaluating models by cost per successful task, tiered routing with fallback, cost observability, and related risks.

    1. Background: Why Cost Becomes a Key Constraint for Agent Adoption

    Once large language models move from single-turn Q&A to agent-based workflows, the number of calls required to complete a task increases significantly. A single document-editing or spreadsheet-repair job typically involves task planning, information retrieval, tool invocation, and result validation, with the context resubmitted on every round. As a result, cost is no longer determined by unit price alone, but by the total tokens consumed per task together with the task success rate.

    Engineering teams usually need to answer three questions. First, what does an average task cost? Second, how does cost grow as task scale increases? Third, which stages can be trimmed while keeping quality acceptable? Answering these questions is the prerequisite for any cost-reduction plan.

    2. Cost Composition and Accounting Method

    The cost of a single model call typically consists of the following parts.

    1. Input tokens: system prompts, conversation history, retrieved passages, and tool outputs all count as input. The longer the context, the higher the input cost.
    2. Output tokens: longer generations cost more and take more time. Output length should be capped according to task needs.
    3. Cached tokens: when an identical prefix is reused by the service provider, this portion of input is usually billed at a lower rate than uncached input. Whether it is supported and how it is billed depends on the provider’s mechanism; refer to the official pricing documentation.
    4. Concurrency and peak load: queuing or degraded service during peak hours increases latency, which indirectly raises business waiting costs and retry costs.

    Based on this composition, the cost of a single task can be written as:

    Task cost = Σ (uncached input tokens in round i × input price + cached input tokens × cached price + output tokens × output price)

    The corresponding accounting code is shown below. Prices should be replaced with the values from the official price list of the service you use:

    1. def estimate_task_cost(rounds, input_price, cached_price, output_price):
    2. """
    3. rounds: list of per-call statistics, each containing input_tokens,
    4. cached_input_tokens, output_tokens
    5. input_price / cached_price / output_price: price per token
    6. """
    7. total = 0.0
    8. for r in rounds:
    9. hit = r["cached_input_tokens"]
    10. miss = r["input_tokens"] - hit
    11. total += miss * input_price
    12. total += hit * cached_price
    13. total += r["output_tokens"] * output_price
    14. return total

    The value of this code is that it breaks the cost down to each round. Teams can use it to identify the most expensive stages, such as an oversized tool response or an output that ran out of control in a particular round.

    3. Sparse Activation: Total Parameters vs. Activated Parameters

    A Mixture of Experts (MoE) architecture contains multiple groups of expert subnetworks. For each input token, the routing mechanism selects only a small number of these experts to participate in computation. Therefore, two metrics must be distinguished when evaluating model scale.

    • Total parameters determine the model’s capacity ceiling and affect GPU memory or storage footprint.
    • Activated parameters determine the main computation per token and are directly related to inference latency and per-unit compute consumption.

    This means a model with a very large total parameter count does not necessarily incur proportionally large inference overhead. When selecting a model, look at both numbers and judge them together with the GPU memory capacity, memory bandwidth, and target concurrency of your deployment environment.

    Note that sparse activation reduces computation, but routing decisions, inter-expert communication, and memory scheduling introduce additional overhead. Actual throughput is affected by hardware, batching strategy, and request length, and should be confirmed through load testing rather than inferred from theoretical parameters alone.

    4. Prefix Caching: Put Stable Content First

    The principle of prefix caching is that when two requests begin identically, the server can reuse intermediate results that have already been computed. To take advantage of this mechanism, the prompt structure needs deliberate design.

    1. Put system instructions and tool definitions first. This part barely changes within a session.
    2. Keep conversation history in append-only order. Do not insert or rewrite existing messages in the middle, or the prefix after that point will be invalidated entirely.
    3. Put dynamic content at the end, including the current user question and real-time retrieval results.

    Example code:

    1. def build_messages(system_prompt, tool_schema, history, retrieved_docs, user_query):
    2. # Stable parts first to enable prefix reuse
    3. messages = [
    4. {"role": "system", "content": system_prompt},
    5. {"role": "system", "content": tool_schema},
    6. ]
    7. # History is append-only; no mid-sequence rewriting
    8. messages.extend(history)
    9. # Dynamic content goes at the end
    10. messages.append({
    11. "role": "user",
    12. "content": f"References:\n{retrieved_docs}\n\nQuestion:\n{user_query}"
    13. })
    14. return messages

    A common mistake is inserting the current timestamp, a random request ID, or a user name into the system prompt. These fields change on every request, preventing the prefix from matching and reducing cache benefits to nearly zero. When troubleshooting, compare the prefix strings of two consecutive requests to confirm they are exactly identical.

    5. Long Context: Window Size Is Not a Usage Strategy

    Some models support context windows of a million tokens or more, theoretically large enough to hold an entire code repository or a lengthy document in one call. But window capacity only indicates how much input the model can accept, not that everything should be sent every time.

    • Cost grows with input volume. Stuffing the full text in significantly increases per-call cost.
    • Information position affects utilization. Key information placed near the question is generally used more reliably than information buried in the middle of a long text.
    • Retrieval and chunking remain valuable. Narrowing the scope through retrieval first and then sending only relevant passages achieves a better balance between cost and accuracy.

    In practice, a “filter first, then send” strategy works well. First locate relevant passages with a lightweight method, then send only the matched content together with the question. For tasks that genuinely require global understanding, such as cross-file refactoring, full input can be considered, but the cost should be estimated in advance and capped.

    6. Cost Control for Multimodal Input

    Images, audio, and video typically consume more tokens than text carrying the same amount of information, so their size should be controlled at the preprocessing stage.

    • Images: reduce resolution according to task needs and crop regions irrelevant to the task. For example, when recognizing numbers in a table, only the region containing the table is needed.
    • Video: prefer extracting key frames rather than feeding every frame. Key frames can be selected based on the magnitude of visual change.
    • Audio: transcribe to text first, then hand it to a text model. This applies to scenarios where only semantic content is needed.

    The goal of multimodal preprocessing is to keep the information the task requires and remove redundancy. Preprocessing itself also has a compute cost, which should be compared against the cost of direct input before deciding.

    7. Evaluating Models by Cost per Successful Task

    Comparing unit prices alone can be misleading. A cheaper model with a lower success rate may require multiple retries, ending up more expensive in total. Therefore, “cost per successful task” should be the core metric.

    The evaluation steps are as follows.

    1. Select 50 to 200 representative tasks covering typical scenarios such as document editing, spreadsheet processing, code modification, and information extraction.
    2. For each task, record token consumption, number of calls, latency, and validation results.
    3. Compute the cost per successful task.
    1. def cost_per_success(results):
    2. """
    3. results: list where each item contains cost (total cost of the task)
    4. and passed (whether it passed validation)
    5. """
    6. total_cost = sum(r["cost"] for r in results)
    7. successes = sum(1 for r in results if r["passed"])
    8. if successes == 0:
    9. return float("inf")
    10. return total_cost / successes

    Note that validation criteria must be objective and automatable. For document tasks, check structural completeness and the presence of key fields; for code tasks, run test cases. Once the criteria rely on subjective judgment, the comparison loses its value.

    8. Tiered Routing with Escalation

    Not every task requires the strongest model. Routing simple tasks to a lower-cost model and complex tasks to a more capable one can reduce overall spending. The key is to include a validation step that automatically escalates when the cheaper model’s output fails validation.

    1. def run_with_routing(task, cheap_model, strong_model, validator):
    2. # Let the low-cost model handle it first
    3. result = cheap_model.run(task)
    4. if validator(result):
    5. return result
    6. # Validation failed; escalate to the stronger model
    7. result = strong_model.run(task)
    8. if validator(result):
    9. return result
    10. raise RuntimeError("Task failed validation on both model tiers")

    Routing rules can be based on task type, input length, or historical failure rates. For example, format conversion of short text can go directly to the low-cost model, while multi-file code modification defaults to the high-capability model. Rules should be adjusted periodically based on evaluation data.

    9. Observability: Making Cost Visible

    After a cost-reduction plan is deployed, continuous monitoring is required. It is recommended to track at least the following metrics.

    • Average tokens per task, broken down by task type.
    • Cache hit rate; if it falls below expectations, check whether the prompt structure has been broken.
    • Task success rate and retry counts.
    • Latency percentiles, such as P95 latency.
    • Daily and monthly cost, with threshold-based alerts.

    These data can be written to a logging service, with thresholds configured in a monitoring and alerting system. When the unit cost of a task category suddenly rises, the team can quickly locate the cause, such as a modified prompt, larger retrieval results, or a malfunctioning tool.

    10. Risks and Precautions

    Cost reduction must not come at the expense of quality and safety. The following three categories of risk need to be mitigated in advance.

    • Quality