A 429 is not a crash. It is the API telling you that you are asking for more capacity than you are currently allowed to consume. Teams that get flooded with 429s in production are almost never unlucky — they are missing one of three things: a retry policy that respects the server's own backpressure signal, a concurrency cap that reflects real account limits, or a workload design that stops generating so many requests in the first place.
Below is a practical playbook: how to read a 429 correctly, a retry helper you can paste into a service today, bounded-concurrency patterns for async workloads, and the design changes that reduce how often you ever see a 429 at all.
A 429 is a queueing signal, not a bug. Systems that treat it that way get paged less.
Read the 429 before you retry it
The status code 429 is overloaded. It can mean a per-minute request ceiling, a tokens-per-minute ceiling, a concurrency ceiling, or an account-level quota condition. Blind retry is the correct response to the first three and the wrong response to the last — retrying a quota problem just burns wall-clock time and log volume.
So before you write retry logic, write inspection logic. Check whether the response includes a retry-after header. If it does, that is the server handing you the exact wait duration; honor it, and do not stack your own exponential backoff on top of it. If it does not, the error body usually distinguishes a transient rate limit from a quota problem.
retry-after: Npresent → sleep N seconds, then make one attempt. No jitter needed, the server already told you when to come back.A burst of 429s immediately after you scaled up workers → you raised concurrency, not request volume. Lower the in-flight count per process.
429s only on long prompts or large contexts → you are hitting a token-based ceiling rather than a request-count ceiling. Trim or split the input.
429 on the very first call of the day, with no
retry-after→ check your balance and quota in the AiCredits dashboard before you touch any code.
A retry helper that survives real traffic
This is the version worth keeping. It retries the three transient failure classes, reads retry-after when present, falls back to capped exponential backoff with jitter, and gives up loudly instead of hanging a request forever.
import os
import random
import time
from openai import APIConnectionError, APITimeoutError, OpenAI, RateLimitError
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def chat(prompt: str, retries: int = 5) -> str:
for attempt in range(retries):
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
timeout=60.0,
)
return resp.choices[0].message.content or ""
except (RateLimitError, APIConnectionError, APITimeoutError) as err:
if attempt == retries - 1:
raise
headers = getattr(getattr(err, "response", None), "headers", None) or {}
hint = headers.get("retry-after")
try:
delay = float(hint)
except (TypeError, ValueError):
delay = min(2 ** attempt, 30)
delay += random.uniform(0, delay * 0.5) # jitter de-syncs a fleet
time.sleep(delay)
return ""
if __name__ == "__main__":
print(chat("Explain prompt caching in two sentences."))
Three details carry most of the value. Jitter matters because without it every worker in your fleet retries at the same instant and re-creates the burst that caused the 429. The cap on the exponential term (min(2 ** attempt, 30)) stops wait times from growing without bound. And retrying connection and timeout errors alongside 429s is intentional — from the caller's perspective they are the same category of transient failure.
What you should not retry: 400, 401, 403, 404, and 422. Those are your bug, your key, or your payload. Silently retrying them hides a real defect and multiplies your request count for no benefit.
Streaming changes the math
With streaming, a request can be accepted and then interrupt partway through. By the time you notice, the model may already have produced output you were billed for. A blind retry therefore does not reset the clock — it duplicates work.
The practical rule: buffer the partial output as it arrives, and only retry the whole call if nothing usable was received. If you got a usable prefix, continue from where it stopped rather than regenerating from scratch. Also set an explicit client timeout on streams — a dropped connection that nobody closes can keep consuming capacity on the server side while your process has already moved on.
Bound concurrency, don't just retry
Retry logic handles the symptom. Concurrency control handles the cause. If you launch two hundred coroutines at once, all two hundred will collect a 429 and then all two hundred will retry in near-lockstep. A semaphore is the cheapest fix in the entire stack.
import asyncio
import os
import random
from openai import AsyncOpenAI, RateLimitError
client = AsyncOpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
MAX_IN_FLIGHT = 4 # start small, raise it until you see sustained 429s
RETRIES = 5
async def ask(sem: asyncio.Semaphore, prompt: str) -> str:
async with sem:
for attempt in range(RETRIES):
try:
resp = await client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
)
return resp.choices[0].message.content or ""
except RateLimitError:
if attempt == RETRIES - 1:
raise
await asyncio.sleep(min(2 ** attempt, 20) + random.random())
async def main(prompts: list[str]) -> list[str]:
sem = asyncio.Semaphore(MAX_IN_FLIGHT)
return await asyncio.gather(*(ask(sem, p) for p in prompts))
if __name__ == "__main__":
prompts = [f"Summarize paragraph {i} in one sentence." for i in range(12)]
for out in asyncio.run(main(prompts)):
print("-", out)
Tune it empirically: start with a handful of in-flight requests, increase until 429s become sustained rather than occasional, then step back one notch. Remember that limits apply to the account, not the process — if you run six workers, each one's share of the ceiling is roughly one sixth, so set per-process limits assuming aggregate traffic. Give batch jobs their own smaller pool so a backfill can never starve your user-facing calls.
Make fewer requests: the part retries cannot fix
Keep prompt prefixes stable. Put fixed instructions and system content first and variable content last, so repeated calls can reuse cached prefix work. Cache hits are cheaper and consume less of your rate-limit headroom.
Right-size the model. Use
deepseek-v4-flashfor classification, extraction, routing, and summarization — the high-volume work. Reservedeepseek-v4-profor genuinely hard reasoning where the quality difference changes the outcome. Pro consumes more per call, which moves you toward token ceilings faster.Move non-urgent work off-peak. Backfills, re-indexing, and nightly evaluations do not care about latency, and off-peak capacity is both easier to get and priced more kindly.
Deduplicate aggressively. Hash the prompt and cache the response for a short window. A surprising share of retries are re-sends of a request that actually succeeded.
Trim retrieval context. If six chunks answer the question, sending twenty costs you tokens and rate-limit budget for nothing.
Batch related items into one call where the task allows, instead of issuing one request per row.
Symptom, cause, fix
| Symptom | Likely cause | Fix |
|---|---|---|
| 429 during bursts, clean when idle | Per-minute request ceiling | Queue requests, bound in-flight concurrency |
| 429 only with long prompts | Token-based ceiling | Trim context, split into smaller steps |
| 429 right after scaling workers | Concurrency ceiling (shared per account) | Lower per-process limits, add worker-aware pooling |
| 429 on the very first call | Quota or balance condition | Top up at aicreditsapi.com, then re-check |
| `retry-after` on nearly every rejection | Sustained server-side pressure | Honor the header, add jitter, spread load across time |
Production checklist
Honor
retry-afterwhen present; otherwise use exponential backoff with full jitter and a hard cap on delay.Cap retries at four or five and cap total wait time — fail loudly after that instead of holding a request open indefinitely.
Bound concurrency per process, and account for the number of processes sharing one API key.
Separate interactive and batch queues so heavy jobs cannot starve user-facing traffic.
Track your 429 rate as a metric and alert on the sustained rate, not on individual events.
Keep requests idempotent where possible, so a retry cannot double-write or double-charge downstream.
Log the response body and headers on 429s during rollout, then dial the verbosity back once the pattern is clear.
FAQ
It can, yes. Account-level quota and balance conditions are sometimes surfaced with the same status code as transient rate limiting. The distinguishing signal is usually the error body and the absence of a retry-after header on the very first request of a session. Check your balance in the AiCredits dashboard before you start tuning backoff parameters.
Four or five attempts is a sane default for interactive traffic, with exponential backoff capped at around thirty seconds per wait so the total budget for one call stays under about a minute. Batch jobs can afford a longer budget because nobody is waiting on the response. The important part is that retries are bounded — an unbounded loop turns a rate limit into an outage.
Only if nothing usable arrived. Streaming responses may already have produced output by the time the connection drops, so a full retry duplicates work and consumes more of your limit. Buffer partial output, and continue from the last complete segment rather than regenerating the whole thing.
Limits are applied at the account level rather than per model, but the models consume differently. Pro generates more per call for complex work, so a pro-heavy workload reaches token-based ceilings sooner than a flash-heavy one. A practical split is flash for volume and pro for the requests where quality genuinely matters.
Not with AiCredits. You top up with an international card or PayPal at aicreditsapi.com and point the OpenAI SDK at https://api.aicreditsapi.com/v1. The code in this article works unchanged — the only thing that changes is where your credits come from. Current rates are on the pricing page.