LLM Rate Limiting
Implement resilient LLM integrations with deterministic retry, throttling, quota handling, and concurrency controls. Read references/examples.md to understand expected triggers and non-triggers. Read references/troubleshooting.md when symptoms do not match the happy path.
Workflow
- Inspect the codebase to find the single boundary where LLM calls leave the application. Prefer modifying one shared gateway, client wrapper, or service module over scattering retries across call sites.
- Analyze the target project source code to identify the specific LLM provider in use. Treat OpenAI and Groq as first-class branches with provider-specific header semantics and limit models.
- If the provider is OpenAI, read
references/openai-rate-limits.mdbefore choosing quotas, retry behavior, or pacing assumptions. - If the provider is Groq, read
references/groq-rate-limits.mdbefore choosing quotas, retry behavior, or pacing assumptions. - If the user says "I am on Tier 1" or provides another plan label, treat it as budget context only unless the provider docs say it fully determines operational limits.
- Reuse existing abstractions, logging, configuration, and test helpers already present in the project. Preserve the project style instead of introducing a parallel client stack.
- Read
scripts/resilience_templates.pyand adapt its retry, reset-window, and circuit-breaker patterns to the project's HTTP client and exception model. - Add or update regression coverage around the shared LLM boundary when the project has tests. Validate happy paths, throttling paths, and provider-specific header parsing.
Reactive Handling
Implement Reactive Header-Driven Handling. Use the tenacity library in Python to wrap all LLM network calls.
- Parse
Retry-Afterfirst when it is present. - If
Retry-Afteris missing, pace using the provider's reset headers before falling back to exponential backoff with jitter. - Keep exponential jitter in the
1sto60srange to avoid thundering herd spikes. - Explicitly handle HTTP
429and503errors. - Treat transient
5xx, timeout, and connection-reset errors as retry candidates only when the surrounding call is idempotent or safe to repeat. - Avoid retrying deterministic client errors such as malformed requests.
- Emit structured logs that include provider, model, status code, retry attempt, and computed delay.
- For OpenAI, parse
x-ratelimit-limit-requests,x-ratelimit-limit-tokens,x-ratelimit-remaining-requests,x-ratelimit-remaining-tokens,x-ratelimit-reset-requests, andx-ratelimit-reset-tokens, and pace against the most constrained dimension. - For Groq, parse
retry-afterplusx-ratelimit-*headers, remembering that request headers refer to RPD and token headers refer to TPM. - Distinguish retryable throttling from non-retryable quota or billing exhaustion.
Circuit Breaker
Implement the Circuit Breaker Pattern. Use the pybreaker library to open the circuit after 5 consecutive throttling or transient server failures.
- Exclude
400and401client errors from tripping the breaker. - Keep the breaker at the same shared LLM boundary as the retry logic.
- Raise or map a project-specific fail-fast exception when the breaker is open so upstream code can degrade gracefully.
- For Groq flex processing, treat status
498withcapacity_exceededas a retryable capacity signal, not as a permanent application error.
Proactive Throttling
Implement Proactive Throttling.
- Set up a local client-side token bucket or equivalent limiter that tracks the provider dimensions actually exposed by the target API.
- Keep effective throughput about
10%under known thresholds to preserve headroom for jitter, clock skew, and concurrent workers. - Queue, delay, or reject locally when insufficient request or token budget is available instead of letting the provider reject the call.
- Prefer shared state such as Redis only when the application has multiple workers or hosts that must coordinate the same budget.
- For OpenAI, treat limits as organization-level and project-level constraints, not user-level constraints.
- For OpenAI, scope pacing by model family and shared-limit groups instead of assuming every model has an independent budget.
- For OpenAI, account for long-context request limits separately when the target model uses a distinct long-context bucket.
- For Groq, treat limits as organization-level constraints and remember that project-level custom limits can only be more restrictive than the org ceiling.
- For Groq, remember that cached tokens do not count toward rate limits, but parallel traffic can still exhaust non-cached capacity.
Framework Optimizations
Implement Framework Optimizations when orchestration layers are present.
- Enforce explicit
max_concurrencyor equivalent fan-out limits on every parallel LLM execution path to prevent network spikes. - Inspect async helpers, worker pools, graph runners, and evaluation harnesses for hidden parallel LLM calls.
- Trim or bound unbounded chat history if the integration keeps appending old context into every call and rapidly burns token budgets.
Caching Guidance
Recommend Semantic Caching and provider-aware throughput tuning.
- Prompt the user in the console to integrate a Redis-backed semantic cache or GPTCache to bypass repeated external calls.
- Frame caching as a direct rate-limit multiplier, not only a latency optimization.
- Suggest cache insertion only for prompts whose outputs are stable enough to reuse.
- For OpenAI, recommend reducing
max_tokensto the closest realistic output size and batching synchronous workloads only when RPM is saturated and TPM headroom remains. - For Groq, recommend prompt caching when the model supports it and the workload reuses large shared prefixes.
Implementation Rules
- Prefer battle-tested libraries over custom retry loops or breaker implementations.
- Keep deterministic code paths low freedom. Do not invent new backoff formulas when the template already fits.
- Use Unix-style forward slashes in every file path you write or reference.
- Keep provider semantics explicit. Do not assume one provider's header meanings apply to another.
- Use actual headers, authenticated limits pages, or explicit user-provided numbers when exact pacing matters.
- Keep the skill folder clean: no
README.md, no repo-only docs, and no screenshots inside the installable skill.