LLM Cost Reduction in Practice: Sparse Architectures and KV Cache

    This article explains where LLM inference costs come from and examines practical levers for reducing them: MoE sparse activation, long-context windows, and KV cache prefix caching. It covers cache hit conditions, billing calculations with a worked example, deployment engineering considerations, and a validation checklist that teams can use before choosing an architecture or caching strategy.

    LLM Cost Reduction in Practice: Sparse Architectures and KV Cache

    Large language models have moved from the lab into day-to-day business operations. Customer service, document understanding, code generation, and multi-turn dialogue all rely on model calls. As call volume grows, inference cost and response latency become major obstacles to expanding adoption. Reducing cost while maintaining quality is an unavoidable issue for enterprise deployment. This article starts with the sources of cost, discusses three common optimization approaches one by one, and provides methods that can be used directly for evaluation.

    1. Where Costs Come From

    Inference cost is mainly determined by two factors: the amount of computation per token, and the GPU memory occupied by model weights and intermediate states. A traditional dense model activates all parameters when processing each token. The larger the parameter count, the higher the computation per call, and the higher the cost.

    Complex document understanding, code generation, and multi-turn dialogue share a common pattern: long inputs and frequent calls. If every call is billed at full computation, the cost of a single task can quickly exceed what the business can bear. Therefore, cost reduction needs to address two directions at the same time: reducing computation per inference and avoiding repeated computation for repeated content.

    2. MoE Sparse Activation: One Feasible Approach

    Mixture of Experts (MoE) is one approach to reducing computation. Taking a publicly described model as an example, its total parameter count is 224B, while each inference activates only about 12B parameters, an activation ratio of roughly 5%.

    This structure works as follows. The model contains multiple expert subnetworks. A routing network selects a small number of experts for each token based on the input content. The model retains the knowledge capacity brought by a large parameter count, while computation for each token passes through only a small portion of the parameters.

    Two points require attention. First, computation can be approximately reduced according to activated parameters, but GPU memory capacity does not decrease in the same way. If all expert weights must remain resident in GPU memory, memory requirements still depend on the total parameter count. Second, actual memory bandwidth usage is affected by batch size, routing distribution, expert loading method, and quantization strategy. It cannot be converted simply according to the activation ratio. Therefore, MoE models are suitable for scenarios with high throughput and sufficient batching. Low-concurrency scenarios may not show a cost advantage.

    3. What 1M Context Is Good For and Where Its Limits Are

    A 1M-token context window allows the model to read a large amount of material at once. In Chinese, 1M tokens is roughly 500,000 to 1,000,000 characters, depending on the tokenizer and text type. The number of image inputs is affected by resolution and tiling strategy and cannot be estimated simply by the number of images.

    Long context can reduce dependence on external retrieval. In the past, when processing long reports, a common approach was to split the document into chunks and retrieve relevant passages from a vector database. This increased system complexity and could lose information across paragraphs. By placing the material directly into the context, the model can compare and summarize across the full text.

    Long context also has clear costs. The longer the input, the more computation is required in the prefill stage, and the higher the GPU memory usage. For retrieval scenarios across multiple documents, RAG remains the more suitable approach. Long context is suitable for holistic understanding of a single long document, comparative analysis of multiple related files, and generation tasks that require global consistency.

    4. How KV Cache Prefix Caching Hits and How It Is Billed

    KV Cache stores the key-value states generated when the model processes historical tokens. When the beginning of a new request is exactly the same as a previous request, the server can reuse this state and skip repeated computation. This mechanism is called prefix caching.

    1. Hit Conditions

    Prefix caching usually requires the following conditions to be met at the same time:

    • The beginning of the request must match the previous request token by token. System instructions and fixed document content should be placed at the front of the messages.
    • Dynamic content, such as timestamps, request IDs, and user IDs, should be placed at the end. Placing them at the beginning breaks prefix consistency.
    • The cache must be within its time to live (TTL). After expiry, the cache is cleared, and the next request must recompute.
    • The cache storage location is determined by the platform and may be in GPU memory, host memory, or a dedicated cache service.

    2. Billing Basis

    Most platforms bill hit input tokens at a lower price. Some platforms also charge for cache storage. Specific rules should be based on the platform documentation.

    The following hypothetical scenario illustrates the calculation. Assume the input contains a shared prefix of 100,000 tokens, plus a new question of 1,000 tokens, and an output of 500 tokens. Example prices are: miss input at CNY 0.5 per million tokens, hit input at CNY 0.02 per million tokens, and output at CNY 2 per million tokens.

    • On a miss, the input cost is approximately 101,000 × 0.5 ÷ 1,000,000 ≈ CNY 0.0505, and the output cost is approximately CNY 0.001, for a total of approximately CNY 0.0515.
    • On a prefix hit, the prefix portion costs approximately 100,000 × 0.02 ÷ 1,000,000 = CNY 0.002, the new question portion costs approximately CNY 0.0005, and the output cost remains CNY 0.001, for a total of approximately CNY 0.0035.

    Under this assumption, the cost per request is about 1/15 of the miss case. The actual savings depend on the hit rate, the proportion of the prefix in the input, and the output length. When the hit rate is lower than expected, savings shrink noticeably. Therefore, before formal evaluation, you should first measure the hit rate in your own business.

    3. Call Example

    The following example shows how to construct a request that can hit the prefix cache and read the number of hit tokens. Field names differ across platforms. Please refer to the relevant API documentation.

    1. import os
    2. import requests
    3. URL = "https://api.example-cloud.com/v1/chat/completions"
    4. API_KEY = os.environ["LLM_API_KEY"] # Read from an environment variable; do not hard-code it
    5. # Put the shared prefix (system instruction and long document) first, and dynamic content last
    6. messages = [
    7. {"role": "system", "content": "You are a professional data analysis assistant."},
    8. {"role": "user", "content": "This is the financial report data for pages 1 to 100..."},
    9. {"role": "assistant", "content": "Received. I have recorded this data."},
    10. {"role": "user", "content": "Based on the previous data, please calculate the profit margin for the fourth quarter."},
    11. ]
    12. payload = {
    13. "model": "cost-effective-large-model-v1",
    14. "messages": messages,
    15. "max_tokens": 500,
    16. "temperature": 0.3,
    17. }
    18. try:
    19. resp = requests.post(
    20. URL,
    21. headers={
    22. "Authorization": f"Bearer {API_KEY}",
    23. "Content-Type": "application/json",
    24. },
    25. json=payload,
    26. timeout=30,
    27. )
    28. resp.raise_for_status()
    29. except requests.RequestException as exc:
    30. raise SystemExit(f"Request failed: {exc}")
    31. result = resp.json()
    32. usage = result.get("usage", {})
    33. # For OpenAI-compatible APIs, the common hit field is prompt_tokens_details.cached_tokens.
    34. # Other platforms may use different field names; adjust according to the documentation.
    35. details = usage.get("prompt_tokens_details") or {}
    36. hit_tokens = details.get("cached_tokens", usage.get("prompt_cache_hit_tokens", 0))
    37. print(f"Input tokens that hit the cache in this request: {hit_tokens}")

    5. Engineering Considerations for Deployment

    The following is an example architecture used to explain the responsibilities of each component. It does not constitute a commitment to any cloud product selection. The actual solution should be determined by latency requirements, concurrency, and budget. Taking Baidu AI Cloud as an example, the division of responsibilities can be as follows.

    1. The container platform handles elastic scaling: MoE models have large weight sizes, and instances start slowly. A container engine such as Baidu AI Cloud Container Engine (CCE) can be used to manage GPU resources and pre-warm instances before traffic peaks. Scaling policies should be determined based on measured cold-start time.

    2. The caching layer has clear responsibilities: Core prefix cache data should remain inside the inference engine, such as the prefix caching features provided by frameworks like vLLM and SGLang. Sharing cache across instances requires low-latency networking and consistency mechanisms and is usually much more complex than single-instance caching. Redis is suitable for storing cache metadata and routing information. Object storage is suitable for offline logs and snapshots, but not for hosting online KV Cache, because read latency cannot meet online inference requirements. Message queues are suitable for asynchronous tasks, such as batch offline inference and log writing.

    3. Monitor core metrics: Continuously record token consumption, cache hit rate, time to first token, and cost per task. A drop in hit rate often means the prompt structure has been changed or dynamic content has been placed in the prefix position. Monitoring data can directly guide prompt adjustments.

    4. Multi-model routing: Simple tasks such as classification and information extraction can be handled by lightweight models or models with small activated parameter counts. Complex reasoning can then call larger models. Routing rules should be based on task type and historical quality evaluation results, not only on word count.

    6. Validation Checklist Before Choosing a Solution

    Before formally adopting a solution, it is recommended to complete the following checks with your own data:

    • Cache hit rate: Use real request logs to calculate the prefix hit ratio, and calculate it separately by business type.
    • Cost per task: Calculate according to hit rate, input length, and output length, and compare with the current solution.
    • Latency distribution: Focus on P95 and P99 latency, not only the average. Long-context and large-batch requests often perform poorly in the tail latency.
    • Output quality: Use a fixed evaluation set to compare the results of different models and configurations. If quality drops significantly after cost reduction, the savings may be offset by rework costs.
    • Capacity planning: Confirm whether GPU memory is sufficient to hold all expert weights, and test throughput at the target concurrency.

    7. Conclusion

    Reducing LLM inference cost requires addressing computation, context length, and repeated computation at the same time. MoE sparse activation can reduce computation per token, but memory requirements and bandwidth behavior still need separate evaluation. Long context can simplify the processing flow for a single document while bringing higher computation and memory overhead. Prefix caching is effective when the hit rate is high, but gains are limited when the hit rate is low.

    For enterprise users, the most reliable approach is to first measure the hit rate, length distribution, and quality requirements of their own business, and then choose the architecture and caching strategy based on that data. Cost estimates should be based on real traffic, not on a single number from a general benchmark.