Rate limiting is the least glamorous part of shipping an LLM feature, and it is usually the thing that breaks first in production. The failure mode is consistent: a prototype that handles a few hundred requests a day gets pointed at a backlog of tens of thousands, and within a minute every worker is retrying into a wall of 429s.
This guide covers what is actually being counted, why naive retry logic makes throttling worse rather than better, and four patterns you can paste into a codebase today: server-directed backoff, bounded concurrency, model escalation, and shrinking requests before you send them. Every example runs against deepseek-v4-flash through the OpenAI SDK and escalates to deepseek-v4-pro only when the task genuinely needs it.
Rate Limits Are a Shape Problem, Not a Volume Problem
Limits are almost always expressed over a rolling window, not as a daily allowance. That means a workload comfortably inside its monthly quota can still trip limits on every run, because it arrives in bursts: a cron job that fires 5,000 calls at 02:00 behaves very differently from 5,000 calls spread across an hour, even though the totals are identical.
Three separate counters usually apply, and they fail in different ways. Understanding which one you hit tells you which fix to apply, because throwing retries at a concurrency problem does nothing and adding a semaphore does nothing for a token-budget problem.
| Limit type | What it counts | How it shows up | First fix |
|---|---|---|---|
| Requests per minute | Individual HTTP calls, including trivial ones | 429s on short prompts while long prompts still succeed | Batch several small items into one call |
| Tokens per minute | Input tokens plus the completion budget you requested | 429s that look random and cluster around large prompts | Trim context and cap max_tokens per task |
| Concurrency / in-flight | Requests open at the same instant | Timeouts and rising tail latency rather than clean 429s | Semaphore with a fixed ceiling, queue the remainder |
One detail catches people out: on many APIs the completion budget you ask for is accounted for when the request is dispatched, not when the response finishes. If you set a very high max_tokens on every call as a safety net, you may be throttled by budget you never actually use. Set the cap per task and check your provider documentation for how your window is measured.
Strategy 1: Back Off the Way the Server Tells You To
The standard retry snippet — sleep for two to the power of the attempt — is a thundering herd generator. Every worker that fails at the same instant wakes at the same instant and retries in the same instant, so a brief throttle becomes a stable oscillation. The fix has three parts: honour the retry-after header when the server sends one, add jitter so workers desynchronise, and never retry errors that will fail identically on the second attempt.
import os, random, time
from openai import OpenAI, APIStatusError, RateLimitError
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def complete(prompt: str, max_attempts: int = 5) -> str:
for attempt in range(max_attempts):
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
max_tokens=512,
)
return resp.choices[0].message.content
except RateLimitError as exc:
if attempt == max_attempts - 1:
raise
headers = exc.response.headers if exc.response is not None else {}
delay = float(headers.get("retry-after", 2 ** attempt))
time.sleep(min(delay, 30) + random.uniform(0, 0.75))
except APIStatusError as exc:
# 4xx other than 429 will fail again unchanged -- surface it instead.
if exc.status_code < 500 or attempt == max_attempts - 1:
raise
time.sleep(2 ** attempt + random.uniform(0, 0.75))
raise RuntimeError("retry loop exited without a response")
Two habits matter as much as the code. Cap the sleep so a pathological retry-after cannot stall a worker for minutes, and log the header value alongside a request id. When you are debugging a throttled batch at 3am, knowing whether the server asked you to wait briefly or substantially changes whether you tune batch size or concurrency.
Strategy 2: Bound Concurrency Instead of Chasing Throughput
The most common high-volume bug is asyncio.gather over thousands of prompts. It feels fast because it saturates the network immediately, but it also saturates your rate limit immediately, and the retry storm that follows costs more wall-clock time than steady pacing would have. A semaphore gives you a hard ceiling on in-flight requests while keeping the queue ordered.
Start lower than you think you need. Raising concurrency from a working baseline is a one-line change; recovering from cascading 429s during a deadline is not.
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
async def summarize(sem: asyncio.Semaphore, text: str) -> str:
async with sem: # never more than N requests in flight
resp = await client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": f"Summarize in one sentence:\n{text}"}],
max_tokens=128,
)
return resp.choices[0].message.content
async def run(texts: list[str], concurrency: int = 8) -> list[str]:
sem = asyncio.Semaphore(concurrency)
return await asyncio.gather(*(summarize(sem, t) for t in texts))
if __name__ == "__main__":
docs = [f"Document {i} describes a routine support ticket." for i in range(20)]
for line in asyncio.run(run(docs)):
print(line)
Strategy 3: Route Cheap, Escalate Rarely
Most pipelines do not need the strongest model on every item. Use deepseek-v4-flash as the default and escalate to deepseek-v4-pro only when the fast model's output fails a check you can automate — invalid JSON, a missing required field, a failed schema validation. This keeps your token spend concentrated on the hard slice instead of spread evenly across everything, and pro costs more than flash, so the saving is real.
The escalation must be driven by a validator, not by vibes. Write the check first, then wire the fallback.
import json, os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def extract_fields(prompt: str) -> dict:
"""Fast model first; pay for the stronger model only when validation fails."""
for model in ("deepseek-v4-flash", "deepseek-v4-pro"):
resp = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "Return one JSON object and nothing else."},
{"role": "user", "content": prompt},
],
max_tokens=512,
)
raw = resp.choices[0].message.content.strip()
raw = raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
return parsed
raise ValueError("Neither model produced valid JSON")
Strategy 4: Shrink the Request Before You Send It
Deduplicate inside a run. High-volume batches often contain near-identical items; hash the normalized prompt and serve repeats from memory instead of re-sending them.
Cap max_tokens per task type rather than globally. A classification needs a handful of tokens, not the same ceiling as a long-form generation.
Retrieve instead of dumping. Sending a whole document to answer a narrow question inflates input tokens on every call — chunk and select first.
Consolidate small prompts. If you are asking the same question about twenty rows, ask it about twenty rows in one call and parse a list.
Stream and abort. Streaming does not change what gets counted, but stopping a generation the moment you have the answer reduces the tokens you actually consume.
Keep stable prefixes stable. If your provider supports prompt caching, identical leading context can be cheaper on repeat calls — check your dashboard for whether it applies to your traffic.
Instrument These Before You Scale
429 rate per minute, split by endpoint — a floor of constant throttling means your baseline concurrency is too high.
Distribution of input tokens per request, not just the average. A long tail is what trips token windows.
p95 and p99 latency separately. Rising tails usually mean you are queuing behind your own retries.
Escalation rate from deepseek-v4-flash to deepseek-v4-pro. If it is high, your validator or prompt is the problem, not the model.
Cache hit rate on deduplicated prompts. This is usually the cheapest win available and the one nobody measures.
If every worker retries on the same schedule, you have not built resilience — you have built a metronome that hammers the endpoint. Jitter, a ceiling, and a queue are what turn a throttled batch into a slow success.
Running High-Volume Workloads on AiCredits
AiCredits sells DeepSeek API credits to developers outside China, payable by card or PayPal, with no Chinese phone number or bank account required. That removes the onboarding step that usually blocks a first high-volume test run. Because both deepseek-v4-flash and deepseek-v4-pro are reachable through the same OpenAI-compatible endpoint, the routing pattern above is a one-word change in your model string.
Pricing is usage-based: flash costs less than pro, off-peak usage costs less than peak, and cache hits are cheaper than fresh input. For current rates, see aicreditsapi.com/pricing. If you would rather fix token waste in your codebase than pay for it, our linting tools flag the usual culprits — oversized max_tokens, unbounded loops, and context that gets resent unchanged.
FAQ
No. Streaming changes how the response arrives, not how requests and tokens are counted against your window. It is still useful: you can abort a generation as soon as you have what you need, which lowers token consumption on long outputs, and it improves perceived latency for interactive features.
Log the response headers on every 429, especially retry-after, plus a request id and the input token count. If the failures cluster around large prompts you are likely hitting a token window; if they cluster around many small prompts, it is request rate; if you see timeouts rather than clean 429s, suspect concurrency.
Only 429s and server errors, with jitter and a hard attempt cap. Authentication failures, malformed requests, and validation errors will fail identically on the second try, so retrying them just delays the error report and burns your budget.
Rarely. Reserve deepseek-v4-pro for work the fast model fails on, measured by a validator. Routing keeps your spend on the hard slice instead of subsidising easy tasks, and it gives you a clean escalation signal to watch.
Limit tiers are set by the provider and typically respond to sustained, well-shaped traffic rather than a single burst. On AiCredits you work from a credit balance with card or PayPal, and current rates and terms live at aicreditsapi.com/pricing.