A Practical Guide to LLM Service Migration: Building a Switchable Architecture

    This article provides a practical guide for engineering teams looking to migrate between large language model (LLM) services without being locked into a single vendor. It outlines a structured approach to decoupling business code from provider-specific APIs, prompt formats, and output parsing logic. Key topics include evaluating migration readiness, designing a unified adapter layer, managing prompts as versioned assets, establishing evaluation benchmarks, and rolling out new models through shadow traffic and canary releases. The guide also covers cost management, security considerations, and a step-by-step migration checklist to minimize risk and ensure a smooth transition.

    Why You Need Room for Migration

    When a team integrates a specific model service, the integration often involves writing the calling method, prompt format, and output parsing logic directly into the business logic. This approach creates tight coupling. Once the service provider adjusts pricing, experiences downtime, tightens regional restrictions, or changes model capabilities, the cost of switching to a different provider grows quickly.

    The goal of migration is not simply to replace one vendor, but to decouple your business code from the specifics of any single vendor. Achieving this decoupling allows your team to select models freely based on quality, cost, and compliance requirements.

    Common coupling issues fall into several categories:

    • Protocol Coupling: The request body structure, streaming response format, and tool-calling fields are hardcoded in the business layer, requiring changes at every call site when switching.
    • Prompt-Model Binding: The same instruction can yield vastly different results on different models, yet prompts often lack version history, making it hard to trace why output quality changed.
    • Output Format Dependency: The business logic assumes the model will return structured content as promised, with no fallback logic if parsing fails.
    • Missing Evaluation: Without a unified test set, teams rely on subjective impressions to judge whether a new model is usable.
    • Scattered API Keys: Access credentials are scattered across multiple repositories and config files, making rotation and revocation difficult.

    Pre-Migration Assessment

    Before making any code changes, conduct four assessments to determine the scope and pace of migration.

    1. Inventory the call sites. Identify all the places in the codebase that invoke the model, the call frequency, the average input/output length, and the failure-handling mechanism at each point. The inventory should be compiled into a list for step-by-step tracking.

    2. Categorize task types. Code completion, code review, documentation generation, and Q&A retrieval impose different requirements on model capabilities. A new service may excel at one task type while failing on another. Evaluating performance per task type provides better insights than a single overall score.

    3. Build a benchmark set. Sample from historical production requests, covering three categories: normal samples, edge samples (e.g., very long inputs, empty inputs, ambiguous instructions), and failure samples (requests that previously caused errors). Save the human-approved ideal output or scoring criteria for each sample. The benchmark set is the foundation for all future comparisons and must be continuously updated as business needs evolve.

    4. Define acceptance metrics. Common metrics to track include:

    • Structured Output Pass Rate: The percentage of outputs that can be parsed correctly.
    • Task Accuracy Rate: Judged either by human review or automated rules.
    • Response Latency: Pay special attention to the 95th percentile.
    • Unit Task Cost: The average cost to complete a single task, typically token-based and directly tied to the pricing of the chosen provider.
    • Failure Retry Rate and Timeout Rate.

    The thresholds for these metrics should be set by the team based on business tolerance, not copied from other teams.

    Architecture Design: Introduce a Unified Adapter Layer

    The recommended design is to introduce an adapter layer between the business code and the model service. The business layer only depends on an internal interface. The adapter layer is responsible for translating internal requests into the specific provider’s protocol and for normalizing the responses back into a unified internal structure. This way, switching providers only requires adding or modifying an adapter, leaving the business code unchanged.

    Below is an illustrative implementation to show the structure:

    1. from dataclasses import dataclass
    2. from typing import Protocol
    3. @dataclass
    4. class ChatRequest:
    5. system: str
    6. messages: list
    7. max_tokens: int = 1024
    8. temperature: float = 0.2
    9. @dataclass
    10. class ChatResult:
    11. text: str
    12. input_tokens: int
    13. output_tokens: int
    14. provider: str
    15. class ChatProvider(Protocol):
    16. name: str
    17. def complete(self, req: ChatRequest) -> ChatResult: ...
    18. class ModelRouter:
    19. def __init__(self, providers, primary, fallback=None):
    20. self.providers = providers # mapping of provider name to adapter instance
    21. self.primary = primary
    22. self.fallback = fallback
    23. def complete(self, req: ChatRequest) -> ChatResult:
    24. try:
    25. return self.providers[self.primary].complete(req)
    26. except Exception:
    27. # In production, log the exception type and request ID for troubleshooting
    28. if self.fallback is None:
    29. raise
    30. return self.providers[self.fallback].complete(req)

    Key design principles:

    • Adapters only handle protocol conversion, containing no business logic, which makes them easy to test in isolation.
    • API keys are injected via environment variables or a secret management service. Adapters should never hardcode credentials.
    • The unified internal structure includes the provider identifier, making it easy to track the performance of different services in logs and metrics.
    • Routing logic is independent of the adapters. Primary/fallback switching, canary traffic ratios, and circuit-breaking strategies are all implemented in the routing layer.

    Prompt Governance

    Prompts are one of the most overlooked aspects of migration. A single prompt can produce very different results on different models, so prompts must be managed as engineering assets.

    • Version-controlled storage: Store prompts as template files in the code repository. Every change has a commit record and version number.
    • Separate variables from instructions: Keep fixed instructions in the template and inject business data as parameters, avoiding string concatenation in the code.
    • Enforce structured output: Require the model to return content in a fixed structure and validate the output strictly on the parsing side.

    Here is an example of validation for structured output:

    1. import json
    2. REQUIRED_FIELDS = {"issues", "severity"}
    3. def parse_review(raw_text):
    4. try:
    5. data = json.loads(raw_text)
    6. except json.JSONDecodeError:
    7. return {"ok": False, "error": "invalid_json"}
    8. if not isinstance(data, dict):
    9. return {"ok": False, "error": "not_an_object"}
    10. if not REQUIRED_FIELDS.issubset(data.keys()):
    11. return {"ok": False, "error": "missing_fields"}
    12. return {"ok": True, "data": data}

    On validation failure, the system can initiate a single retry with the format instructions included in the request. If repeated attempts fail, the system should route the request to a manual handling or degraded fallback process. All failures should be reported as metrics for evaluating model stability.

    Evaluation and Canary Release

    Switching services should be done in phases, with clear pass and rollback criteria at each stage.

    Phase 1: Offline Evaluation. Run the old and new services against the same benchmark set and compare the acceptance metrics item by item. This phase does not involve live users, keeping the cost low while catching obvious capability gaps.

    Phase 2: Shadow Traffic. Send a copy of production traffic to the new service but do not return the output to users. This approach helps identify issues that only surface under real traffic distribution, such as inputs in specific languages, very long contexts, or unusual characters.

    Phase 3: Canary Deployment. Enable a small percentage of real traffic to the new model, for example starting at 5% and gradually increasing to 20%, 50%, and 100%. Monitor structured output pass rate, latency, and failure rate at each step. If any metric breaches its threshold, roll back the traffic automatically.

    Traffic switching is done via configuration, not via a new deployment. A sample configuration might look like this:

    1. routing:
    2. primary: provider_b
    3. fallback: provider_a
    4. canary_ratio: 0.1
    5. rollback_on:
    6. json_error_rate: 0.05
    7. p95_latency_ms: 8000

    The thresholds above are examples only; actual values should be set based on historical baselines and business requirements. Keeping a fast rollback capability to the previous configuration is the most important safety net during your migration.

    Cost and Quota Management

    Model invocation costs are directly related to the number of input and output tokens. The migration should also include cost optimization.

    • Use tiered models for different tasks: Use lightweight models for simple tasks like format conversion and classification. Reserve higher-capability models for tasks requiring complex reasoning.
    • Set output token limits: Configure appropriate maximum output lengths per task type to avoid wastage on irrelevant long-form text.
    • Cache reusable results: For identical, repeated requests (like summarization of the same file), return a cached result.
    • Track usage and attribute costs: Record input tokens, output tokens, and the associated business line for every call. Generate weekly or monthly usage reports.
    • Set budget alerts: Establish quota thresholds per project or team and notify the responsible person when exceeded.

    Security and Compliance

    Model services introduce concerns around data leaving the infrastructure, privacy protection, and API key management. These must be addressed during the migration.

    • API key management: Store credentials only in environment variables or a dedicated secret management service. Never write them into code repositories, config templates, or logs. Rotate keys regularly and provision separate credentials for each service.
    • Data masking: Redact personal information, internal secrets, and customer data before sending it to external services. Implement masking rules centrally in the adapter layer to avoid every business team handling this separately.
    • Data retention: Clarify the provider’s data retention policy and whether they use submitted data for training. Verify these terms against your contract or the service agreement.
    • Access audit: Record who called which service and when, to facilitate operational review and troubleshooting.

    Migration Checklist

    1. Complete a call-site inventory, build a benchmark set, and define acceptance metrics.
    2. Introduce an adapter layer while keeping the business interfaces unchanged.
    3. Wrap the existing service as the first adapter and verify the behavior is identical to the previous direct integration.
    4. Integrate the second service and run offline evaluations.
    5. Enable shadow traffic, analyze the differences, and adjust the adapter logic and prompts as needed.
    6. Roll out the canary deployment according to a pre-defined ratio, monitor the metrics, and set up automatic rollback.
    7. After full migration, keep the old adapter for a reasonable period to ensure stability before cleaning it up.

    Keep records for each step, including evaluation data, configuration changes, and rollback events. These records will serve as a reference for future migrations.

    Common Pitfalls

    • Assuming migration is just a config change: In practice, most issues stem from prompts, output parsing, and error handling. Configuration changes are merely the final step.
    • Judging quality by a few samples: A few impressive examples are not proof of long-term stability. Rely on the overall pass rate on the benchmark set and the production error rate.
    • Over-optimizing for uniformity: Different tasks have very different requirements for model capabilities. A unified adapter layer should still allow configuring different services and parameters per task.
    • Ignoring the rollback path: If you cannot revert the traffic to the old service within minutes, the canary plan is practically useless.

    The ability to migrate is an engineering asset in itself. Once the team has built the adapter layer, the benchmark set, and the canary rollout mechanism, introducing new models or adjusting the supply structure can be done reliably with predictable cost and risk.