AiCredits
Production Reliability

How to Handle DeepSeek API Errors Gracefully in Production

A practical playbook for DeepSeek API errors in production: error classification, jittered retries, stream recovery, model fallbacks, and safe degradation.

Published 2026-09-27 Updated 2026-09-27 8 min

Why DeepSeek API Errors Hurt Differently in Production

In a notebook, an API error is a red traceback and a re-run. In production it is a support ticket, a half-rendered answer on a user's screen, and a retry storm that makes the original blip worse. The DeepSeek API is easy to call — it speaks the OpenAI wire format, so the standard OpenAI SDK works unchanged — which is exactly why so many teams ship it with no error strategy at all.

The failures that cost you money are rarely the loud ones. A 401 is obvious and fixed in a minute. The painful ones are a stream that dies at 80% of an answer, a timeout that leaves you unsure whether the work completed, and a retry loop that converts a short upstream hiccup into a self-inflicted outage.

If you are building from outside China and need DeepSeek credits without a Chinese phone number or bank account, that is what AiCredits is for: top up with a card or PayPal, then point the OpenAI SDK at https://api.aicreditsapi.com/v1. Every example below uses deepseek-v4-flash, the fast default. deepseek-v4-pro is the stronger, costlier option for when output quality matters more than speed.

Step 1: Classify the Error Before You Retry Anything

Most incidents start with an over-broad except clause. Catching everything and retrying treats a permanently broken request — a bad model name, a revoked key, an input that exceeds the context window — as if it were a temporary network fault. You then spend thirty seconds discovering what one log line would have told you instantly. Classify first:

SignalWhat it usually meansCorrect response
BadRequestError (400)Malformed payload, unsupported parameter, input too longDo not retry. Fix the request or trim the input.
AuthenticationError (401) / PermissionDeniedError (403)Key missing, revoked, or lacking accessDo not retry. Fail fast and alert; retries only burn time.
NotFoundError (404)Unknown model name or endpoint pathDo not retry. Check your model string.
RateLimitError (429)Too many requests or too much concurrencyRetry with backoff and jitter, honoring Retry-After when present.
InternalServerError / 502 / 503 / 504Transient upstream or gateway problemRetry with backoff, with a capped attempt count.
APITimeoutErrorNo response within your client timeoutRetry once. If it repeats, change strategy rather than hammering.
APIConnectionErrorDNS, TLS, or socket failureRetry with backoff. If persistent, check egress and proxies.

Step 2: Retry With Jitter and a Time Budget

Once you know which errors are retryable, the policy itself matters more than people expect. Fixed delays and pure exponential backoff share a flaw: every client that failed at the same moment retries at the same moment, and your fleet re-synchronizes into repeated spikes. Add jitter, and cap the total wall-clock budget rather than only the attempt count. A request that has already spent two minutes retrying is not a request a user is still waiting for.

import os
import random
import time
import logging

import openai
from openai import OpenAI

logger = logging.getLogger(__name__)

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    timeout=60.0,   # per-request wall clock
    max_retries=0,  # we own the retry policy
)

RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}


def complete(messages, *, model="deepseek-v4-flash", max_attempts=5, **kwargs):
    """Call DeepSeek with bounded, jittered retries."""
    deadline = time.monotonic() + 120  # total budget for this call
    last_error = None

    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model=model, messages=messages, **kwargs
            )
        except openai.APIStatusError as exc:
            # 400/401/403/404 will never succeed on a retry.
            if exc.status_code not in RETRYABLE_STATUS:
                raise
            last_error = exc
            retry_after = exc.response.headers.get("retry-after")
        except openai.APIConnectionError as exc:
            # APITimeoutError subclasses this, so it is covered here too.
            last_error = exc
            retry_after = None

        remaining = deadline - time.monotonic()
        if remaining <= 1.0 or attempt == max_attempts - 1:
            raise last_error

        delay = float(retry_after) if retry_after else min(2 ** attempt, 20) * (0.5 + random.random())
        delay = min(delay, remaining)
        logger.warning("attempt %d failed; retrying in %.1fs", attempt + 1, delay)
        time.sleep(delay)

Two details are doing quiet work there. Setting max_retries=0 on the client disables the SDK's built-in retries so you do not end up with two layers of backoff multiplying each other. The deadline guarantees a slow-moving outage fails in bounded time instead of holding a worker for minutes.

One caveat worth designing around: a retry is a brand-new request. If the original call actually completed and only the response was lost in transit, you will be charged for work you never saw. Keep your own request identifier, log it on every attempt, and dedupe downstream so a retried generation does not get applied twice.

Step 3: Decide What a Half-Finished Stream Means

Streaming breaks the tidy assumption that a request either succeeds or fails. Once the first token reaches the user, a dropped connection is a third state: partial success. Blindly restarting the call duplicates text the user has already read. Doing nothing leaves a truncated answer on screen with no explanation. Neither is acceptable, so make the third state explicit.

import os
import openai
from openai import OpenAI

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


class StreamInterrupted(RuntimeError):
    """Raised when a stream dies after tokens have already been emitted."""

    def __init__(self, partial_text):
        super().__init__("stream interrupted")
        self.partial_text = partial_text


def stream_tokens(messages, *, model="deepseek-v4-flash", timeout=60.0):
    buf = []
    try:
        stream = client.chat.completions.create(
            model=model,
            messages=messages,
            stream=True,
            timeout=timeout,
        )
        for chunk in stream:
            if not chunk.choices:
                continue  # usage-only or keep-alive frame
            delta = chunk.choices[0].delta.content
            if delta:
                buf.append(delta)
                yield delta
    except (openai.APIConnectionError, openai.APIStatusError) as exc:
        # The caller still receives the text produced so far.
        raise StreamInterrupted("".join(buf)) from exc

The caller decides what partial success means. For a chat interface, the sensible default is to keep the partial answer, mark it visibly as incomplete, and offer a regenerate button rather than overwriting what the user already read. For anything feeding a database, a queue, or a downstream parser, discard the partial text and retry the whole call — half an answer written to a table is worse than no answer at all.

Step 4: Timeouts and Model Escalation

Give every request an explicit timeout budget: a connect timeout for the socket, a read timeout for token flow, and an overall wall-clock cap. Without them, a stalled connection can pin a worker indefinitely, and under load that is how a partial degradation becomes a full outage. Once timeouts are in place, escalation becomes safe to automate.

def complete_with_escalation(messages, **kwargs):
    """Fast path first; escalate to the stronger model only if it fails."""
    try:
        return complete(messages, model="deepseek-v4-flash", **kwargs)
    except openai.APIError as exc:
        logger.error("flash path failed (%s); escalating", type(exc).__name__)
        return complete(messages, model="deepseek-v4-pro", max_attempts=2, **kwargs)

Escalating to deepseek-v4-pro is a useful safety valve but a poor default. Pro costs more than flash, so gate it deliberately: escalate for user-facing, quality-sensitive jobs, and stay on flash for bulk or background work. Billing is usage-based, off-peak requests cost less, and cache hits are cheaper than fresh input — so read the current rates at aicreditsapi.com/pricing before wiring an automatic escalation path into a high-volume service.

Step 5: Degrade Instead of Merely Failing

  • Circuit breaker: after several consecutive failures against the same endpoint, stop sending traffic for a cooldown instead of burning retries into a wall.

  • Queue non-interactive work: batch jobs should be retried later by a worker, never held open inside a user's request thread.

  • Serve something useful: for repeated questions, a cached or retrieval-only answer beats an error page.

  • Fail honestly in the UI: a spinner that never resolves is worse than a plain message that the model is busy.

  • Alert on error rate, not error count: one failure in twenty requests is noise; a sustained few-percent failure rate across thousands is an incident.

Test the Error Path Before It Tests You

Error handling is usually the least-exercised code you own, because the failure cases never happen on your machine. Inject them on purpose: wrap your client in a thin shim whose create() raises, in order, a RateLimitError, an APITimeoutError, and then a success, and assert that your caller produced exactly one result and slept between attempts. Ten lines of that test is worth more than any amount of retry configuration.

It also helps to have a second reader. AiCredits' code linting tools flag broad except blocks and swallowed exceptions — the patterns that quietly turn a handled failure into an invisible one — so they get caught in review rather than at 3am.

FAQ

Should I retry a 429 immediately?

No. A 429 means you are already sending traffic faster than the endpoint wants. Retrying instantly deepens the problem. Back off exponentially with jitter, honor a Retry-After header if one is returned, and consider lowering your concurrency for that endpoint.

Is it safe to retry a request that timed out?

Usually yes, but treat it as a brand-new request. The original may have completed even though you never saw the response, which means you can be billed for work you discarded. Track your own request ID and dedupe on the consumer side.

How many retry attempts is too many?

Judge it by time budget rather than count. If a request has been retrying longer than a user would plausibly wait, more attempts only consume capacity. Cap both the attempt count and the total elapsed time.

Does streaming change my error handling?

Yes, substantially. A stream can fail after partial output, so you need a third state between success and failure. Capture the tokens you already emitted, raise a distinct exception carrying them, and let the caller decide whether to keep or discard the partial text.

Can I reuse existing OpenAI SDK code with DeepSeek?

Yes. AiCredits exposes an OpenAI-compatible endpoint, so the standard SDK works unchanged — set base_url to https://api.aicreditsapi.com/v1, pick deepseek-v4-flash or deepseek-v4-pro, and your existing error classes and retry logic carry over.

The Bottom Line

Graceful error handling is not a library you install; it is three decisions made deliberately. Classify errors so you only retry what can actually succeed. Bound every retry in time as well as attempts, with jitter to keep your fleet from re-synchronizing. And decide in advance what a partial stream or an unavailable model means for the person on the other end of the request. Do those three things and most DeepSeek incidents shrink from outages into log lines.

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 ×