How to Handle LLM API Rate Limits: A Practical Multi-Provider Migration Guide
This article explains how to diagnose LLM API quota and rate-limit errors, build a unified access gateway, route requests across multiple providers, persist conversation context, and migrate in stages. It covers error-code triage, backoff and idempotency considerations, gateway configuration examples, routing and fallback strategies, storage design, and a pre-migration checklist.
Introduction: Why Rate Limits Affect the Whole Business
Many teams assume that after they integrate an LLM API, the service will remain stable and available. In practice, any provider may reject requests because of excessive concurrency, exhausted quota, or an abnormal account state.
Consider a hypothetical scenario: a platform opens a new batch of interfaces, many users call them at the same time, some requests are rejected, some streaming responses break midway, and historical conversations cannot continue. This is an illustrative scenario used to explain the risk. It does not correspond to any actual event on a specific platform.
If a business deeply ties session state, invocation logic, and service operation to a single provider, one rate limit can affect all users at once. This article proceeds in the following order: first, identify limit types and error codes; second, build a unified gateway; third, implement multi-provider routing and context persistence; and finally, migrate in stages.
1. Limit Types and Troubleshooting: How to Distinguish 429, 403, and 503
1.1 Common Limit Types
API limits usually come in more than one form. Common examples include:
- Request rate limits: the number of calls allowed per second or per minute (RPM, QPS).
- Concurrency limits: the number of requests that can be processed at the same time.
- Token limits: the total number of input and output tokens per minute (TPM).
- Daily or monthly quota: the total usage cap per day or per month.
- Account balance or budget: requests are rejected when the balance is insufficient or the budget is exhausted.
A single request may trigger multiple limits at the same time. During troubleshooting, first check the returned error code and error message, then determine which type of limit was hit.
1.2 Error Code Decision Table
| Status code | Common meaning | Retry? | Handling |
|---|---|---|---|
| 429 | Request rate, concurrency, or token limit exceeded | Yes | Read rate-limit response headers, apply exponential backoff with jitter, and reduce concurrency |
| 503 | Service temporarily unavailable or overloaded | Retry a limited number of times | Back off and retry; switch to a backup provider after the threshold is exceeded |
| 401 | Invalid or expired key | No | Check the key, environment variables, and key rotation records |
| 403 | Insufficient permissions, unavailable model, regional restriction; some platforms also use it for quota issues | Usually no | Check permissions, model name, and account status |
| 400 or 413 | Invalid parameters or context too long | No | Fix the request, truncate the context, or summarize history |
Different platforms use 403, 402, and 429 in different ways. Follow each provider’s official documentation, and do not treat every rejection as rate limiting. Treating 403 as a rate limit leads to ineffective retries and also wastes quota.
1.3 Rate-Limit Response Headers and Retry-After
Many platforms return a wait time in a 429 response. A common field is Retry-After. It may be a number of seconds or an HTTP date, so both formats need to be handled during parsing. Some platforms also return headers related to remaining quota; for specific field names, refer to the official documentation.
1.4 Exponential Backoff and Jitter
Do not resend immediately when retrying. The recommended approach is exponential backoff with random jitter, so that a large number of requests do not flood in again at the same moment:
import randomimport timedef call_with_backoff(send, max_retries=4, base=0.5, cap=8.0):"""send is a no-argument function that returns a response object with status_code and headers."""resp = send()for attempt in range(max_retries):if resp.status_code not in (429, 503):return respretry_after = resp.headers.get("Retry-After")if retry_after and retry_after.isdigit():delay = float(retry_after)else:delay = random.uniform(0, min(cap, base * (2 ** attempt)))time.sleep(delay)resp = send()return resp
The parameters above are examples and need to be adjusted based on business load-test results. If Retry-After is in date format, the code needs additional parsing.
1.5 Idempotency and Retries
Retries introduce the risk of duplicate execution. For requests that produce side effects, such as creating a task, writing data, or triggering a billable generation request, do the following:
- Generate a unique idempotency key for each logical request, and reuse the same key when retrying. Some platforms support request headers such as
Idempotency-Key; whether they are supported depends on the official documentation. - If the platform does not support idempotency keys, record request status in your own system and check whether the result has already taken effect before retrying.
- After a streaming request is interrupted, do not immediately resend the entire segment. First determine whether the content already received is usable.
1.6 Degradation Trigger Conditions
When retries cannot solve the problem, degradation is required. Common trigger conditions include:
- The failure rate for the same provider exceeds a threshold within a statistical window, for example, more than 10% within 5 minutes. This is an example value and should be set according to business tolerance.
- Multiple consecutive 503 responses or timeouts occur.
- The 95th percentile latency remains above an acceptable range.
- Account quota is about to run out, triggering a budget alert.
Degradation options include switching to a backup model or backup provider, returning cached results, showing users a queue notification, or temporarily disabling non-core features. Degradation strategies should be written and rehearsed in advance rather than decided ad hoc after an incident occurs.
2. Unified Access Gateway
2.1 What the Gateway Solves
The gateway is the single entry point between business code and model providers. The business only calls internal interfaces, while the gateway handles authentication, rate limiting, retries, logging, metrics collection, and conversion of internal requests into each provider’s format.
The benefit is that when a provider changes, only the adapter in the gateway needs to be modified, and business code generally does not need to change.
2.2 Core Gateway Configuration
The gateway should manage at least the following:
- Key management: read keys from environment variables or a key management service; do not write them into code, configuration files, or logs.
- Model aliases: the business uses logical names such as
chat-default, and the gateway maps them to specific provider model names. - Timeout settings: distinguish between connection timeout, first-token timeout, and total timeout. Streaming requests need a separate first-token timeout.
- Rate limiter: set token buckets by tenant, user, or interface to prevent a single user from exhausting shared quota.
- Circuit breaker: automatically open after a provider has consecutive failures, then try a half-open probe after a period of time.
An example configuration is shown below; the field names are for illustration only:
models:chat-default:primary: provider_a/model-xfallback: provider_b/model-ytimeouts:connect_ms: 2000first_token_ms: 8000total_ms: 60000rate_limit:per_user_rpm: 30circuit_breaker:failure_threshold: 5open_seconds: 30
2.3 Boundaries of the Gateway
The gateway adds one network hop, so latency increases slightly. The gateway itself may also become a single point of failure, so multi-instance deployment and health checks are required.
The gateway should not carry business logic. It should only handle common invocation governance concerns. Prompt templates, business rules, and session state should be placed in the business layer or persistence layer.
3. Multi-Provider Routing
3.1 Common Routing Strategies
- Primary-backup mode: use the primary provider by default and switch to the backup provider on failure. This is simple to implement and suitable for most scenarios.
- Success-rate weighting: dynamically distribute traffic based on recent success rates and latency. This is more complex to implement and requires stable metrics collection.
- Task-type routing: route long-text, code, speech, and other tasks to providers that are better suited to them. This requires maintaining evaluation results for each task.
3.2 When to Switch
Switch providers only in the following situations: 429, 503, timeout, and an open circuit breaker. Errors such as 400, 401, and 403 are usually request or configuration problems. Switching to another provider often does not solve them and may spread the problem to both sides.
The switching itself must also be rate-limited. If all requests switch to the backup provider at the moment the primary provider fails, the backup provider may also rate-limit immediately, creating a retry storm.
3.3 Model Capability Differences
Models from different providers may differ in the following areas:
- Parameter formats for function calling or tool calling, and support for parallel calls.
- Constraints and stability of JSON output.
- Support for multimodal inputs such as images and audio.
- Context length limits and token counting methods.
- Output style and tone under the same prompt.
Therefore, before switching, you must run key scenarios against a fixed evaluation set and confirm that output quality reaches an acceptable level. Prompts may need to be adjusted separately for each provider.
3.4 Boundaries of Routing
Multiple providers increase the workload for interface adaptation, cost accounting, monitoring, and compliance review. If the business scale is small, primary-backup and degradation are enough at first; there is no need to build complex weighted routing from the beginning.
4. Context Persistence
4.1 Why You Should Store Conversations Yourself
If conversation history is stored only in a provider’s session system, provider rate limits, API changes, or account problems may prevent old conversations from continuing. By storing conversation history in your own database, you only need to reassemble requests in the new provider’s format when switching providers.
4.2 Recommended Storage Structure
The message table should contain at least the following fields:
conversation_id: conversation identifier.seq: message sequence number, used to preserve order.role: user, assistant, system, or tool.content: message content, stored in a unified internal format rather than directly in the provider’s raw structure.modelandprovider: the model and provider used to generate the message, for troubleshooting and analysis.status: complete, partially complete, or failed.token_count: token count, for calculating context length.schema_version: internal format version, for future upgrades.created_at: creation time.
4.3 Write Order
The recommended order is: save the user message first, then call the model, and finally save the assistant reply. If the call fails, the user message has already been saved, so it can be retried safely without losing user input.
When a streaming response is interrupted, save the received content with status=partial and tell the user that they can choose to continue generation or regenerate.
4.4 Handling Overlong Context
When historical messages exceed the target model’s context length, you can use the following approaches:
- Keep the system prompt and the most recent several turns of conversation.
- Generate a summary of older history and insert the summary as a system message.
- Truncate tool call results and keep only key fields.
Test truncation strategies with real conversations to avoid losing critical constraints.
4.5 Risks of Persistence
- Format incompatibility: tool calls, role definitions, and multimodal fields are not completely consistent across providers. During historical data migration, perform field mapping and sample validation.
- Personal information: conversation history often contains names, phone numbers, addresses, and other information. Encrypt it at rest, set retention periods, and support deletion by user.
- Cross-provider transmission: sending history to another provider is equivalent to handing data to a new processor. Evaluate data storage location, retention duration, and training-use terms, and sign a data processing agreement when necessary.
5. Staged Migration and Checklist
5.1 Three Stages
Stage 1: Shadow traffic. Business requests are sent to both the old provider and the new provider, but only the old provider’s results are returned. Record the new provider’s latency, error codes, and output differences for evaluation.
Stage 2: Canary rollout. Route traffic by hashing user IDs and gradually increase the new provider’s share, for example, 1%, 5%, 20%, 50%, and 100%. Observe at least one complete business cycle at each level. Proceed to the next level only when error rates, latency, and quality evaluation results all meet the target.
Stage 3: Full cutover and cleanup. After switching fully to the new provider, keep the old provider’s adapter for at least one release cycle for emergency rollback. Delete the old code only after confirming stability.
5.2 Pre-Migration Checklist
- Authentication: the new provider’s keys are stored in a key management service, isolated by environment, and configured with usage limits.
- Model capabilities: compare function calling, JSON output, multimodal input, context length, and other capabilities.
- Context: confirm the maximum length, token counting method, and message format.
- Tool calling: compare parameter structures, return formats, and parallel invocation.
