Cost Reduction for Open-Source LLMs: Implementing Routing and Caching Strategies

    As enterprises increasingly adopt Large Language Models (LLMs), managing rising API costs becomes a critical challenge. This article explores a combined strategy for reducing LLM inference costs: setting open-source models as the default, implementing intelligent routing, and applying cache reuse. It details best practices for model selection, routing logic, semantic and prefix caching, cloud-native deployment, and provides a practical checklist for gradually implementing these cost-saving measures without compromising business quality.

    The longer an enterprise integrates Large Language Models (LLMs), the more likely it is to face a common issue: API call volumes are rising, and the bills are growing even faster. Scenarios like intelligent customer service, knowledge base Q&A, and code assistance generate massive amounts of tokens daily. If the default model is on the expensive side, costs scale directly with business growth.

    There is no one-click solution for cost reduction. A combination of setting an open-source model as the default, adding a smart routing layer, and leveraging cache reuse is typically required to see significant results. Using any of these in isolation often yields limited savings. The actual reduction depends on routing hit rates, cache hit rates, and price differences between models. Results vary across enterprises, so published figures cannot be directly applied.

    1. Setting Open-Source Models as the Default

    Teams often rely on closed-source commercial APIs during the validation phase for quick integration and stable performance. However, as business volume grows, token-based billing makes costs unpredictable. Setting an open-source model as the default for engineers and business systems controls the unit price from the source.

    When selecting models, compare the following dimensions rather than just looking at leaderboard scores:

    • License: Whether commercial use, private deployment, and secondary training are allowed.
    • Context length: Whether long document Q&A requires a larger window.
    • Capability: Validate Chinese language tasks, coding tasks, and tool calling using your own evaluation sets.
    • Quantization loss: How much accuracy drops after quantization and whether it affects key businesses.
    • Versioning strategy: Whether outputs change after model upgrades and whether regression testing is needed.

    Deployment methods also affect costs. Private deployment converts usage-based fees into fixed hardware and O&M investments, which is more cost-effective when request volume is stable and high. If request volume is low or highly volatile, using third-party inference services might be cheaper. Private deployment is not zero-cost; GPU utilization, hardware depreciation, and O&M labor must be factored into the total cost.

    2. Directing Requests with Smart Routing

    Even after replacing the default model, many requests still go to LLMs, and a significant portion of them are not complex. A routing gateway directs requests based on characteristics: simple tasks go to lightweight models, while complex tasks go to larger parameter models.

    Common routing criteria include task type, context length, and current load. Below is a sample code illustrating the concept; it is not for production use:

    1. # Sample code: illustrates routing logic only. Add timeout, fallback, and monitoring before production.
    2. class ModelRouter:
    3. def __init__(self):
    4. self.light_model = "light-open-source-model"
    5. self.heavy_model = "heavy-open-source-model"
    6. self.complex_keywords = ["重构", "架构设计", "全量测试"]
    7. def route_request(self, prompt: str, context_length: int) -> str:
    8. if context_length < 2000 and not self._is_complex_task(prompt):
    9. return self.light_model
    10. return self.heavy_model
    11. def _is_complex_task(self, prompt: str) -> bool:
    12. # Keyword rules have a high misjudgment rate. Use an evaluated classification model in practice.
    13. return any(kw in prompt for kw in self.complex_keywords)

    Keyword rules are only a starting point. They might misjudge “briefly explain the architecture design document” as a complex task, or miss difficult questions without keywords. Before going live, at least the following must be addressed:

    • Fallback for classifier errors: When the lightweight model outputs low confidence, automatically upgrade to the large model for a retry.
    • Set timeout and retry limits: Timeout retries consume extra tokens; limit the number of attempts.
    • Set a per-request cost ceiling: Requests exceeding the limit enter a manual or asynchronous processing flow.
    • Canary release: Affect a small portion of traffic first, compare quality and cost metrics, then switch entirely.
    • Monitor key metrics: Routing ratio, upgrade ratio, average cost per request, and user dissatisfaction rate.

    When a node queue is too long, the gateway should route new requests to idle nodes based on health checks and response latency, reducing duplicate calls caused by timeouts.

    3. Reducing Redundant Computation with Caching

    R&D Q&A and internal knowledge bases contain many repetitive or similar requests. Caching is a common method to reduce this waste, operating on two levels with different use cases and risks.

    The first level is Prompt prefix reuse, or KV Cache. Enterprise System Prompts are usually long, containing coding standards, tech stack requirements, etc. For prefixes within the same session or task type, the inference engine can cache intermediate results, so subsequent requests only need to compute the new parts. This primarily reduces the computation and latency of repeated prefixes. Whether it reduces the token bill depends on whether the service provider charges less for cached prefixes. If unsupported, prefix caching only improves performance, not cost.

    The second level is semantic caching. Exact matches have very low hit rates. Semantic caching identifies similar intents via vectorization. The flow is:

    • Ingestion: After the model returns a result, store the Prompt vector along with the Response in a vector database.
    • Query: When a new request arrives, vectorize it and retrieve historical records exceeding the similarity threshold. If hit, return the cached result directly without calling the model.

    Below is a sample code for the query logic:

    1. # Sample code: Semantic cache query. Threshold requires A/B testing for tuning.
    2. class SemanticCache:
    3. def __init__(self, vector_db_client, threshold=0.95):
    4. self.db = vector_db_client
    5. self.threshold = threshold
    6. def get_cached_response(self, prompt: str, tenant_id: str, model_version: str):
    7. embedding = self._embed(prompt)
    8. # Cache key includes tenant and model version to prevent cross-permission or cross-version usage.
    9. hits = self.db.search(embedding, top_k=1,
    10. filter={"tenant_id": tenant_id,
    11. "model_version": model_version})
    12. if hits and hits[0].score >= self.threshold:
    13. return hits[0].response
    14. return None # No hit, call the actual LLM

    The risks of semantic caching require more attention than performance issues:

    • Permission isolation: Caches must be isolated by user, department, or tenant to prevent one person’s historical answers from being seen by another.
    • Sensitive data: Requests containing personal information or keys should not be cached, or should be encrypted with strict access controls.
    • Expiration policy: Set a TTL for caches. After coding standards or API docs are updated, proactively invalidate related entries.
    • False hits: Similar but distinct questions might be misjudged as the same. Regular sampling checks are needed.
    • Threshold tuning: 0.95 is just a common starting point. Different business domains should use different thresholds determined through A/B testing.

    It is recommended to continuously monitor cache hit rates, false hit rates, and manual correction counts. Looking only at hit rates can mistakenly classify “many hits but many wrong answers” as a success.

    4. Cloud-Native Architecture Implementation

    To stably run the routing and caching mechanisms above, a scalable, highly available infrastructure is needed. Container platforms, object storage, message queues, and monitoring/alerting services provided by mainstream cloud providers can support this architecture.

    A viable combination is:

    1. Use a container platform to orchestrate inference services, routing gateways, and cache services, with auto-scaling based on queue length or GPU utilization.
    2. Use object storage to save model weights and historical logs, setting retention periods according to compliance.
    3. Use message queues to handle asynchronous tasks, shaving off traffic peaks and preventing sudden requests from crashing inference nodes.
    4. Configure monitoring and alerting to track token consumption rate, API success rate, and unit cost of each model in real-time.

    The premise of this solution is: the open-source model quality meets business requirements, the cache hit rate is high enough, routing misjudgments are controllable, and compliance policies allow data into the respective inference environments. If any premise fails, the plan must be adjusted. For example, if data residency requirements prevent data from leaving the country, private deployment should be chosen, and some third-party services should be abandoned.

    5. Implementation Checklist

    Before a full rollout, follow this sequence:

    1. Analyze existing token usage and split costs by team and application to identify the most expensive call chains.
    2. Select two or three open-source models and compare quality and unit price on your own evaluation set.
    3. Launch routing first with a small amount of canary traffic, recording quality and cost changes.
    4. Start caching in low-risk scenarios, such as public document Q&A, and expand after confirming permission and expiration mechanisms are reliable.
    5. Establish a monthly review to compare metrics and decide whether to adjust thresholds or switch models.

    Following this sequence allows the team to verify benefits at each step rather than replacing the entire system at once. The goal of cost reduction is to ensure every token is spent on valuable requests, not just lowering the unit price.