Most "the API is flaky" tickets are really client-side retry bugs. A loop that retries a 400 five times, a stream that restarts mid-answer and duplicates text, a 429 storm caused by ten workers waking up at the same millisecond — none of those are the provider's fault, and all of them cost you tokens on every attempt.
This guide covers the DeepSeek-compatible error envelope, which status codes are worth a second attempt, and two runnable Python patterns: one for normal chat completions, one for streaming, where naive retries are actively harmful.
The error envelope, and why the status code isn't enough
The API is OpenAI-compatible, so failures come back with an HTTP status plus a JSON body of the shape {"error": {"message": ..., "type": ..., "code": ...}}. The status tells you the category; the code field tells you the specific cause. Two very different problems can share a 429: "you are sending too many requests right now" (transient — retry) and "your account has no balance left" (permanent — top up). Retrying the second one just burns time.
Always read
error.codebefore branching. Treat the status code as a bucket and thecodeas the actual decision input. If you only build on status codes, you will eventually retry a billing error until your request deadline expires.
| Status | Typical meaning | Retry? | Check first |
|---|---|---|---|
| 400 | Malformed body, bad tool schema, context too long | No | Payload shape, message history size |
| 401 | Missing, malformed, or revoked API key | No | AICREDITS_API_KEY env var, key status |
| 402 / 403 | Billing, quota, or key permission problem | No | Account balance, key scope |
| 404 | Wrong base_url path or unknown model id | No | base_url and exact model string |
| 409 | Conflicting state for the same resource | Yes | Usually transient |
| 422 | Semantically invalid parameter values | No | Param types and ranges |
| 429 | Rate limit (or, sometimes, quota exhausted) | Yes | Read error.code; then concurrency |
| 500 / 502 / 503 / 504 | Upstream or gateway failure | Yes | Nothing — just back off |
Sort every failure into one of three buckets
Retry with backoff: 408, 409, 429 (rate-limit variant), 500, 502, 503, 504, plus connection resets and client timeouts. Nothing about the request needs to change.
Fix the request: 400, 401, 403, 404, 422. Retrying is pure waste — a 400 will be a 400 forever. Log the
messagefield and fail fast, because the fix lives in your code or your account, not in a delay.Degrade: 503s that persist past your retry budget, or 429s you cannot shed. Return a cached answer, a shorter
deepseek-v4-flashresponse, or an honest error — but never spin forever behind a user-facing spinner.
A runnable retry wrapper
Disable the SDK's built-in retries (max_retries=0) and own the policy yourself. Otherwise the SDK's internal backoff and yours stack, and a 503 can turn into dozens of silent attempts you never see in your logs.
Python 3.10+; requires pip install openai and AICREDITS_API_KEY in the environment.
import os
import random
import time
from openai import APIConnectionError, APIStatusError, APITimeoutError, OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
timeout=60.0,
max_retries=0, # we own the retry policy
)
RETRYABLE = {408, 409, 429, 500, 502, 503, 504}
def backoff_delay(attempt, exc=None, cap=30.0):
"""Honor Retry-After when present, else full-jitter exponential backoff."""
if isinstance(exc, APIStatusError) and exc.response is not None:
raw = exc.response.headers.get("retry-after")
if raw:
try:
return min(float(raw), 60.0)
except ValueError:
pass
return random.uniform(0, min(cap, 2 ** attempt))
def chat(messages, model="deepseek-v4-flash", max_attempts=5, **params):
for attempt in range(max_attempts):
try:
return client.chat.completions.create(
model=model, messages=messages, **params
)
except APIStatusError as exc:
if exc.status_code not in RETRYABLE or attempt == max_attempts - 1:
raise
time.sleep(backoff_delay(attempt, exc))
except (APITimeoutError, APIConnectionError) as exc:
if attempt == max_attempts - 1:
raise
time.sleep(backoff_delay(attempt, exc))
reply = chat([{"role": "user", "content": "Summarize what a 429 means."}])
print(reply.choices[0].message.content)
Full jitter beats fixed delays, and Retry-After beats both
random.uniform(0, ceiling) is full jitter: it spreads retries across the whole window instead of lining them up. With hundreds of workers, a fixed 1s/2s/4s ladder produces synchronized waves that hit the rate limiter together and retry together forever. Jitter breaks the convoy.
When the response carries a Retry-After header, use it verbatim (capped at something sane) — the server knows when it will be ready better than your backoff formula does.
Cap total attempts at four or five, and add a wall-clock deadline across the whole call. A request that has spent 90 seconds retrying has already failed from the user's point of view.
Streaming is where retries actually break things
A streamed response that dies after 200 tokens cannot be safely restarted: you will re-emit the first 200 tokens to the user and pay for them twice. The rule is simple — retry only if zero content has been emitted; otherwise surface the partial result and resume with a follow-up request.
def stream_chat(messages, model="deepseek-v4-flash", max_attempts=4, **params):
"""Retries only before the first chunk is emitted."""
for attempt in range(max_attempts):
emitted = 0
try:
stream = client.chat.completions.create(
model=model, messages=messages, stream=True, **params
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
emitted += 1
yield chunk.choices[0].delta.content
return
except (APIStatusError, APITimeoutError, APIConnectionError) as exc:
status = getattr(exc, "status_code", None)
retryable = status is None or status in RETRYABLE
if emitted:
raise RuntimeError(
f"stream broke after {emitted} chunks - resume, do not restart"
) from exc
if not retryable or attempt == max_attempts - 1:
raise
time.sleep(backoff_delay(attempt, exc))
for token in stream_chat([{"role": "user", "content": "Explain backoff jitter."}]):
print(token, end="", flush=True)
Retry the request, never the side effect. If a failed call triggered a database write, an email, or a tool invocation, a retry is a second mutation — deduplicate on your own request ID before you re-send.
Idempotency, logging, and the cheap-retry trick
Generate a UUID per logical request, log it with every attempt, and key any side effects on it. That single habit turns "did the retry double-charge the customer?" into a two-second query.
Log status code,
error.code, attempt number, and delay for every failure. A rising 429 rate is a concurrency bug in your app, not a provider incident — you cannot see that without per-attempt data.Repeated retries of an identical prompt prefix are friendlier to prompt caching than fresh prompts, so the marginal cost of a retry is lower than the first call — but it is never free. Budget your attempts accordingly, and check aicreditsapi.com/pricing for how caching, off-peak usage, and the pro model are billed.
Prefer
deepseek-v4-flashin the retry loop. It is the fast default and keeps tail latency low; reservedeepseek-v4-profor calls that genuinely need it, and avoid retrying the more expensive model on a persistent 503 — a labeled fallback to flash beats a hung request.
Quick answers
FAQ
No. A 400 means the request itself is invalid — a malformed tool schema, a message history that exceeds the context window, or an unsupported parameter. The same body will fail identically next time. Read error.message, fix the payload, then send once more.
Four or five, with a total wall-clock deadline of roughly 60-90 seconds. Beyond that the user has already given up, and you are just consuming your own capacity and tokens.
Because it stacks with your own loop. The SDK retries silently, your wrapper retries the SDK, and a single 503 can become a burst of attempts during exactly the window when the server is struggling. Set max_retries=0 and centralize the policy.
You pay for the tokens processed on each attempt, but identical prompt prefixes benefit from caching, which is billed more cheaply than fresh input. Retries are therefore discounted, not free — which is another reason to cap attempts rather than loop indefinitely.
For idempotent, read-only calls, yes — falling back from deepseek-v4-pro to deepseek-v4-flash on repeated 503s keeps the experience alive. Label the response as degraded so downstream logic and users know quality may differ.