You shipped the feature, the first calls worked, and then the logs filled up with 502 Bad Gateway or a client-side transport failed. Nothing in your prompt changed. That is the first clue: a 502 is a statement about the path between your process and the model, not about the words you sent.
The second clue is which of the two errors you got. A 502 means an HTTP response came back — just the wrong one. transport failed usually means no HTTP response arrived at all: the socket, the TLS handshake, or a proxy hop fell over before the gateway could answer. The symptoms look identical in a log viewer, but the fixes barely overlap — and conflating them is why teams end up retrying requests that were never going to succeed.
What a 502 actually means on the DeepSeek API path
Every call to an OpenAI-compatible endpoint makes at least three hops: your process, the edge or gateway that terminates TLS, and the model backend behind it. A 502 Bad Gateway means the gateway asked upstream for an answer and did not get one it could use. It says nothing about whether your prompt was good, and almost nothing about whether your application code is correct.
Two details tell you where to look. First, the body: if the 502 arrived as an HTML page, a proxy or gateway generated it and your request was cut before reaching the application. If it arrived as a JSON error object, it reached the application layer and the message is worth reading. Second, the pattern: failures on every request point at the network path or credentials; failures only on long or large requests point at timeouts and payload size, which are yours to fix.
transport failed is a different animal. It almost always means the client library never received an HTTP status at all. Retrying is still correct, but the root cause lives on your side of the wire.
Triage: five checks that find the cause in minutes
Reproduce outside your app. One
curlcall rules out your framework, your async plumbing, and your middleware in a single step.Read the body, not just the status. Gateway HTML and an application JSON error have completely different owners.
Compare a tiny request against your real one. Both fail → network. Only the big one fails → timeouts or payload size.
Check your egress.
env | grep -i proxy, VPN split-tunnelling, and container DNS cause moretransport failederrors than any provider incident.Check timing. Bursts that line up with a cron job or a queue-worker spike usually mean rate limiting or retry amplification, not a dead gateway.
curl -sS -w '\nHTTP %{http_code} | total %{time_total}s | connect %{time_connect}s\n' \
https://api.aicreditsapi.com/v1/chat/completions \
-H "Authorization: Bearer $AICREDITS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"ping"}],"max_tokens":8}'
If the eight-token request succeeds and your real call still fails, the problem is request shape. If both fail, jump to the network section — no amount of retry tuning will fix a broken TLS path.
Know which failures are retryable — and which never will be
| Error | What it usually means | Retry? | First move |
|---|---|---|---|
| 502 Bad Gateway | The edge got no usable response from upstream | Yes, with backoff | Compare a small request vs. your real payload |
| 503 Service Unavailable | Upstream saturated or briefly unavailable | Yes — honour Retry-After | Slow down, reduce concurrency |
| 504 Gateway Timeout | The answer took longer than the gateway allows | Yes, but change the request | Stream it, lower max_tokens, split the task |
| 429 Too Many Requests | You are over the rate limit for your tier | Yes, after the given delay | Add a token-bucket limiter |
| 400 / 422 | Bad payload: unknown model, malformed messages, context too long | No | Log the response body verbatim and fix the request |
| 401 / 403 | Missing or invalid key, or no available balance | No | Rotate the key, check the dashboard |
| Transport failed / connection reset | Socket died before any status arrived — DNS, TLS, proxy, or a stale keep-alive reuse | Yes | Test with curl outside the app, then check proxy settings |
Retrying a 4xx is the most common self-inflicted incident in LLM code. A malformed message array or a retired model name will fail identically five times, five seconds later, while your user waits.
Fix 1: classify the exception before you retry anything
The OpenAI Python SDK already separates connection-level failures from HTTP failures, but the class hierarchy hides a trap: APITimeoutError subclasses APIConnectionError, so a naive except APIConnectionError swallows timeouts into the wrong bucket and you never discover that your read timeout is simply too short.
import os
import openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
timeout=60.0,
max_retries=0, # we run our own retries so every failure gets logged
)
def classify(exc: Exception) -> str:
# APITimeoutError subclasses APIConnectionError, so test it first
if isinstance(exc, openai.APITimeoutError):
return "timeout" # read deadline hit: retry, but consider streaming
if isinstance(exc, openai.APIConnectionError):
return "transport" # DNS/TLS/proxy/socket: no status code ever arrived
if isinstance(exc, openai.APIStatusError):
if exc.status_code in (502, 503, 504):
return "gateway" # retry with backoff
if exc.status_code == 429:
return "rate_limit"
return "request" # 4xx: only fixing the payload helps
return "unknown"
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "ping"}],
max_tokens=8,
)
print("ok:", resp.choices[0].message.content)
except Exception as exc:
print("class :", classify(exc))
print("type :", type(exc).__name__)
print("message:", str(exc)[:300])
Fix 2: jittered backoff that honours Retry-After
Once you can classify, write exactly one retry loop and keep every call site out of it. Set max_retries=0 on the client so retries happen in one place and every attempt is loggable — otherwise the SDK's internal retries hide the very 502s you are trying to count. Add full jitter, a random multiplier per attempt, so a fleet of workers that fail together does not come back in lockstep and hammer the gateway a second time.
Two rules make this production-safe: cap the wait, and stop after a handful of attempts. If a dependency is down for minutes, fast failure plus a queued retry beats pinning a request thread open.
import os
import random
import time
import openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
timeout=60.0,
max_retries=0,
)
RETRYABLE = {429, 502, 503, 504}
def retry_after(exc: openai.APIStatusError) -> float | None:
headers = getattr(getattr(exc, "response", None), "headers", {}) or {}
raw = headers.get("retry-after")
if not raw:
return None
try:
return max(0.0, float(raw))
except ValueError:
return None
def backoff(attempt: int) -> float:
return min(30.0, (2 ** attempt) * random.uniform(0.5, 1.0))
def chat(messages, model="deepseek-v4-flash", attempts=5, **kwargs):
last = None
for i in range(attempts):
try:
return client.chat.completions.create(
model=model, messages=messages, **kwargs
)
except openai.APIStatusError as exc:
if exc.status_code not in RETRYABLE:
raise # 400/401/422 will fail identically every time
last = exc
time.sleep(retry_after(exc) or backoff(i))
except (openai.APITimeoutError, openai.APIConnectionError) as exc:
last = exc
time.sleep(backoff(i))
raise last
if __name__ == "__main__":
print(chat([{"role": "user", "content": "ping"}], max_tokens=8)
.choices[0].message.content)
Fix 3: stop long answers from turning into 502s and 504s
If failures only appear on long generations, you are probably hitting a gateway response deadline or an idle-read timeout, not a broken service. A non-streamed request looks completely silent to every proxy between you and the model until the whole answer is ready — which is precisely the situation gateways are built to cut off.
Streaming changes the physics of the request: bytes keep moving while the model generates, so an idle socket never trips. It also lets you fail fast, because a stream that dies mid-answer can be retried from the last complete segment instead of redoing the whole job.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
timeout=120.0,
max_retries=0,
)
def stream_answer(prompt: str, model: str = "deepseek-v4-flash") -> str:
parts = []
with client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
stream=True,
) as stream:
for chunk in stream:
if not chunk.choices:
continue # trailing usage-only chunk
delta = chunk.choices[0].delta.content
if delta:
parts.append(delta)
print(delta, end="", flush=True)
text = "".join(parts)
if not text:
raise RuntimeError("empty stream - count it as a failed attempt and retry")
return text
if __name__ == "__main__":
out = stream_answer("Explain TCP backpressure in 200 words.")
print(f"\n\nreceived {len(out)} characters")
If you cannot stream — some batch pipelines cannot — lower max_tokens, split the task into stages, and raise the read timeout explicitly. A 60-second default read timeout is generous for a short classification call and far too small for a multi-page summary.
Fix 4: kill "transport failed" at the network layer
Persistent transport errors are rarely the model. In rough order of likelihood: a proxy that mishandles HTTP/2, a container with a broken resolver, a VPN that drops long-lived connections, or a keep-alive socket reused after the server already closed it. You can test the first three from a shell before touching code.
import os
import httpx
from openai import OpenAI
# trust_env=True makes HTTPS_PROXY / NO_PROXY take effect.
# http2=False avoids h2 negotiation problems behind some middleboxes.
http_client = httpx.Client(trust_env=True, http2=False)
client = OpenAI(
base_url="https://api.aicreditsapi.com/v1",
api_key=os.environ["AICREDITS_API_KEY"],
http_client=http_client,
# granular timeouts: fail fast on connect, be patient on read
timeout=httpx.Timeout(connect=10.0, read=180.0, write=30.0, pool=10.0),
max_retries=0,
)
if __name__ == "__main__":
r = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "ping"}],
max_tokens=8,
)
print(r.choices[0].message.content)
curl -4versuscurl -6— if only IPv6 fails, your container has a broken v6 route and the SDK's happy-eyeballs fallback is masking it intermittently.openssl s_client -connect api.aicreditsapi.com:443 -servername api.aicreditsapi.com— a handshake failure here means TLS interception on your corporate network.env | grep -i proxy— anHTTPS_PROXYpointing at a decommissioned proxy is the classic Docker and CI failure, and it never reproduces on a laptop.Container networks with a reduced MTU can stall large TLS records; test with a smaller payload before blaming the API.
Reuse one client instance per process. Creating a provider client inside a request handler exhausts the connection pool and produces connection resets that look exactly like transport failures.
Fix 5: protect the rest of the stack from retry storms
Cap concurrency per API key and give the whole service a shared retry budget, not a per-request one.
Add a short circuit breaker: after several consecutive gateway errors, fail fast for a few seconds instead of queueing more doomed attempts.
Log the status code, the first few hundred characters of the body, and the request ID on every failure — that trio turns "it's flaky" into a fixable ticket.
Make side effects idempotent before you retry them; a call that succeeded upstream but timed out locally will otherwise duplicate work.
Test the failure path on purpose: point the client at something that returns 502 and confirm your retry, logging, and fallback all behave.
A 502 is a statement about the path, not the prompt. Fix the prompt and you will still see it tomorrow.
Choosing a model while you stabilise
Keep deepseek-v4-flash as the default during an incident: it is the faster, cheaper option, and short requests are far less likely to trip gateway deadlines. Reserve deepseek-v4-pro for calls that genuinely need more reasoning, and route to it deliberately rather than as a panic fallback — both models sit behind the same edge, so switching models does not fix a 502. Current rates for both are on aicreditsapi.com/pricing, and the request log in your AiCredits dashboard is the quickest way to confirm whether failing calls are reaching the model at all.
FAQ
No. A 502 means something between you and the model failed. If both tiny and large requests fail, look outside your code — network, proxy, credentials. If only large or long-running requests fail, the cause is request shape and timeouts, which you control.
Three to five attempts with full jitter and a capped wait covers most gateway blips. Past that, surface a clear error and a fallback path rather than holding a user's request open for a minute.
Model-level fallback does not fix gateway errors, because both models sit behind the same edge and the same proxy path. Use fallback for quality or capacity planning; use streaming and backoff for 502s.
Usually proxy environment variables, container DNS, or an MTU mismatch. Run the same curl command inside the container — if it behaves like your laptop, the problem is your client's timeout and retry configuration, not the network.
Because bytes keep moving while the model generates, an idle socket or a gateway response deadline is much less likely to fire mid-answer. You also detect a dead stream before you have paid for the whole generation.
A bad or retired model name normally returns a 4xx with a JSON error body. If you recently migrated, pin explicitly to deepseek-v4-flash or deepseek-v4-pro, re-test, and check the response body rather than assuming the gateway is at fault.
Don't guess — log the request ID from each response and compare it against the usage page in your AiCredits dashboard. That also tells you whether the failures were reaching the model at all.
Work the list in order: classify the exception, back off with jitter, stream the long calls, then verify the network path. In practice that sequence resolves almost every 502 and transport failure without a support ticket — and the cases that remain are genuine incidents you now have evidence for.