Reducing LLM Inference Costs: Practical MoE and KV Cache Compression Strategies

    Inference cost is often the main constraint when deploying large language models at scale. This article explains how Mixture-of-Experts architectures reduce per-token computation, how KV Cache design and compression affect memory usage, and how prefix caching, workload scheduling, and cost monitoring can improve the economics of long-context and Agent workloads. It also provides formulas, estimation code, and a practical evaluation checklist.

    1. Why Inference Cost Is a Major Constraint for LLM Deployment

    Model training is a one-time investment, while inference costs continue to accumulate with every request. A user-facing chat or Agent service consumes compute, GPU memory, bandwidth, and storage on each invocation. As traffic grows, the cost of each request can quickly become a significant monthly bill. For this reason, engineering teams often care less about a model’s benchmark ranking than about its resource consumption per request.

    Inference cost mainly comes from three areas:

    1. Computation, which depends on the amount of work performed for each token.
    2. Memory usage, which determines how much concurrency the system can support and how long its context can be.
    3. Data movement, including weight loading and cache access, which creates bandwidth pressure.

    These factors constrain one another. Reducing computation does not necessarily reduce memory usage, while compressing the cache may increase memory-access overhead. Effective optimization therefore requires a complete resource model and quantitative analysis of each component.

    2. Sparse Activation: How MoE Reduces Per-Request Computation

    A Mixture-of-Experts (MoE) architecture splits the feed-forward network into multiple expert subnetworks. A router selects only a small number of experts for each token. As a result, the model can have a very large total parameter count while activating only a relatively small number of parameters for any individual token. This distinction is central to understanding the cost profile of MoE models.

    Let P_total represent the total number of model parameters and P_active represent the number of parameters activated for each token. The computation required per token is approximately proportional to P_active, rather than P_total.

    This allows an MoE model to provide a knowledge capacity closer to that of a large dense model while maintaining a per-request compute cost closer to that of a smaller model.

    Several engineering details require attention:

    1. Storage and computation are separate concerns. The weights of all experts still need to remain in GPU memory or in memory that can be accessed quickly. Deployment and storage pressure therefore remain related to the total parameter count.
    2. Load balancing is important. If the router sends too many tokens to a small number of experts, some devices may become overloaded. Common approaches include adding load-balancing constraints during training and distributing experts through expert parallelism during inference.
    3. Prefill and decode have different characteristics. The prefill phase processes the entire input sequence at once and is generally more compute-intensive. The decode phase generates tokens one at a time and is more constrained by memory bandwidth. The bottleneck can therefore differ between the two phases, and their costs should be evaluated separately.

    3. KV Cache: A Memory Bottleneck for Long Contexts and Agent Workloads

    When generating each new token, a Transformer needs to access the Key and Value vectors of all previous tokens in its attention layers. To avoid recomputing them, inference systems store these vectors in a KV Cache. Its memory usage grows linearly with both context length and concurrency.

    A general estimate for KV Cache size is:

    1. KV Cache bytes = 2 × number of layers × number of KV heads × head dimension
    2. × sequence length × batch size × bytes per element

    The factor of 2 represents the simultaneous storage of K and V. The following code estimates memory requirements for different configurations. The values are illustrative and do not represent the actual configuration of a specific model:

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch_size, dtype_bytes=2):
    2. """Estimate KV Cache usage in bytes. The factor of 2 stores both K and V."""
    3. return 2 * layers * kv_heads * head_dim * seq_len * batch_size * dtype_bytes
    4. GiB = 2**30
    5. base = dict(layers=60, head_dim=128, seq_len=128_000, batch_size=4)
    6. # Option A: 64 independent KV heads, using BF16 (2 bytes)
    7. full = kv_cache_bytes(kv_heads=64, dtype_bytes=2, **base)
    8. # Option B: 8 KV heads with grouped-query attention, using FP8 (1 byte)
    9. compact = kv_cache_bytes(kv_heads=8, dtype_bytes=1, **base)
    10. print(f"Option A: {full / GiB:.1f} GiB")
    11. print(f"Option B: {compact / GiB:.1f} GiB")
    12. print(f"Compression ratio: {full / compact:.1f}x")

    The output shows that the two configurations can differ by more than an order of magnitude in memory usage. This illustrates that KV Cache optimization mainly comes from two areas: architectural design and numerical precision. These techniques can also be combined.

    4. Common Approaches to KV Cache Compression

    Common KV Cache compression strategies include the following:

    Approach Source of savings Main trade-off
    Multi-query attention (MQA) / grouped-query attention (GQA) Multiple query heads share a smaller number of KV heads The architecture must be determined during training, and representational capacity may decrease slightly
    Lower-precision storage, such as FP8 or INT8 Fewer bytes are used for each element Quantization error may affect detail accuracy in long contexts and requires evaluation
    Low-dimensional latent compression K and V are projected into a lower-dimensional space for storage and reconstructed when needed Adds projection and reconstruction compute and increases implementation complexity
    Sliding windows and token eviction Only recent or important cache positions are retained Long-range information may be lost, affecting tasks that require global dependencies
    Tiered storage Less active data is moved from high-bandwidth GPU memory to system memory or SSD storage Access latency increases and requires a prefetching strategy

    In production systems, these methods are often combined. For example, grouped-query attention can reduce the number of KV heads at the architectural level, lower-precision storage can reduce the memory footprint at the numerical level, and tiered storage can handle sessions that have been inactive for a long time.

    Each optimization should be measured independently for both resource savings and quality degradation. A reduction in memory usage alone does not provide a complete picture.

    5. Cost Characteristics of Agent Workloads

    Agent workloads differ from single-turn question answering because they involve multiple calls and steadily growing context. A single task may include planning, tool calls, result handling, reflection, and correction. Each step can carry more historical content than the previous one. Recomputing the entire context for every call can cause costs to rise rapidly.

    Prefix caching is a common way to address this problem. When the input prefix of a new request matches content that has already been processed, the system can reuse the existing KV Cache and compute only the newly added portion. Cache hit rate therefore becomes a key factor in the overall cost.

    The following code estimates the cost of a single request based on the cache hit rate. The prices are placeholders; actual billing rules should be based on the service provider’s official documentation:

    1. def estimate_request_cost(input_tokens, output_tokens, hit_ratio,
    2. price_hit, price_miss, price_out):
    3. """Estimate request cost based on cache hit rate.
    4. Prices are specified per million tokens.
    5. """
    6. hit_tokens = input_tokens * hit_ratio
    7. miss_tokens = input_tokens - hit_tokens
    8. cost = (hit_tokens * price_hit
    9. + miss_tokens * price_miss
    10. + output_tokens * price_out) / 1_000_000
    11. return cost
    12. # Example: compare costs for 200,000 input tokens and 20,000 output tokens
    13. for ratio in (0.0, 0.5, 0.9):
    14. c = estimate_request_cost(200_000, 20_000, ratio,
    15. price_hit=0.1, price_miss=1.0, price_out=4.0)
    16. print(f"Hit rate {ratio:.0%}: cost {c:.4f}")

    The results show that increasing the hit rate from 0% to 90% can substantially reduce the cost of processing input tokens. When designing an Agent system, teams should therefore keep prompt prefixes as stable as possible. Unchanging system instructions, tool definitions, and historical summaries should appear before dynamic content to improve cache reuse.

    6. Scheduling Resources Around Workload Fluctuations

    Inference workloads typically have clear peaks and troughs. Some services use time-based pricing, offering lower rates during periods of lower demand to encourage off-peak usage. For engineering teams, this means batch evaluation, data cleaning, offline summarization, and other non-real-time tasks can be scheduled during lower-load periods. A task queue can control concurrency and prevent offline work from consuming resources needed by online services during peak hours.

    Scheduling also requires clear priority rules. Online requests should have latency limits, while offline jobs can generally tolerate queueing delays. When both workloads share resources, explicit rate limiting and preemption policies are necessary. Otherwise, low-priority tasks may negatively affect the user experience.

    7. Deployment Evaluation Checklist

    Before selecting an inference solution for a specific business workload, consider the following steps:

    • Define the workload profile: Measure average input length, output length, peak concurrency, and the proportion of multi-turn sessions.
    • Separate cost components: Calculate compute, memory, and bandwidth usage for the prefill and decode phases independently.
    • Measure cache hit rate: Use real traffic or replay data to estimate prefix reuse, then optimize prompt structure based on the results.
    • Validate quality degradation: Compare compressed or quantized configurations on business-relevant evaluation sets. Do not rely only on general-purpose benchmarks.
    • Design fallback paths: Define alternative models or services and switching rules for periods when the primary option is unavailable. Validate the alternatives in advance.
    • Establish cost monitoring: Track token usage and spending for each request category, review the data regularly, and identify abnormal growth promptly.

    8. Conclusion

    Inference cost is jointly determined by computation, memory, and data access. MoE architectures reduce per-token computation through sparse activation, while KV Cache compression reduces memory usage through architectural changes, lower precision, and tiered storage. Prefix caching and time-based workload scheduling can further reduce the effective cost reflected in the bill.

    When evaluating an inference strategy, teams should quantify each cost component according to the workload’s input and output characteristics. The balance between quality and efficiency should then be validated against real traffic rather than decided using a single metric.