Prompt
How do I handle rate limits across OpenAI, Anthropic, and open-source models?
Latest observation
Handling rate limits well usually means building one provider-agnostic control layer that manages retries, pacing, quotas, and fallback behavior for OpenAI, Anthropic, and open-source/self-hosted models.
1) Treat every model/provider as having its own budget
Track separately:
- Requests per minute (RPM)
- Tokens per minute (TPM)
- Concurrent requests
- Daily/spend quotas
- Context window limits
- For self-hosted/open-source: GPU memory, batch size, queue depth
Even if two providers both return “rate limit,” the real bottleneck may be different.
2) Normalize errors into a common format
Build a small adapter layer that converts provider-specific failures into categories like:
rate_limitedtemporary_unavailablequota_exceededinvalid_requestcontext_too_longauth_error
This lets your app use one retry/fallback policy instead of special-casing each SDK.
3) Use exponential backoff with jitter
For transient failures and 429s:
- Retry with exponential backoff
- Add random jitter
- Cap max delay and max retries
Example policy:
- retry after 0.5s, 1s, 2s, 4s, 8s
- stop after 5 attempts
- use full jitter or equal jitter to avoid retry storms
Avoid immediate retries, especially with concurrent traffic.
4) Implement client-side throttling
Don’t wait for the provider to reject you. Add a local limiter:
- Token bucket or leaky bucket
- Separate buckets per provider/model
- Optional per-tenant/user buckets
This is especially important if you have:
- bursty traffic
- many workers
- multiple services hitting the same API key
5) Batch and queue when possible
If your workload allows it:
- Queue requests instead of firing instantly
- Batch embeddings, classification, or offline jobs
- Schedule lower-priority tasks during off-peak times
For open-source models, batching can improve throughput dramatically, but can increase latency.
6) Respect provider-specific headers and signals
Many APIs return rate-limit metadata. If available, use it:
- remaining requests/tokens
- reset time
- retry-after
- organization/project quotas
When the provider gives a Retry-After, honor it.
7) Add fallback routing
Define a policy like:
- Try preferred model/provider
- If rate-limited, route to secondary model
- If still constrained, degrade gracefully
Examples:
- Use a cheaper/smaller model for non-critical tasks
- Reduce
max_tokens - Shorten prompts
- Switch from premium provider to self-hosted/open-source
- Return cached or partial results
8) Use adaptive request sizing
If you hit token limits often:
- Reduce prompt size
- Summarize conversation history
- Trim irrelevant context
- Cap output length
- Split large tasks into chunks
This helps both rate limits and cost.
9) Coordinate across distributed workers
If you run multiple app instances:
- Centralize rate-limit state in Redis or another shared store
- Use distributed semaphores or counters
- Avoid each worker independently hammering the API
Without coordination, each node may think it has full quota.
10) For open-source/self-hosted models, manage capacity like an SRE problem
You won’t get 429s from a vendor, but you will still “rate limit” yourself via resources:
- queue length
- max concurrent generations
- GPU utilization
- memory fragmentation
- timeouts
Common tactics:
- Admission control
- Dynamic batching
- Autoscaling
- Circuit breakers
- Timeouts and cancellation
- Separate queues for interactive vs batch jobs
11) Add circuit breakers
If a provider starts failing repeatedly:
- stop sending traffic for a short cooldown
- fail over to another provider
- reduce load automatically
This prevents cascading failures and wasted retries.
12) Monitor the right metrics
At minimum track by provider/model:
- request count
- success/error rate
- 429 count
- retry count
- latency p50/p95/p99
- tokens in/out
- queue depth
- fallback rate
- cost per request
You’ll quickly see whether you need more quota, better pacing, or a fallback.
A practical architecture
A good implementation often looks like this:
- LLM Router
- chooses provider/model
- Rate-Limit Manager
- per-provider token/request budgets
- Retry Policy
- exponential backoff + jitter
- Queue
- smooth bursts
- Fallback Engine
- alternate model/provider
- Observability
- metrics and alerts
Simple policy example
- Primary: OpenAI GPT-4-class model
- Secondary: Anthropic Claude equivalent
- Tertiary: self-hosted open-source model
- If 429:
- wait using
Retry-Afterif present - retry up to 3–5 times
- if still blocked, fail over
- wait using
- If queue backlog exceeds threshold:
- degrade to cheaper/smaller model
- reject low-priority traffic
Best practices summary
- Don’t hardcode provider behavior in application logic
- Use centralized throttling
- Retry carefully with jitter
- Prefer graceful degradation over hard failure
- Track separate budgets per provider/model
- Plan for both vendor limits and your own infrastructure limits
If you want, I can give you:
- a Python implementation of a provider-agnostic rate limiter,
- a Node.js example, or
- an architecture diagram/pattern for production.