Why DeepSeek API timeouts are three different bugs
Almost every timeout ticket is one of three failures wearing the same error name. Either the request never reached the API — DNS, an egress proxy, or a TLS handshake that stalled. Or it arrived but no bytes came back inside your read window, which usually means queueing or a long prefill. Or the response started and then the socket went silent mid-stream, which is almost always an intermediary closing an idle connection.
These fixes contradict each other, which is why blind tuning wastes days. Raising the read timeout helps the second case and does nothing for the first. Streaming fixes the third, not the first. If your logs just say "timeout", your client is hiding the answer from you. Start by making it tell you which of the three actually happened.
Step 1: Split connect, read, and pool timeouts
Most teams pass a single float to the SDK and never revisit it. Because the OpenAI SDK is built on httpx, you can pass an httpx.Timeout and get four independent limits: connect (handshake), read (gap between bytes), write (sending the body), and pool (waiting for a free connection).
Keep connect tight. A handshake that has not completed in a few seconds is not going to complete — it is a blocked route, not a slow one. Keep read generous but finite: with streaming it becomes a stall detector rather than a total-duration budget.
import os
import httpx
from openai import OpenAI
# Four independent limits instead of one number.
# connect = TCP + TLS handshake, read = gap between bytes mid-response.
timeout = httpx.Timeout(connect=5.0, read=90.0, write=15.0, pool=5.0)
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
timeout=timeout,
max_retries=0, # we classify and retry ourselves (see step 3)
)
stream = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Summarize this log line in one sentence: connection reset by peer"}],
max_tokens=256,
stream=True,
)
first = True
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if not delta:
continue
if first:
print("first token received -> not a prefill or queueing problem")
first = False
print(delta, end="", flush=True)
print()
With stream=True, the read timeout now means "no bytes for 90 seconds" — exactly the signal you want. It fires on a genuinely dead connection instead of on a long-but-healthy answer. For a single call with a different budget, use client.with_options(timeout=httpx.Timeout(connect=5.0, read=180.0, write=15.0, pool=5.0)) rather than mutating the shared client.
Step 2: Measure time-to-first-token, not total latency
A p95 of 40 seconds tells you nothing. Time-to-first-token (TTFT) separates the two very different causes: a request that sat waiting, versus one that started instantly and then decoded slowly. Run this probe on the same prompt shapes your production traffic uses.
import os
import time
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def probe(prompt: str, max_tokens: int = 300) -> dict:
start = time.perf_counter()
ttft = None
chunks = 0
stream = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
if chunk.choices[0].delta.content:
if ttft is None:
ttft = time.perf_counter() - start
chunks += 1
total = time.perf_counter() - start
decode = (total - ttft) if ttft else 0.0
return {
"ttft_s": round(ttft, 3) if ttft else None,
"total_s": round(total, 2),
"chunks": chunks,
"chunks_per_s_after_ttft": round(chunks / decode, 1) if decode > 0 else None,
}
short = "Explain TCP keep-alive in one sentence."
long_input = short + (" Add no extra detail." * 200)
print("small prompt ", probe(short))
print("large prompt ", probe(long_input))
print("long output ", probe("Write a 400-word explanation of TCP keep-alive.", max_tokens=800))
Read the three lines together. If TTFT is stable but total time balloons on the long-output probe, your problem is output length — cap max_tokens. If TTFT grows with the large prompt, it is prefill, so trim context. If TTFT is fine in the morning and terrible at peak, it is capacity and queueing, and retrying harder will make it worse. The chunk count is a proxy for tokens, not an exact count, but it is consistent enough to spot trends.
Step 3: Classify the exception before you retry
The SDK's built-in retries are a reasonable default, but on timeouts they retry blindly: a 422 and a 503 get the same treatment. Turn max_retries off and handle the cases yourself, so non-retryable errors fail fast and retryable ones back off with jitter.
import os
import random
import time
import httpx
from openai import (
OpenAI,
APITimeoutError,
APIConnectionError,
RateLimitError,
APIStatusError,
)
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
timeout=httpx.Timeout(connect=5.0, read=90.0, write=15.0, pool=5.0),
max_retries=0,
)
RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}
def ask(messages, *, model="deepseek-v4-flash", max_tokens=512, attempts=4):
last = None
for attempt in range(attempts):
try:
resp = client.chat.completions.create(
model=model,
messages=messages,
max_tokens=max_tokens,
stream=False,
)
return resp.choices[0].message.content
except APITimeoutError as e: # connected, then stalled
last = e
except APIConnectionError as e: # never connected at all
last = e
except RateLimitError as e:
last = e
except APIStatusError as e:
if e.status_code not in RETRYABLE_STATUS:
raise # 400/401/403/422 will never succeed
last = e
if attempt == attempts - 1:
break
time.sleep(min(2 ** attempt, 10) + random.uniform(0, 0.5))
raise RuntimeError(f"gave up after {attempts} attempts") from last
print(ask([{"role": "user", "content": "Explain HTTP keep-alive in two sentences."}]))
One caveat that bites teams in production: if a request times out after the server started generating, a retry can duplicate the work and you pay for both attempts. Make retried operations idempotent on your side, attach your own correlation id with extra_headers so you can dedupe downstream, and prefer a slightly longer read timeout over an aggressive retry policy for expensive calls.
Step 4: Check the boring client-side causes first
HTTP_PROXY / HTTPS_PROXY / NO_PROXY environment variables: common in containers and CI. A proxy doing TLS inspection adds latency and sometimes drops long-lived responses.
A new OpenAI client per request throws away keep-alive and pays a fresh TLS handshake every call. Create one client per process, at module scope.
Async apps calling the blocking sync client inside the event loop: requests appear to time out because the loop never got to them. Use AsyncOpenAI with await.
Small httpx pool limits plus high concurrency cause pool timeouts that look like API slowness. Reuse a single client and bound your own concurrency with a semaphore.
Container CPU throttling and GC pauses can push a healthy response past your read window under load. Check cgroup limits before blaming the network.
Synchronized retries from many workers create self-inflicted queueing. Jitter, as in the wrapper above, is not optional.
A wrong base URL or a stale DNS entry produces clean, fast connect timeouts rather than slow ones — verify the endpoint with a single curl before anything else.
Symptom to cause to first fix
| Symptom | Likely cause | First thing to change |
|---|---|---|
| Fails in a few seconds, every time, everywhere | Handshake blocked: proxy, egress firewall, wrong base_url, DNS | Check proxy env vars; curl the endpoint directly |
| Fails at exactly your timeout value, no output | Read timeout on a long generation or long prefill | Stream the response; cap max_tokens |
| Intermittent, only on long prompts | Prefill time scales with input length | Trim context; keep stable prefixes so cache hits help |
| Fine locally, times out in containers or CI | Proxy variables, pool limits, blocked egress | Reproduce inside the same image; log the exception type |
| Only fails under load | Concurrency too high for your pool | Bound workers with a semaphore, share one client |
| Stream starts, then stalls mid-answer | Intermediary closed the idle connection | Send keep-alives or shorten outputs; check proxy idle timeout |
Step 5: Shrink the work per request
Cap max_tokens. An uncapped generation is the most common cause of a read timeout on a short budget.
Trim context. Send the relevant window, not the entire conversation history.
Keep the system prompt and other stable prefix text identical across calls — cache hits cost less and reduce prefill work.
Split very long generations into sequential short calls you can checkpoint, instead of one call that must survive a 120-second window.
Send long outputs to the user as a stream rather than buffering them behind a single blocking call.
When the real fix is the model, not the timeout
deepseek-v4-flash is the right default for high-volume, latency-sensitive work, and it is what the code above uses. deepseek-v4-pro is the stronger model for harder reasoning, and it costs more per token — it is not a latency fix. If pro is timing out, give it a longer read timeout and a tighter max_tokens rather than downgrading blindly, and only escalate to pro when flash's answers are genuinely the bottleneck. If a timeout only appears on pro calls, that is a length problem, not a model problem.
FAQ
No. That converts a fast, diagnosable error into a slow hang and hides the actual cause. Measure TTFT first: if time-to-first-token is healthy and only the total time is long, then yes, raise read and cap output length. If TTFT is high, a longer window only makes the failure slower.
It eliminates the class of timeouts caused by a long total duration under a fixed read budget, because bytes keep arriving and the read timer keeps resetting. It does not help with connect failures, and it turns a stall into a visible mid-stream error instead of a clean timeout — which is a better failure to have.
Proxy environment variables, restricted egress, and smaller connection pools are the usual culprits. Log the exception class, not just the message: a connect timeout in the container points at the network path, while a pool timeout points at your own concurrency.
Three or four attempts with exponential backoff plus jitter is enough for transient errors, and never retry a 4xx that is not a rate limit. Past that, retries mostly amplify whatever is already overloaded — including your own workload.
AiCredits issues DeepSeek API credits to international developers and accepts card or PayPal, with no Chinese phone number or bank account required. Set the key as AICREDITS_API_KEY and the samples run as written. Current rates are on the pricing page at aicreditsapi.com/pricing.
A connect timeout is a network problem, a read timeout is a length problem, and a mid-stream stall is an intermediary problem. Fix the one you actually have — and check aicreditsapi.com/pricing if you are budgeting for it.