AiCredits
Error Handling

DeepSeek "request quota exhausted": What the Error Means and How to Fix It

Why DeepSeek returns 'request quota exhausted', how to tell a rate cap from an empty balance, plus retry, backoff and batching code that actually fixes it.

Published 2026-11-08 Updated 2026-11-08 8 min

What "request quota exhausted" is actually telling you

The first thing to internalise: this is a gate, not a crash. Your request was rejected at the edge of the API — before or instead of the model doing any work — which is why the response arrives almost instantly and why the content of your prompt is irrelevant to whether it succeeds.

That distinction matters because the fix is rarely "retry harder." The same wording gets attached to at least three different underlying conditions, and each has a different remedy: a per-window request cap (usually HTTP 429), a drained account balance (usually 402, or a message mentioning insufficient balance), and a per-key concurrency ceiling that only fires when you run calls in parallel.

The phrase "This turn failed" is a clue that the message bubbled up through an agent loop or chat wrapper rather than a raw SDK call. Your wrapper caught the rejection and reported it as a failed turn, which makes a billing or scheduling problem look like a model failure. Strip the wrapper away and read the status code and error body — that is where the real answer lives.

What you seeMost likely causeWhat to do
"request quota exhausted" + HTTP 429Per-minute or per-hour request cap on the keyBack off with jitter, add a client-side rate limiter
HTTP 402 / "insufficient balance"Credits spentTop up; check current rates before resizing the job
401 / "invalid api key"Wrong key, revoked key, or wrong base_urlVerify both; a stale key often looks like a billing error
Errors only in async/parallel pathsConcurrency cap on the accountWrap calls in a semaphore
Long silence, then a wall of 429sSynchronised retry storm from your workersFull jitter + a cap on attempts

Retry logic that doesn't make the outage worse

Naive retries convert a short rate window into a long outage. If ten workers all sleep exactly two seconds and retry in phase, you rebuild the same burst that tripped the cap, just later. The fix is exponential backoff with full jitter, honouring the Retry-After header when the gateway sends one, and a hard cap on attempts so a dead key fails loudly instead of spinning forever.

Equally important: separate a soft failure (rate window, transient 5xx) from a hard one (balance gone, key revoked). A soft failure should be retried and, if it keeps failing, queued for later. A hard failure should surface to your logs immediately.

import random, time
from openai import OpenAI, APIStatusError, APIConnectionError

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
)

class QuotaExhausted(RuntimeError):
    """The account balance (not the rate window) is the problem."""


def _text(err):
    body = getattr(err, "body", None) or {}
    if isinstance(body, dict):
        inner = body.get("error") if isinstance(body.get("error"), dict) else body
        if inner.get("message"):
            return str(inner["message"]).lower()
    return str(getattr(err, "message", err)).lower()


def _retry_after(err):
    try:
        return float(err.response.headers.get("retry-after"))
    except Exception:
        return None


def _backoff(attempt, cap=30):
    return min(2 ** attempt, cap) + random.uniform(0, 1)


def complete(messages, model="deepseek-v4-flash", max_attempts=6,
             quota_is_retryable=False, **kwargs):
    for attempt in range(1, max_attempts + 1):
        try:
            return client.chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except APIConnectionError:
            if attempt == max_attempts:
                raise
            time.sleep(_backoff(attempt))
        except APIStatusError as e:
            msg = _text(e)
            quota_like = any(
                k in msg for k in ("quota", "insufficient", "balance", "billing")
            )
            if quota_like and not quota_is_retryable:
                raise QuotaExhausted(msg) from e
            if e.status_code in (401, 402, 403) and not quota_like:
                raise QuotaExhausted(msg) from e
            if quota_like or e.status_code == 429 or e.status_code >= 500:
                if attempt == max_attempts:
                    raise
                time.sleep(_retry_after(e) or _backoff(attempt, cap=60))
                continue
            raise
    raise RuntimeError("retries exhausted")

The quota_is_retryable flag exists because some gateways reuse the same wording for a short-window cap as for an empty balance. If you know your credits are funded — you topped up this morning, nothing else is running — flip it to True and let the backoff do its job. If you're unsure, leave it False: failing fast with a typed exception beats a loop that never terminates.

A client-side token bucket, so you never trip the cap

The cheapest fix is to never send more requests than you're allowed, on purpose, with headroom left for retries. A token bucket is a dozen lines and it smooths a fan-out job into a steady drip. Size it below the cap you believe you have — if the ceiling is fuzzy, start conservative and raise it once your logs are clean for a full window.

import threading, time


class TokenBucket:
    """Block until a request slot is free. One bucket per process, per key."""

    def __init__(self, rate_per_min, burst=None):
        self.capacity = float(burst or rate_per_min)
        self.tokens = self.capacity
        self.rate = rate_per_min / 60.0
        self.updated = time.monotonic()
        self.lock = threading.Lock()

    def take(self, n=1):
        while True:
            with self.lock:
                now = time.monotonic()
                self.tokens = min(
                    self.capacity,
                    self.tokens + (now - self.updated) * self.rate,
                )
                self.updated = now
                if self.tokens >= n:
                    self.tokens -= n
                    return
                wait = (n - self.tokens) / self.rate
            time.sleep(min(wait, 2.0))


bucket = TokenBucket(rate_per_min=50, burst=10)

for prompt in prompts:
    bucket.take()
    resp = complete(
        [{"role": "user", "content": prompt}],
        model="deepseek-v4-flash",
        max_tokens=512,
    )
    print(resp.choices[0].message.content)

Batching: one request where you used to send twenty

Most quota walls are self-inflicted. A loop that calls the API once per row, per file, or per comment burns request quota on work that could be done in a twentieth of the calls. Batch twenty items into a single prompt and your request count drops by roughly that factor; token spend rises modestly because the instructions are repeated once instead of twenty times, and you actually save on the shared overhead.

The tradeoff is real: bigger prompts are harder to parse, one bad item can poison a whole batch, and you need a strict output contract with stable ids so you can re-align results. The system prompt below is written to be boring and explicit for exactly that reason.

import json

SYSTEM = (
    "You receive a JSON object with an 'items' array. Return a JSON object "
    "{\"results\": [{\"id\": <id>, \"summary\": <one sentence>}]} covering "
    "every item exactly once. No markdown fences, no commentary, no extra keys."
)


def summarize(items, batch_size=20):
    out = []
    for start in range(0, len(items), batch_size):
        chunk = items[start:start + batch_size]
        payload = json.dumps(
            {"items": [{"id": start + i, "text": t} for i, t in enumerate(chunk)]}
        )
        resp = complete(
            [
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": payload},
            ],
            model="deepseek-v4-flash",
            max_tokens=1024,
        )
        raw = resp.choices[0].message.content.strip()
        raw = raw.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
        out.extend(json.loads(raw)["results"])
    return out

Make every token go further

  • Route bulk work to deepseek-v4-flash and reserve deepseek-v4-pro for the calls that genuinely need stronger reasoning. Pro costs more per token, so using it for classification or summarisation quietly drains a balance.

  • Keep the system prompt byte-identical at the front of the messages array. A stable prefix lets prefix caching do its job, and cache hits are billed more cheaply than fresh input — which stretches a fixed balance further without changing your code.

  • Always set max_tokens. An agent that forgets it can produce an enormous completion on one rambling turn, and that single call can be what pushes you over the edge.

  • Trim history with a rolling summary instead of resending forty turns. Long context is the most common reason a job that worked in testing suddenly stops fitting.

  • Use streaming when you might stop early — you can break out of the loop once you have enough, rather than generating the whole answer. How partial generations are billed depends on the gateway, so read the pricing page rather than assuming.

Where the quota actually comes from

A surprising number of "quota exhausted" tickets are not rate problems at all — they are top-up problems. The official DeepSeek platform is built around Chinese payment rails, and plenty of international developers end up holding a key they cannot recharge with a normal card. The result is a 429-shaped error on day two of a project that never changed its code.

AiCredits sells DeepSeek credits payable with an international card or PayPal, no Chinese phone number or bank account required, behind the same OpenAI-compatible endpoint you're already using — https://api.aicreditsapi.com/v1. Billing is usage-based: off-peak usage costs less than peak, cache hits cost less than fresh input, and deepseek-v4-pro costs more than deepseek-v4-flash. Current rates live on aicreditsapi.com/pricing; check them before you size a batch job rather than after it dies. The same account also covers our code-linting tools if you want to catch malformed model output before it ships.

Qualitative budgeting beats guesswork here. If a job is worth running at all, it is worth estimating its token cost first, choosing flash or pro deliberately, and setting a request ceiling in your own code so the answer arrives from your scheduler instead of from an error message.

A pre-flight checklist before you blame the API

  • Log the status code and full response body, not just the message string. "quota" on its own is ambiguous; 429 versus 402 is not.

  • Confirm the key and base_url are the ones you think they are. A stale key from a deleted project frequently looks like a billing failure.

  • Check whether failures cluster on a time boundary — every hour at :00 is a window reset, not an empty account.

  • Count requests per minute from your own metrics, not from a provider dashboard that may lag.

  • If errors appear only on the parallel code path, it is concurrency: add an asyncio.Semaphore or a worker pool sized to your cap.

  • If errors appear after a quiet period followed by a burst, the problem is queue design — smooth the burst with the token bucket above.

A quota error is usually a scheduling problem wearing an API error's clothes. Fix the schedule, not the prompt.

FAQ

Does "request quota exhausted" mean I've run out of money?

Not necessarily. It can mean the short-window request cap was hit while your balance is perfectly healthy. Read the HTTP status code: 429 points at the rate window, 402 or an "insufficient balance" message points at the account.

Is this the same as a rate limit?

Sometimes. The wording is often reused across both conditions, which is why classifying the error by status code and by the words in the body — as the retry wrapper above does — is more reliable than trusting a single fixed phrase.

Will switching to deepseek-v4-pro or deepseek-v4-flash fix it?

No — the model does not change your account's request quota. It does change token cost: flash is the cheaper default and stretches a fixed balance further, while pro costs more and should be reserved for harder calls.

Does streaming avoid the error?

No. Streaming changes how quickly you see output and lets you stop generating early, but it does not give you more requests. Batching and rate limiting are what actually reduce your request count.

My balance is fine and I still get the error — what now?

Look for a shared key. Multiple services or teammates using one key share its concurrency and rate ceiling, so one noisy loop starves everything else. Give each workload its own key, or route everything through a single limiter.

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 ×