Migrating LLM APIs Under Rate Limits: A Practical Guide

    This guide explains why LLM API rate limits happen and how to migrate workloads without breaking availability. It covers auditing your call sites, building a pluggable provider layer with routing and error handling, adapting protocol differences across providers, migrating text, retrieval, document, audio, and reasoning workloads, using general cloud services for stability and cost control, and running a gradual rollout with rollback. Readers will get a checklist for validating a migration and keeping quota usage and per-task cost under control.

    1. Why Rate Limits Happen: Understand Before Reacting

    LLM inference is a resource-intensive workload. Unlike a traditional stateless web request, a single chat request may involve long-context encoding, multi-turn KV caching, streaming output, and content safety review. Compute usage per call can vary widely. Once a platform exposes the full stack to developers through an API, call volume often climbs quickly. To protect response quality for all tenants, providers apply rate limiting and quota management. This is an industry-wide practice, not a special policy from one vendor.

    Common quota dimensions include:

    • Requests per minute (RPM)
    • Tokens per minute (TPM)
    • Concurrent connections
    • Daily or monthly totals per account or per key
    • Separate quotas for each capability, such as text generation, web retrieval, document parsing, speech recognition, and speech synthesis

    Understanding these dimensions is the prerequisite for a migration plan, because different bottlenecks need different fixes. Request limits call for batching and queuing; token limits call for context compression and caching.

    2. Pre-Migration Inventory: Break “Calls” into a List

    Before changing code, build a call inventory. Record at least the following fields: the module where the call lives, the capability type, average input and output length, peak QPS, latency sensitivity, business impact of failure, and whether degradation is allowed.

    1. Module Capability Avg input Peak QPS Latency-sensitive Degradable
    2. Support chat Text generation 1800 12 High Yes
    3. Contract review Document parsing 12000 2 Low No
    4. Voice tickets Speech recognition - 5 Medium Yes

    The value of this list is that it turns the vague question of “should we move at all” into concrete engineering decisions: which call sites must migrate, which only need throttling, and which can be made asynchronous. In practice, a few long-context scenarios usually consume most of the quota. Fixing those first relieves most of the pressure.

    3. Target Architecture: From Single-Point Dependency to a Pluggable Call Layer

    The stable approach is not to swap one endpoint for another. Insert an abstraction layer between the business logic and the models. This layer handles protocol adaptation, authentication management, routing, retries, and circuit breaking. Business code programs only against a unified interface.

    1. class LLMProvider:
    2. def chat(self, messages, **kw): ...
    3. def embed(self, texts, **kw): ...
    4. class Router:
    5. def __init__(self, providers, policy):
    6. self.providers, self.policy = providers, policy
    7. def chat(self, messages, **kw):
    8. for name in self.policy.order(messages, kw):
    9. try:
    10. return self.providers[name].chat(messages, **kw)
    11. except RateLimited:
    12. continue
    13. except TransientError:
    14. continue
    15. raise AllProvidersExhausted()

    A three-layer routing policy is recommended:

    1. Priority and failover: send all traffic to the primary channel while it is healthy.
    2. Capability-based routing: send long-document parsing to channels that support large contexts, and voice workloads to a dedicated voice channel.
    3. Cost awareness: schedule low-value, latency-tolerant batch jobs on more economical channels.

    With these three layers combined, quota fluctuations on a single platform have much less impact on overall availability.

    4. Protocol and Capability Differences: The Real Work of the Adapter

    Providers do not expose identical interfaces. The adapter must handle these differences: message roles and where the system prompt belongs, the chunk format of streaming responses, how tool-calling (function calling) parameters are described, whether structured output is natively supported, error code semantics (rate limiting, authentication, content blocking, context overflow), and whether retries are idempotent.

    A practical recommendation is to fix error classification as an enum rather than scattering string checks across the codebase:

    1. class ErrKind(Enum):
    2. RATE_LIMIT = "rate_limit"
    3. AUTH = "auth"
    4. TOO_LONG = "too_long"
    5. SAFETY = "safety"
    6. SERVER = "server"

    Only categories judged retryable enter the backoff queue. Everything else returns to the business side for degradation, avoiding ineffective retries that further amplify quota pressure.

    5. Migrating Multiple Capabilities: Four Workloads Beyond Text

    The capabilities in the original requirement fall into four general workload types, each with different migration priorities.

    Web retrieval: this is a two-stage “retrieve then generate” flow. Decouple retrieval from generation. Normalize retrieval results into an intermediate structure that carries source and timestamp, and let the model only summarize. Switching channels then requires no changes on the retrieval side.

    Document parsing: split long documents by layout and paragraphs first, then feed semantic blocks to the model, using summary levels to avoid filling the context in one shot. Chunk granularity is the key portable asset and should be stored independently of the model.

    Speech recognition and synthesis: pay attention to sample rate, encoding format, segment duration, and endpoint detection strategy. Keep audio segmentation and post-processing (punctuation restoration, timestamp alignment) in your own services, and let the model side handle only transcription and synthesis.

    Reasoning: intermediate reasoning output varies significantly across channels. The business side should consume only the final answer and any necessary citations, avoiding tight coupling to intermediate structures.

    6. Using General Cloud Capabilities for Stability and Cost

    The runtime environment after migration can be hardened with general cloud product categories: object storage to archive original documents and audio, a message queue to smooth peaks and make non-real-time tasks asynchronous, a container platform to host the adapter and business services for elastic scaling, and logging plus monitoring and alerting to collect and visualize latency, token consumption, and failure codes for every call. Baidu AI Cloud offers corresponding capabilities in these general categories and can serve as the infrastructure for the migrated architecture.

    For cost control, three measures deliver the most direct benefit:

    1. Prompt and context compression to remove repeated background.
    2. Result caching that reuses output for identical or near-identical requests; semantic caching can significantly cut token consumption.
    3. Tiered model strategy: simple tasks use lightweight channels, and only complex tasks are escalated.

    7. Gradual Rollout and Rollback

    Migration must be gradual and reversible. Advance by call site rather than site-wide. Start in shadow mode with dual runs that only log and do not return results. Then ramp to 5%, 20%, and 50%, comparing quality metrics (human sample scoring, task success rate) and engineering metrics (P95 latency, error rate, cost per task). Finally, switch the primary. The rollback switch should be a configuration item rather than a release, so it takes effect within minutes.

    8. Acceptance Checklist

    • Does the call inventory cover all capability types and peak scenarios?
    • Does the adapter enforce unified error classification and retry boundaries?
    • Is there at least one backup channel and a local degradation path?
    • Are caching, compression, and tiering live with quantified benefits?
    • Does the monitoring dashboard include quota utilization and unit cost?
    • Have the rollout and rollback procedures been rehearsed?

    Rate limits are not the end of the road. They are the moment to move the architecture from “working” to “controllable.” Abstract calls into a pluggable capability layer, add solid observability and cost governance, and the application stays smooth in the face of any supply change.