MoE and Context Caching: Conditions and Limitations for Reducing AI Agent Costs

    When selecting cloud models for AI agents, developers often face slow response times and high costs from repeatedly sending large contexts. Mixture of Experts (MoE) architectures and context caching are common solutions, but their effectiveness depends on the model, deployment, and request patterns. This article explains the conditions under which each approach is beneficial, highlights areas where they are often overestimated, and provides practical gateway-level implementation steps with reference code.

    If you are choosing a cloud model for an AI agent, you likely face two issues: slow responses and rapidly increasing bills due to repeatedly passing large amounts of context with each request. MoE (Mixture of Experts) architecture and context caching are two common industry approaches to tackle this. While they are effective, their actual impact depends on the model, deployment method, and request patterns. This article explains the conditions under which they are useful, where they might be overestimated, and provides gateway-level implementation steps with reference code.

    1. Why AI Agents are Slow and Expensive

    Common agent architecture consists of two layers. The local gateway receives user actions, such as terminal commands and file read/writes, and packages the relevant context to send to the cloud model. The cloud model is responsible for understanding intent, decomposing tasks, and returning execution instructions.

    This division of labor brings two types of pressure. The first is Time To First Token (TTFT), which is the time from sending a request to the model outputting the first token. While the gateway waits for the first token, users will perceive UI lag. The second is Token consumption for repeated prefixes. System settings, history summaries, and user preferences are usually placed at the beginning of each request. As tasks grow longer, this prefix grows larger, requiring payment and recalculation for every request.

    These two issues need separate handling. MoE architecture primarily affects computation volume, while context caching mainly affects the cost of processing repeated prefixes. Neither replaces the need to optimize the gateway’s calling method itself.

    2. The Impact of MoE Architecture on TTFT

    MoE splits a large model into multiple expert subnetworks. A gating network selects a few experts to participate in the computation for each token based on the input. The total parameters of the model might be huge, but each forward pass only activates a portion, known as the active parameters.

    Fewer active parameters mean less computation per token. During the Prefill phase, the model must process all input tokens at once; less computation presents an opportunity to shorten wait times. This is the main effect of MoE on TTFT.

    However, MoE does not automatically guarantee low latency. The following factors also determine TTFT:

    • Expert parallelism communication overhead: When experts are distributed across multiple cards or machines, tokens need to be routed between nodes, and communication might offset the time saved in computation.
    • Batching and queuing: If the server merges requests into larger batches for throughput, a single request might have to wait, increasing TTFT instead.
    • Memory bandwidth: Prefill for long contexts reads and writes large amounts of KV Cache; memory bandwidth can become a bottleneck before compute power does.
    • Network path: The network round-trip time between the gateway and the model service accounts for a significant portion in scenarios where agents frequently send small requests.

    Therefore, when evaluating TTFT, you must fix testing conditions, including input length, concurrency, whether caching is enabled, region, and network path. Providing only an average value is unhelpful; it is recommended to record P50 and P95 simultaneously.

    The table below can serve as a reference during selection. The content in the table should be based on the official model cards and service provider documentation of each model and should not be applied blindly.

    Comparison Dimension Dense Model MoE Model Questions to Confirm
    Total Parameter Size All participate in computation Total parameters are large, only a portion is activated per call Whether the provider officially discloses total and active parameters
    Per-Token Computation Volume Correlates with parameter count Correlates with active parameter count Throughput data on the same hardware
    Time To First Token (TTFT) Grows with input length and model size Computation drops, but affected by communication and queuing Concurrency and input length during testing
    Context Window Depends on the model Depends on the model, some support 256K level Whether it is the nominal value, what is the actual usable length
    Context Caching Depends on the provider Depends on the provider Hit conditions, TTL, and billing method

    3. Context Caching: When It Actually Saves Money

    The principle of context caching is: when processing input, the model generates a KV Cache (Key-Value Cache). If the beginning of subsequent requests is exactly the same as before, the server can directly reuse this part of the cache, skipping redundant computation. For agents, system settings and user profiles are usually stable, making them ideal cache prefixes.

    Whether the cache hits depends on the following conditions:

    1. The prefix is byte-for-byte identical. Any single character difference, such as adding a timestamp or request ID, invalidates the cache.
    2. Stable content first, dynamic content later. The user’s current input should be placed at the end.
    3. The model name and deployment version remain unchanged. After a model upgrade, old caches are usually unavailable.
    4. The request occurs within the cache’s validity period. The TTL (Time To Live) is defined by the service provider, commonly ranging from minutes to hours; refer to the provider’s documentation.
    5. Requests from the same user or session appear consecutively. If the interval is too long, the cache has likely expired.

    Costs must also be calculated comprehensively. Caching saves the computation and partial input costs of repeated prefixes, but there are usually additional expenses: the cost of writing to the cache for the first time (if charged separately by the provider), the duration fee for cache storage (if billed by time), and the portion billed as normal input if a cache miss occurs. You can use the following rough formula to estimate the cost of a single session:

    Single Cost ≈ Hit Tokens × Hit Unit Price + Missed Tokens × Normal Unit Price + Written Tokens × Write Unit Price + Storage Duration × Storage Unit Price

    The lower the hit rate, the smaller the benefit from caching. In scenarios with short sessions or low-frequency calls, the overhead of cache writing and storage might exceed the benefits. Before going live, use real traffic logs to estimate the hit rate before deciding whether to enable it.

    Conclusion: In scenarios with stable prefixes, continuous sessions, and frequent calls, caching can significantly reduce the overhead of repeated prefixes. It does not make long-term memory free, nor is it suitable for scenarios where prefixes change frequently.

    4. Implementation Steps for Enterprise Gateways

    The goal of the gateway is to keep prefixes stable, make hit situations observable, and make failures recoverable. The following steps are recommended.

    1. Deploy the gateway. The gateway can run on container services from mainstream cloud providers or in a self-hosted Kubernetes cluster. When choosing, focus on three points: the ability to scale on demand, integration with unified logging and monitoring, and whether the network latency between the gateway and the model service is controllable.
    2. Asynchronize non-real-time tasks. Tasks like log writing, session summary updates, and memory compression should be placed in message queues for asynchronous execution to avoid blocking user requests.
    3. Organize request structure. Place the System Prompt and user profile at the very beginning and ensure the serialization result is stable, such as fixed field order and no random values.
    4. Manage cache versions. Calculate a hash of the prefix content as a version number. When user preferences or system settings change, the hash changes, and the old cache no longer hits. Manual cleanup is unnecessary; old caches will expire after the TTL.
    5. Record hit situations. Read fields like input tokens and cached hit tokens from the usage information returned by the server, and calculate the hit rate by version number. Field names vary by provider and need to be mapped according to the documentation.

    Below is reference code for a gateway call. It does four things: reads the API key from environment variables, sets a timeout with limited retries, uses a prefix hash for version tagging, and avoids logging the full prompt and key in the logs. The code requires Python 3.10 or above. The request fields (such as enable_cache, metadata) are examples and need to be replaced with the actual fields of the service provider you are using.

    1. import hashlib
    2. import logging
    3. import os
    4. import time
    5. import requests
    6. API_URL = os.environ.get("LLM_API_URL", "https://api.example.com/v1/chat/completions")
    7. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variables, do not hardcode or commit
    8. MODEL = os.environ.get("LLM_MODEL", "your-moe-model")
    9. TIMEOUT_SECONDS = 10
    10. MAX_RETRIES = 3
    11. RETRYABLE_STATUS = {429, 500, 502, 503}
    12. logger = logging.getLogger("agent_gateway")
    13. def mask_secret(value: str) -> str:
    14. """Keep only the last 4 characters to identify the key in logs."""
    15. return "***" + value[-4:] if len(value) > 4 else "***"
    16. def build_prefix(system_prompt: str, user_profile: str) -> str:
    17. """Place stable content at the front to ensure the prefix is byte-for-byte identical."""
    18. return f"{system_prompt}\n{user_profile}"
    19. def prefix_version(prefix: str) -> str:
    20. """When prefix content changes, the version number changes, invalidating the old cache."""
    21. return hashlib.sha256(prefix.encode("utf-8")).hexdigest()[:12]
    22. def call_cloud_brain(system_prompt: str, user_profile: str,
    23. user_input: str, request_id: str) -> str | None:
    24. prefix = build_prefix(system_prompt, user_profile)
    25. version = prefix_version(prefix)
    26. payload = {
    27. "model": MODEL,
    28. "messages": [
    29. {"role": "system", "content": prefix},
    30. {"role": "user", "content": user_input}, # Dynamic content at the end
    31. ],
    32. "enable_cache": True, # Example field, refer to provider docs
    33. "max_tokens": 1024,
    34. "metadata": {"prefix_version": version}, # Example field
    35. }
    36. headers = {
    37. "Content-Type": "application/json",
    38. "Authorization": f"Bearer {API_KEY}",
    39. }
    40. for attempt in range(1, MAX_RETRIES + 1):
    41. try:
    42. resp = requests.post(API_URL, json=payload,
    43. headers=headers, timeout=TIMEOUT_SECONDS)
    44. except requests.RequestException as exc:
    45. logger.warning("request_id=%s attempt=%d network error: %s",
    46. request_id, attempt, type(exc).__name__)
    47. time.sleep(2 ** attempt)
    48. continue
    49. if resp.status_code == 200:
    50. data = resp.json()
    51. # Log usage and version for cache hit rate statistics; do not log original prompt
    52. logger.info("request_id=%s prefix_version=%s usage=%s",
    53. request_id, version, data.get("usage"))
    54. return data["choices"][0]["message"]["content"]
    55. if resp.status_code in RETRYABLE_STATUS:
    56. logger.warning("request_id=%s attempt=%d status=%d, retrying",
    57. request_id, attempt, resp.status_code)
    58. time.sleep(2 ** attempt)
    59. continue
    60. logger.error("request_id=%s rejected status=%d key=%s",
    61. request_id, resp.status_code, mask_secret(API_KEY))
    62. return None
    63. logger.error("request_id=%s failed after %d attempts", request_id, MAX_RETRIES)
    64. return None

    5. Common Mistakes and Troubleshooting Checklist

    In practice, a zero cache hit rate is the most common issue. You can troubleshoot in the following order:

    • The prefix contains timestamps, random IDs, or the current date. The solution is to move this content to the user message.
    • The concatenation order of the user profile is not fixed. Ensure fixed field order during serialization and sort lists.
    • The model name or version number is inconsistent between requests, such as using both an alias and a specific version number.
    • The interval between two requests exceeds the TTL. You can adjust the session retention strategy or accept the cost of a miss.
    • Only counting requests instead of cached hit tokens. This should be based on the usage fields returned by the server.
    • Only looking at average TTFT while ignoring tail latency. P95 better reflects the lag perceived by users.

    When checking costs, also include write fees and storage fees. If the hit rate for a certain type of session remains below the break-even point for a long time, caching for that session type should be disabled.

    6. Conclusion

    MoE architecture can reduce the computation volume per token, offering an opportunity to improve TTFT, but communication, queuing, and memory bandwidth will offset some of these gains. Context caching can significantly reduce the repeated overhead of stable prefixes, provided the prefix is stable, the session is continuous, and the hit situation is observable. For enterprise teams, the safer approach is to first measure TTFT and cache hit rate with real traffic before deciding on the model and caching strategy.