AiCredits
Reliability Guide

Rate Limiting Explained: Handling 429s from LLM Providers Gracefully

Learn why LLM APIs return 429s, how to read Retry-After, and how to build retry, concurrency, and token-budget controls that keep DeepSeek workloads running.

Published 2026-11-04 Updated 2026-11-04 8 min

Why LLM rate limits are different from ordinary API limits

HTTP 429 means the server understood your request and refused to process it right now because a limit was exceeded. In LLM APIs, that limit is rarely just requests per minute. Providers typically enforce several dimensions at once: requests per minute, tokens per minute — input plus output, often counted as output tokens are generated — concurrent in-flight requests, and daily or account-level quotas. A short prompt sent many times can hit requests-per-minute limits; one long prompt can hit token limits. Streaming makes this feel stranger because the request starts successfully and the token budget is consumed over time.

Because limits are multi-dimensional, retrying the same call without changing its shape often makes the incident worse. A retry storm turns one 429 into many, and immediate retries compete with your own traffic. The goal is not to beat the limit; it is to make your workload fit inside it predictably and to degrade cleanly when it does not.

Read the 429 response before you retry

Before writing retry logic, inspect the error object. The OpenAI SDK exposes the HTTP response on the exception, so you can read Retry-After when it is present. Treat that value as authoritative: it is the provider telling you when capacity is likely to be available. If the header is absent, fall back to capped exponential backoff with jitter. Also log the request ID and status code; those are what support needs when a 429 pattern looks wrong.

  • Retry-After is a delay, not a suggestion to retry instantly. Parse seconds; if it is an HTTP date, convert it to a delay before sleeping.

  • Do not retry 400, 401, 403, or 404 errors. They are configuration, auth, or payload problems; retrying wastes quota and delays the real fix.

  • Retry 5xx and connection timeouts with the same backoff, but treat repeated 5xx as an incident, not a rate-limit problem.

  • Log the request ID header if present, plus the model name and the request shape, on every failure.

A safe retry wrapper for DeepSeek on AiCredits

The same wrapper works with AiCredits' OpenAI-compatible endpoint. Set the base URL and use a key from your dashboard; AiCredits supports international card or PayPal top-ups, so you can test retry behavior without a Chinese phone or bank account. The example below defaults to deepseek-v4-flash, the fast model suited to high-volume paths.

import os
import random
import time

from openai import APIStatusError, OpenAI, RateLimitError

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
    timeout=60.0,
)

def retry_after_seconds(exc):
    if exc.response is None:
        return None
    value = exc.response.headers.get('retry-after')
    if not value:
        return None
    try:
        return max(0.0, float(value))
    except ValueError:
        return None

def chat_with_retry(messages, *, model='deepseek-v4-flash', max_tokens=512, max_attempts=5):
    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model=model,
                messages=messages,
                max_tokens=max_tokens,
                temperature=0.2,
            )
        except RateLimitError as exc:
            if attempt == max_attempts - 1:
                raise
            delay = retry_after_seconds(exc)
            if delay is None:
                delay = min(2 ** attempt, 30) + random.uniform(0, 0.5)
            time.sleep(delay)
        except APIStatusError as exc:
            if exc.status_code < 500 or attempt == max_attempts - 1:
                raise
            time.sleep(min(2 ** attempt, 30) + random.uniform(0, 0.5))

The wrapper does three things deliberately. It caps attempts so a bad request cannot loop forever; it honors Retry-After before falling back to capped exponential backoff; and it adds jitter so a fleet of workers does not retry in lockstep. The APIStatusError branch only retries 5xx, because a 400 will never become valid by waiting.

Use deepseek-v4-flash as the default for retry-heavy paths. It is the fast default and keeps token budgets predictable. Reserve deepseek-v4-pro for calls where the extra quality is worth the higher cost, and do not use model switching as a rate-limit workaround: if the limit is account-level, a stronger model has the same account constraints.

Control concurrency, not just retry count

Most production 429s are caused by fan-out, not by a single slow request. If you launch 50 async tasks, you have 50 in-flight requests whether or not your average requests-per-minute figure looks fine. A semaphore is the simplest fix: it bounds concurrency below your provider limit and gives the retry wrapper room to work. For batch jobs, combine the semaphore with a queue and a small delay between waves.

import asyncio
import os
import random

from openai import APIStatusError, AsyncOpenAI, RateLimitError

client = AsyncOpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
    timeout=60.0,
)

async def ask(sem, prompt, *, model='deepseek-v4-flash', max_tokens=512, max_attempts=4):
    async with sem:
        for attempt in range(max_attempts):
            try:
                return await client.chat.completions.create(
                    model=model,
                    messages=[{'role': 'user', 'content': prompt}],
                    max_tokens=max_tokens,
                )
            except RateLimitError:
                if attempt == max_attempts - 1:
                    raise
                await asyncio.sleep(min(2 ** attempt, 20) + random.uniform(0, 0.5))
            except APIStatusError as exc:
                if exc.status_code < 500 or attempt == max_attempts - 1:
                    raise
                await asyncio.sleep(min(2 ** attempt, 20) + random.uniform(0, 0.5))

async def main(prompts):
    sem = asyncio.Semaphore(4)  # keep in-flight requests below your RPM/concurrency limit
    responses = await asyncio.gather(*(ask(sem, p) for p in prompts))
    return [r.choices[0].message.content for r in responses]

if __name__ == '__main__':
    print(asyncio.run(main(['Summarize rate limiting in one sentence.'])))

The semaphore is not a token limiter, but it prevents the most common burst pattern. If you still see 429s with a semaphore set to 4, lower it or reduce max_tokens; do not add more retries. For multi-process workers, the semaphore must be shared or replaced by a distributed queue, because per-process semaphores multiply.

Budget tokens, because TPM limits are invisible

Token-per-minute limits are harder to see because prompt length varies. A request that is fine at 500 input tokens can fail at 5,000, even at the same request rate. Track usage from every response, cap max_tokens, and trim context before you send it. Cache-friendly prompt prefixes help because cache hits are cheaper and reduce effective token pressure; check current pricing at aicreditsapi.com/pricing rather than assuming a fixed rate.

  • Set max_tokens explicitly. An unbounded completion is an unbounded budget.

  • Trim retrieved context and conversation history; send summaries instead of full transcripts.

  • Batch related small prompts into one well-structured request when quality allows.

  • Use deepseek-v4-flash for classification, extraction, and routing; use deepseek-v4-pro only where the task needs it.

  • Log prompt, completion, and total tokens per request so you can see which endpoint drives token pressure.

When 429s persist: diagnose the limit you hit

SymptomLikely causeFirst action
429 on the first request after idleDaily or account quota, or a hard limitCheck dashboard and account limits; retrying will not help
429 after a burst of parallel callsRequests per minute or concurrencyAdd a semaphore or queue; reduce fan-out
429 only on long promptsTokens per minute, including outputTrim context, lower max_tokens, split the job
429 during streamingConcurrent streams or output token rateLimit concurrent streams; shorten outputs
Intermittent 429 plus 5xxProvider congestion or incidentBack off, circuit-break, and surface a retry message

Graceful degradation: what users should see

Retries are invisible to users only when they are short. After the first failed retry, decide what the user sees. For interactive chat, show a calm busy, retrying state and keep the prompt. For background jobs, queue the work and process it at lower concurrency or off-peak, when pricing is lower. For batch pipelines, checkpoint completed items so a 429 does not force a full restart.

A circuit breaker prevents a bad minute from becoming a bad hour. After a threshold of consecutive 429 or 5xx failures, stop sending new work for a short cooldown, then probe with a single request. This protects your account, your users, and the provider. It also makes incidents visible instead of hiding them behind infinite retries.

  • Honor Retry-After; otherwise use capped exponential backoff with jitter.

  • Cap attempts and total elapsed time; never retry 4xx errors that indicate auth or payload problems.

  • Bound concurrency with a semaphore or queue, including across processes.

  • Track token usage and set max_tokens; trim context before sending.

  • Use an idempotency strategy for side-effecting workflows; chat calls are usually safe to retry, but downstream writes may not be.

  • Emit metrics for 429 rate, retry count, and latency; alert on sustained 429s.

FAQ

What does a 429 from an LLM API actually mean?

It means a limit was exceeded right now: requests, tokens, concurrency, or quota. It is not a malformed prompt. Read the error body and Retry-After before deciding whether to retry, queue, or reduce request size.

Should I retry a 429 immediately?

No. Immediate retries add load and usually produce more 429s. Wait for Retry-After if provided; otherwise use exponential backoff with jitter and a cap. If 429s continue after a few attempts, change the workload shape instead of retrying harder.

Does deepseek-v4-pro avoid rate limits?

No. Model choice changes quality and cost, not your account's rate-limit dimensions. deepseek-v4-flash is the better default for high-volume retry paths; deepseek-v4-pro is for tasks that need stronger output and can tolerate higher cost.

How do I handle 429s in a streaming app?

Treat each stream as one in-flight request for concurrency purposes, limit the number of simultaneous streams, and keep a retry path for failures that occur before output is consumed. If a stream fails mid-output, resume from a checkpoint or ask the user to retry rather than silently duplicating the request.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×