MoE and Caching: Cutting LLM Serving Costs for AI Agents
This article examines two techniques for reducing the cost of large language model (LLM) inference in AI agent scenarios: Mixture of Experts (MoE) architecture and context caching. It explains how MoE reduces per-request computation through sparse activation, and how prompt caching eliminates redundant prefill computation for repeated context. The article also outlines the deployment prerequisites, memory constraints, and common pitfalls to consider when evaluating these approaches.
What AI Agents Demand from LLMs
A typical AI agent uses a “local gateway plus cloud model” architecture. The local gateway listens for user terminal commands and code-save events, structuring them into well-formed prompts. The cloud model interprets the intent and returns executable instructions.
This setup imposes three key requirements on the underlying LLM:
- Low time to first token (TTFT) — Users experience noticeable lag if the first token is slow.
- Long-context retention — The model must maintain system prompts, user preferences, and historical actions across a session.
- Scalable cost per call — The inference cost must be sustainable at scale.
Traditional dense models face a challenge here: the attention computation grows rapidly with sequence length, making it difficult to satisfy all three requirements simultaneously.
MoE Architecture: Reducing Computation Per Inference
Mixture of Experts (MoE) uses a gating network to handle each input token. The gate scores each expert sub-network and activates only the top-scoring few for computation.
For example, a model with a trillion total parameters might activate only a few billion parameters per inference. This lowers the amount of computation and reduces the weights that must be read for each request.
Here is a simplified illustration of the routing logic:
def moe_inference(input_tokens, expert_weights, gate_network):# The gating network scores each expert for every tokengate_logits = gate_network(input_tokens)# Select the top-K experts (e.g., K=2)top_k_experts = get_top_k(gate_logits, k=2)# Compute only with the selected expertsoutput = 0for expert_idx in top_k_experts:output += expert_weights[expert_idx](input_tokens)return output
However, sparse activation does not automatically translate to low latency. Real-world latency depends on several factors:
- Routing balance — If too many tokens are routed to a small set of experts, those experts become a bottleneck while others sit idle.
- Communication overhead in expert parallelism — Experts distributed across multiple GPUs require inter-GPU data transfer, which can offset the computational savings.
- Memory bandwidth — Inference is often limited by the speed of reading weights rather than compute itself.
- Batch size — Small batches underutilize hardware; large batches increase queueing time.
So the TTFT improvement from MoE depends on the specific deployment. When routing is balanced, communication is controlled, and batch sizes are reasonable, MoE provides higher throughput on the same hardware and faster per-request responses.
Context Caching: Avoiding Repeated Computation at the Cost of Memory
In agent workloads, system prompts, conversation history, and project code often stay unchanged across many requests. Prompt caching saves the KV Cache for this recurring content. Subsequent requests only need to send the new or appended content, and the model reuses the cached KV states without recomputing attention on the full prefix.
The primary saving is in the prefill phase. When the cache hits, both the input token computation cost and the time to first token are reduced.
Caching is not free, though. KV Cache resides in GPU memory, and its size can be estimated with the following formula:
Memory ≈ 2 × layers × KV heads × head dimension × context length × bytes per element × concurrent sessions
For example: a model with 60 layers, 8 KV heads, 128 dimensions per head, a 256K token context, and FP16 format (2 bytes per element) would require roughly 2 × 60 × 8 × 128 × 256000 × 2 bytes, or about 63 GB for a single session at full context. This is an estimate; the exact number depends on the model architecture and quantization, so refer to your model’s configuration file.
Long contexts consume GPU memory quickly, and concurrent sessions multiply the usage. Service providers typically set a cache capacity limit and rely on eviction policies such as least recently used (LRU).
Cost reduction from caching therefore requires careful measurement. Key variables include the cache hit rate, average context length, degree of concurrency, model and hardware specifics, and how the provider bills for cache usage. Since price structures vary, avoid applying another provider’s numbers to your own scenario.
The Role of “Intelligent Commons” and Compute Subsidies
An “intelligent commons” refers to an open ecosystem where model providers, developers, and platforms collaborate. Models are made available at low or even zero cost, and developers build applications on top of them. It is important to note the boundaries: subsidies have time limits, free quotas have ceilings, and switching to another model later can carry significant migration costs.
The purpose of compute subsidies is to establish developer habits and ecosystem lock-in. For developers, short-term free credits lower the barrier to validation, but they should not be treated as a reliable long-term cost assumption.
For enterprise deployment, you can use container services, object storage, message queues, and API gateways from your cloud provider to build an agent pipeline. Pay attention to the following:
- API selection — Compare unit price, TTFT, context length, and cache billing rules, rather than just the per-token price.
- Cost monitoring — Track token usage and cache hit rates per model, session, and function.
- Logging and alerting — Record request latency, error rates, and TTFT, and set threshold alerts.
- Data residency — Since agents read code and operation logs, confirm how long data is stored, where it resides, and whether it is used for training.
Common Mistakes
- Focusing only on unit price while ignoring TTFT and cache hit rates.
- Overlooking the GPU memory footprint of caching, which leads to capacity shortfalls under long contexts or high concurrency.
- Treating free quotas as a permanent cost basis.
- Assuming that sparse activation equals low latency without verifying routing balance and communication overhead.
Conclusion
MoE reduces computation per inference, and context caching eliminates redundant prefill work. Both can lower the operating cost of AI agents. However, their real-world effect depends on deployment conditions, GPU memory capacity, and actual usage patterns. Before migrating, test your own workload to measure the real impact.
