Legacy LLM API Retirement: How to Migrate Safely to a New Model
This article provides a practical migration workflow for backend and algorithm engineers who maintain LLM API integrations. It covers confirming retirement status, inventorying all callers, running empirical model selection, updating code and prompts, hardening output parsing, executing a rollout checklist, and managing canary releases and rollback.
Scope and Prerequisites
This article is intended for backend engineers and algorithm engineers who maintain LLM API integrations. Before you begin, you need the following permissions: read access to call logs, the configuration center, and code repositories; change permission for the configuration center (subject to an approval process); and permission to execute rollback operations. You also need the platform’s official documentation and retirement notice.
The model names, API endpoints, request paths, parameter fields, and prices in this article are all subject to each platform’s official documentation. This article does not provide specific prices or promise performance data for any model. Code examples illustrate structure only and must be adapted to your own configuration before use.
1. Confirm Retirement Status and Inventory Callers
1.1 Verify Notice Dates
Retirement notices usually provide a specific date. Record the retirement time, affected model names, and recommended replacement models from the notice. If the date has not yet arrived, you can start with inventory and model selection. If the date has passed, prioritize inventory and switchover.
1.2 Test the Legacy Model with a Minimal Request
Use a very short request to confirm whether the legacy model name is still callable. Put only a few characters in the input and set a small output limit to avoid unnecessary costs. Read the endpoint and key from environment variables; do not write them into code or logs.
import osimport requestsBASE_URL = os.environ["LLM_API_BASE_URL"] # Platform API base URL; refer to official documentationAPI_KEY = os.environ["LLM_API_KEY"] # Injected by the secret management service; do not hardcodeMODEL_NAME = os.environ["LLM_MODEL_NAME"] # Model name to test, e.g., the legacy model namedef ping_model(timeout: float = 10.0) -> None:url = f"{BASE_URL.rstrip('/')}/chat/completions" # Request path; refer to official documentationheaders = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}payload = {"model": MODEL_NAME,"messages": [{"role": "user", "content": "ping"}],"max_tokens": 8,}resp = requests.post(url, headers=headers, json=payload, timeout=timeout)print("status:", resp.status_code)resp.raise_for_status()if __name__ == "__main__":ping_model()
Key run points:
- Always set an explicit timeout; the example uses 10 seconds. Requests without a timeout may hang for a long time.
max_tokenslimits output length and reduces test cost.- Log only the status code, not request headers, to avoid leaking secrets.
- If the response returns a model-not-found or unavailable error, the legacy model is no longer callable, and you should move directly to the switchover process.
- If transient network errors are common, add up to two retries at the outer layer with a backoff interval. Do not set too many retries; otherwise, failures can be amplified.
1.3 Inventory All Callers
Legacy model names and API endpoints may be scattered across code, configuration, and environment variables. Use the following commands to search the code repository. Replace OLD_MODEL_NAME and OLD_BASE_URL with the actual values:
grep -rn "OLD_MODEL_NAME" --include="*.py" --include="*.yaml" --include="*.yml" --include="*.json" --include="*.env" .grep -rn "OLD_BASE_URL" --include="*.py" --include="*.yaml" --include="*.yml" --include="*.json" --include="*.env" .
You also need to check three places outside the code:
- Configuration center: Search for the legacy model name and confirm the values in each environment (development, staging, production).
- Call logs: Count request volume by model field over a recent period to identify real callers. The log retention period determines the time range you can trace. If retention is too short, record the current baseline in the logging platform.
- Scheduled jobs and offline scripts: These calls are easy to miss and must be checked separately.
Organize the search results into a caller inventory. Each caller should have at least one row:
| Service name | Repository and path | Legacy model name | Configuration location | Owner | Average daily requests | Peak QPS | Rollback switch | Migration status |
|---|---|---|---|---|---|---|---|---|
| Example: customer support summarization service | repo-a / services/summary | Legacy model name | Config center summary.yaml | Alice | TBD | TBD | Yes / No | Not started |
The inventory must meet three requirements: every caller has a clear owner, every caller has a rollback switch, and every caller’s baseline metrics are recorded. For services without a rollback switch, add the switch before starting the switchover.
2. Empirical Model Selection
2.1 Build an Evaluation Set
The evaluation set must come from your own real business data. Extract historical requests from logs and cover common inputs, edge-case inputs, and historical error samples. Data must be anonymized and handled according to data usage rules. The number of samples depends on business complexity; this article does not prescribe a fixed number.
2.2 Comparison Metrics
Measure the following metrics for the old and new models (if the old model is still available) or for alternative new models, using the same samples and the same network environment:
| Metric | Measurement method | Notes |
|---|---|---|
| Latency | Measure P50 and P95 | Test the same samples in the same time window to avoid network fluctuation interference |
| Error rate | Count HTTP errors and business parsing failures separately | The two error types have different causes and should be reviewed separately |
| Output stability | Call the same input multiple times and compare consistency of structured fields | Especially important for services that depend on JSON output |
| Cost basis | Use measured token counts and convert according to official pricing rules | Prices are subject to the official page; document the conversion basis |
| Business evaluation set pass rate | Judge each evaluation sample as pass or fail | Define pass criteria in advance and have the business team confirm them |
Record the test conditions during measurement: date, region, concurrency, input length distribution, output limit, and temperature. Data without recorded conditions cannot be reproduced or used for decision-making.
2.3 Set Pass Criteria
Set pass criteria before testing and do not adjust them after seeing the results. Criteria may include: the business evaluation set pass rate is no lower than baseline, structured output consistency meets business requirements, and P95 latency is within an acceptable range. The team should determine specific values based on the baseline and business requirements.
3. Update Code and Prompts
3.1 Make the Model Name Configurable
Do not hardcode model names in code. Put the model name, API endpoint, and timeout parameters into configuration, and support per-environment or per-service switching:
import osMODEL_CONFIG = {"model_name": os.environ.get("LLM_MODEL_NAME", ""),"timeout_seconds": float(os.environ.get("LLM_TIMEOUT_SECONDS", "30")),"max_output_tokens": int(os.environ.get("LLM_MAX_OUTPUT_TOKENS", "1024")),}if not MODEL_CONFIG["model_name"]:raise RuntimeError("LLM_MODEL_NAME is not configured; refusing to start the service")
The benefit is that model switching only requires a configuration change, not a code release. Rollback also only requires changing the configuration back.
3.2 Prompt Regression
The same prompt may behave quite differently on different models. During the migration, check the following:
- Are instructions clear, or do they rely on some implicit behavior of the legacy model?
- Are output format constraints explicit, such as JSON field names, required fields, and value ranges?
- Is the boundary between the system prompt and user input clear?
- Are the example samples still applicable?
After every prompt change, rerun it against the evaluation set and record the version number.
3.3 Harden Output Parsing
New model output may differ slightly in format. The parsing layer should:
- Validate structure before using fields.
- On parsing failure, log a summary of the raw output, not the full sensitive content.
- Have a degradation strategy on parsing failure, such as returning a default value or moving the request to a manual queue.
4. Execution Checklist
Confirm the following items before migration, and proceed to canary only after all are complete:
- Confirm the retirement date and recommended replacement model in the notice
- Test whether the legacy model name is still callable with a minimal request and record the result
- List all callers, including code, configuration center, scheduled jobs, and offline scripts
- Assign an owner, rollback switch, and migration status to each caller
- Record legacy model baseline metrics: error rate, latency, and business evaluation pass rate
- Complete empirical model selection and record test conditions and pass criteria
- Model name and API endpoint are configured, not hardcoded
- Prompt has been regressed on the evaluation set, and the version number is recorded
- Output parsing has been hardened with a degradation strategy
- Configuration changes have passed approval, and rollback permission has been confirmed for specific people
- Secrets are injected through the secret management service, with no plaintext secrets in code or logs
- Monitoring dashboards are in place, covering error rate, latency, and business metrics
- Rollback steps have been rehearsed, and on-call staff can execute them
5. Canary Rollout and Rollback
5.1 Phased Traffic Ramp-Up
Ramp up traffic by percentage in stages, for example 1%, 5%, 20%, 50%, and 100%. Observe each stage for a period. The observation period length depends on traffic volume and the business cycle, and should be determined before ramping up.
Before each ramp-up stage, check three things: whether the error rate is within the baseline range, whether latency is normal, and whether business evaluation sampling results meet the bar. Proceed to the next stage only when all three pass.
5.2 Rollback Triggers
Write rollback conditions in advance and make them executable automatically or semi-automatically. The following thresholds are examples only and must be adjusted based on business baselines:
- Error rate rises more than 1 percentage point above baseline and lasts for 5 minutes.
- P95 latency exceeds 2 times the baseline and lasts for 5 minutes.
- Failure rate on key business evaluation samples exceeds the configured value.
- Data anomalies appear, such as widespread missing structured fields.
5.3 Rollback Steps
- In the configuration center, switch the model name back to the fallback option. If the legacy model has already been retired, the fallback should be a validated replacement model or existing degradation logic.
- Confirm traffic has switched back and observe error rate recovery.
- Preserve failed samples and their request timestamps for troubleshooting.
- If there were write operations during canary, check data consistency. Output results should record the model version so old and new data can be distinguished. Repeated write operations should be idempotent to avoid duplicate records after rollback.
- Record the event timeline, trigger conditions, and handler, and schedule a postmortem.
Rollback permissions must be assigned to specific people in advance, and on-call staff must be able to execute configuration rollback without temporary approval.
5.4 Post-Ramp-Up Cleanup
After full switchover has run stably for a period, clean up the legacy model configuration and code branches. Before cleanup, keep a backup of the old configuration for later troubleshooting.
FAQ
What should I do after the legacy model is retired? First confirm status with a minimal request, then inventory callers. If a fallback model already exists, switch to the fallback first to stop the bleeding, then perform formal model selection.
How should I choose a new model? Compare models with your own evaluation set rather than relying on promotional data. Focus on business pass rate, output stability, and cost basis, and record test conditions for all three.
What is most easily missed during migration? Scheduled jobs, offline scripts, and old values in the configuration center. Inventory must cover these locations, not just the main service.
What are common mistakes? Not setting timeouts, causing requests to hang; writing secrets into code or logs; changing only code but not configuration, making rollback slow; and not recording baselines, making it impossible to judge whether the switchover is good or bad.
