## MoE and Context Caching for AI Agents: Limits on Latency and Cost Gains
This article explains how Mixture-of-Experts (MoE) models and prefix context caching affect latency and cost in AI agents that rely on cloud models. It covers when each technique helps, the conditions it depends on, how to measure results with your own call logs instead of promotional figures, and engineering checks for the cloud backend.
1. Why AI Agents Are Sensitive to Latency
A modern agent typically uses a structure that pairs a local gateway with a cloud large language model. The local gateway captures events such as terminal commands and browser actions. It sends the context to the cloud model for intent understanding and task planning, then returns the result to the local machine for execution. On this path, time to first token (TTFT) in the cloud determines how long the user perceives a pause. If every operation takes several seconds to start, users feel that the system is sluggish.
For this reason, when you evaluate the base model for an agent, look at three metrics together: TTFT, output tokens per second (tokens/s), and end-to-end P95 latency. Looking at only one of them can easily lead to a one-sided conclusion.
2. How MoE Reduces Computation per Call
A dense model uses all of its parameters in every forward pass, so its compute grows roughly linearly with parameter count. MoE (Mixture of Experts) splits the feed-forward layers into multiple expert networks. A router selects the top k experts with the highest scores for each token, and only those experts compute their outputs.
Take some publicly reported leading models as an example. Their total parameters can reach the trillion scale, while each inference activates about 32 billion parameters. The compute per call is therefore close to that of a 32-billion-parameter dense model, even though the model’s total capacity is far larger.
Keep three points in mind when using MoE:
- Total parameters still have to reside in GPU memory or be sharded across multiple cards. MoE reduces the compute per call and the memory bandwidth needed for reads, but it does not reduce the model’s size.
- Routing needs load balancing. If a few experts are selected over and over, the cards hosting them become bottlenecks, and overall throughput drops.
- Whether a single card can hold the model depends on total parameters, quantization precision, the parallelism strategy, and memory capacity. Activated parameter count alone does not answer that question.
The following illustrative pseudocode shows the basic routing flow. It omits production-grade optimizations such as the load-balancing loss and grouped matrix multiplication. Do not use it directly for training or deployment.
import torchimport torch.nn as nnclass MoELayer(nn.Module):def __init__(self, hidden_size, num_experts, top_k):super().__init__()self.top_k = top_kself.router = nn.Linear(hidden_size, num_experts)self.experts = nn.ModuleList([nn.Sequential(nn.Linear(hidden_size, 4 * hidden_size),nn.GELU(),nn.Linear(4 * hidden_size, hidden_size),)for _ in range(num_experts)])def forward(self, x): # x: [tokens, hidden]logits = self.router(x) # [tokens, num_experts]scores, idx = torch.topk(logits, self.top_k, dim=-1)weights = torch.softmax(scores, dim=-1) # Normalize over the selected expertsout = torch.zeros_like(x)for e, expert in enumerate(self.experts):mask = (idx == e) # [tokens, top_k]rows = mask.any(dim=-1) # Tokens routed to expert eif rows.any():w = (weights * mask).sum(dim=-1)[rows].unsqueeze(-1)out[rows] += w * expert(x[rows])return out
3. Long Context and Caching: When It Pays Off
Agents need to store system settings, operating preferences, and past sessions, so they require long context windows. Many current models support windows of 256K tokens or more. However, as context grows, recomputing the KV Cache for the prefix on every request adds noticeable compute and time costs.
Prefix caching works as follows. Compute the fixed parts of the prefix, such as the system prompt, tool definitions, and long-term memory, once, and save their KV Cache. When a later request starts with an identical prefix, reuse the saved result and compute only the new portion.
Caching delivers clear savings only when all of the following conditions hold:
- The prefix is stable. The opening content of every request must be byte-for-byte identical. If you place timestamps or random IDs in the prefix, the cache will be invalidated frequently.
- The hit rate is high. If each session uses a different system prompt, the cache will rarely hit.
- The billing rules give a discount for cached tokens or price them separately.
- The interval between two requests falls within the cache retention period.
The table below lists the expected benefit for three common scenarios.
| Scenario | Prefix Stable? | Expected Benefit |
|---|---|---|
| Fixed system prompt plus tool definitions | Yes | High |
| Current time added to every request | No | Low. Moving the time after the prefix can improve this. |
| Shared template across multiple users | Yes, but must be isolated per user | Depends on the isolation granularity |
You can estimate the cost of a single request with this formula:
Cost per request = uncached input tokens × input price + cached input tokens × cache price + output tokens × output price
The formula does not produce a fixed savings multiplier. The actual savings depend on context length, hit rate, and the vendor’s specific pricing. Calculate them from your own call logs.
4. Measure Instead of Relying on Promotional Figures
Evaluate your setup with these steps:
- Record, for each call, the input tokens, cached tokens, output tokens, TTFT, and total duration.
- Replay real agent task traces instead of testing only single question-and-answer pairs.
- Group results by cache hit rate, and compare cost and latency within each group.
- Compare task completion rates for the same tasks across different models or configurations. A lower unit price does not necessarily mean lower total cost if the task failure rate is higher.
Billing rules are defined by the vendor’s official documentation. Prices can change, so update your calculations regularly.
5. Engineering Checklist for the Cloud Backend of an Agent
After you choose a model, the backend system also affects stability. Check the following areas:
- Local gateway: Scale elastically with load. Distinguish network timeouts from model timeouts, and configure a sensible reconnection policy.
- Asynchronous tasks: Put long-running tasks into a message queue. Set retry limits and idempotency keys so that write operations are not executed twice.
- Logging and redaction: Record token usage and latency. Redact terminal commands, file contents, and user data before storing them.
- Alerting: Set thresholds for TTFT, error rate, and cache hit rate, and notify the team promptly when a threshold is crossed.
- Cost control: Set budget caps per project or per user to prevent abnormal calls from causing excess charges.
- Permissions: An agent that can run local commands should follow the principle of least privilege. Limit the directories and commands it can access.
6. Conclusion
MoE lowers compute per call through sparse activation. Prefix caching lowers input costs by reusing repeated prefixes. The benefits of both techniques depend on specific conditions, including model architecture, context stability, hit rate, and billing terms.
When selecting a model, first define your latency targets and cost budget, then estimate outcomes using real task traces. Treat claims of near-zero cost as hypotheses to verify against your own logs rather than as established facts.
