LLM API Request Timeout: Fix 504 and 408
Why an LLM API request timeout happens after switching to a reasoning model or long output: the 240-second 504, the 120-second silent-stream 408, and the fixes.
By OceanToken Team

Editor's note: Timeouts tend to appear the week someone swaps a fast chat model for a reasoning model, or asks for a whole report instead of a paragraph. Nothing in the code changed, so the bug looks like the platform's fault. Usually it is a mismatch between three clocks: the server's limit, the stream's silence rule, and your client's own timeout. Line those up and most timeouts go away.
Want to run the examples in this article? Get API Key and call every model below with one key.
Short answer: An LLM API request timeout on our API is one of two errors. 504 timeout means a non-streamed request ran past 240 seconds. 408 timeout means a stream went 120 seconds without anything from the model. Stream long and reasoning responses, keep your client timeout at least as long as the server's, and retry 408 with backoff.
This applies to any model you call through OceanToken, which is why we use it here: one key reaches reasoning models from OpenAI, DeepSeek and other publishers, and the timeout rules are the same for all of them, so one fix covers every model you switch to. The limits below come from our docs, read November 30, 2026. We have not timed your prompts, so the article ends with a test you can run.
01 · Why an LLM API request timeout appears after a model switch
Switching models changes how long a request takes, even when the prompt is identical. A reasoning model thinks before it answers, and our text guide says that thinking is billed as output tokens and, on many models, counts toward max_tokens. More output tokens take more time to produce. Ask for a long answer from a model that also reasons at length, and a request that used to return in seconds can run for minutes.
Minutes are where the limits start to matter. Our limits page says a synchronous request is held open for at most 240 seconds, measured from the start of the request to the last byte of the response. A streamed request is different: it stays open as long as tokens keep flowing. And our errors page defines a second rule for streams: if a stream receives nothing from the model for 120 seconds after it started, it ends with 408 timeout.
So the same model and prompt can succeed when streamed and fail when not. That is why most of the fixes below start with streaming. If you want the broader question of when to switch to another model after an error, our guide to falling back to another LLM covers it; here we stay with the timeout itself.

02 · Symptom, cause and fix
Before changing anything, work out which clock fired. The status code, and whether you streamed, usually tell you:
| What you see | Most likely cause | Fix |
|---|---|---|
504 with timeout, non-streamed request |
The response was not finished within 240 seconds | Stream it, ask for less output, or lower reasoning effort |
408 with timeout during a stream |
The model sent nothing for 120 seconds after the stream started | Retry with backoff; lower reasoning effort if it repeats |
| Your client raises a timeout error before any status code | Your client's timeout is shorter than the request needs | Raise the client timeout to cover the server window, or stream |
| Stream stops partway, with no finish marker | Connection broke or an error arrived as the last chunk | Treat the answer as incomplete and retry; see section 06 |
200 but an empty or cut-off answer |
Reasoning used up max_tokens (finish_reason: length) |
Raise max_tokens or lower effort; not a timeout |
The last row is not a timeout, but it shows up in the same week for the same reason, so it is worth ruling out. Our reasoning tokens and empty replies fix covers it in detail. A 429 is also not a timeout; for that, see our 429 rate limits guide.
03 · 504 timeout on a long LLM response
A 504 timeout on a long LLM response means the request ran past the 240-second window, and our errors page gives three ways out: stream the response, shorten the request, or use an asynchronous endpoint. For text generation the first is almost always the right one.
Streaming works because the limit applies to synchronous requests. Our limits page says long text generations should use "stream": true, since a stream stays open as long as tokens keep flowing. The model does not get faster; the request simply stops being judged against a single deadline. It also gives your user something to read while the rest arrives, which is why our text guide recommends streaming anything a person is waiting on.
# pip install openai
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.oceantoken.ai/v1",
api_key=os.environ["OCEANTOKEN_API_KEY"],
timeout=300.0, # longer than the server's 240 s window for non-streamed calls
max_retries=0) # we retry ourselves, see section 07
parts, finish, usage = [], None, None
with client.chat.completions.create(
model="deepseek/deepseek-v4-pro",
messages=[{"role": "user", "content": "Write a detailed migration plan for moving a monolith to services."}],
stream=True,
stream_options={"include_usage": True},
) as stream:
for chunk in stream:
if chunk.usage:
usage = chunk.usage
if chunk.choices:
delta = chunk.choices[0].delta.content
if delta:
parts.append(delta)
if chunk.choices[0].finish_reason:
finish = chunk.choices[0].finish_reason
print("".join(parts))
print("finish:", finish, "| usage:", usage)
Two details in that snippet matter. stream_options={"include_usage": True} makes the last chunk carry token counts, which our docs say chat-completions streams only send when asked; our streaming token usage guide explains reading them. And the loop records finish_reason, because a stream without one is incomplete, as section 06 explains.
What if you cannot stream, for example a batch job whose framework only accepts a full response? Then shrink the work. Ask for less output, split one big request into several smaller ones, or lower reasoning effort (section 05). Keep the client timeout above 240 seconds so the server, not your client, decides when the request has failed.
04 · Stream went quiet: the 408 timeout
A 408 timeout means a stream received nothing from the model for 120 seconds after it started. Our errors page lists it as retryable with backoff. It is rarer than the 504, because a streamed request usually produces something well inside that window, but reasoning models are where it shows up: a model can think for a long stretch before writing, and if nothing reaches the stream in that time, the rule applies.
Our reliability page adds what happens before the first token. If a channel sends nothing for 120 seconds before the first token, the request moves to the next channel of the same model, where the model has more than one. You see a stream that starts a little later. Once the answer has started, a clean switch is not guaranteed; the gateway either finishes on another channel or ends the stream with an error event, depending on the endpoint.
What should you do on a 408? Retry it, with backoff, as section 07 shows. If the same prompt produces a 408 repeatedly on the same model, the prompt is probably asking for more thinking than the model can do without pausing, and the fix is to lower reasoning effort or break the task into steps. Moving to a different model is also reasonable at that point, and our fallback guide shows how to name backup models in the request.
05 · Reasoning model API timeout
A reasoning model API timeout is usually a time budget problem, and reasoning_effort is the main control. Our text guide says more effort means more output tokens, so a higher cost and a slower answer, and that the accepted values vary by model. Check them on the model page before you set the parameter; two models from our catalog show why:
| Model | Reasoning in docs | reasoning_effort values |
Output cap (max_tokens) |
|---|---|---|---|
openai/gpt-6.2-sol |
Always reasons | low, medium, high, max (default medium) | up to 128K, reasoning included |
deepseek/deepseek-v4-pro |
Supports reasoning | not in the docs parameter list | up to 384K, reasoning included |
For GPT-6.2 Sol, dropping from high to low is the documented way to get a faster answer, and max is the setting most likely to run long. For DeepSeek V4 Pro, the parameter does not appear in its docs, and our text guide says an unsupported parameter is dropped while the request still succeeds. Sending reasoning_effort there may do nothing at all, so test it rather than assuming it shortened anything; read usage.completion_tokens_details.reasoning_tokens with and without it.
max_tokens works on time indirectly. It caps how much the model writes, reasoning included, so a lower cap ends a runaway answer sooner. The trade-off is the empty-reply problem from section 02: too low, and reasoning eats the budget before the answer starts. Leave room for both. If you work with Gemini models, our Gemini thinking levels guide covers the same trade-off for that family.
06 · Streams that stop partway
A stream can end early without a timeout code: the connection breaks, your process restarts, or an error arrives. Our errors page says an error after the stream has started comes as a final data chunk carrying the error object, and then the stream ends. Our reliability page says to check that every stream ends with a finish reason: finish_reason on chat completions, stop_reason on Messages, and a response.completed event on Responses. A stream without one is incomplete; retry it.
Billing matters here, because retrying a broken stream is not free. Our docs say a stream that ends early is billed for its prompt in full and for the output streamed up to that point, and a reasoning model's streamed reasoning counts as output even if no answer text had arrived yet. A stream that ended before producing any output is not billed. If you cancel a stream yourself, some channels keep generating and that output can be billed too; the errors page has the details. The practical lesson: do not cancel and resend long streams on a hunch. Retry when the stream actually failed.
07 · Retries without double work
Retry only the errors that can succeed on a second try. Our errors page lists them: 408, 429, any 5xx except 501, 409 idempotency_key_in_progress after Retry-After, and network failures, which include a client-side timeout. Every other 4xx, and 501 not_supported, will fail the same way again. The page recommends exponential backoff with jitter, starting around one second and capping around thirty, and waiting at least Retry-After seconds when the response sends it. It also notes that Retry-After is guaranteed only on the 409 case.
The OpenAI SDK retries on its own by default. Its README says requests time out after 10 minutes by default and that certain errors, including 408, 409, 429 and >=500, are retried twice automatically. That default can work against you: a 504 after a long wait gets retried twice more by the SDK, and the SDK also retries 501, which our docs say never to retry. Our docs' own example sets max_retries=0 and retries in a loop, and that is what we would do:
import random, time
from openai import APIConnectionError, APIStatusError, APITimeoutError
def with_retries(call, attempts=4):
for attempt in range(attempts):
try:
return call()
except (APIConnectionError, APITimeoutError):
if attempt == attempts - 1:
raise
delay = None
except APIStatusError as e:
code = e.status_code
retryable = code in (408, 429) or (code >= 500 and code != 501)
if code == 504 or not retryable or attempt == attempts - 1:
raise # a 504 will time out again unless you stream or shorten it
ra = e.response.headers.get("retry-after")
delay = float(ra) if ra else None
time.sleep(delay if delay is not None else min(30, 2 ** attempt) + random.random())
The 504 line is our choice, not the docs'. A 5xx is retryable in general, but a request that just ran out of time will most likely run out of time again if you send it unchanged; we would raise it, switch to streaming, and only then retry.
What about idempotency keys? Our docs support an Idempotency-Key header, but only on image generation, image edits, video creation and speech; it is ignored on every other endpoint, chat completions included. A chat request retried after a client-side timeout simply runs again. If the first attempt actually finished on the server, you pay for both. For long chat requests, that is one more reason to stream and wait rather than give up early: check the request in Logs in the console before you assume it failed.
How to test this on your workload
We have not timed your prompts, so this is the test we would run before changing production settings:
- Pick your longest real prompt, the one most likely to time out.
- Send it non-streamed to
deepseek/deepseek-v4-prowith the client timeout above 240 seconds; record wall time, status code andusage. - Send the same prompt streamed with
include_usage; record time to first token, total time,finish_reasonandusage. - Repeat both on
openai/gpt-6.2-solatreasoning_effortlowandhigh. - Send
reasoning_effortto DeepSeek V4 Pro and comparereasoning_tokenswith and without it. - Set your client timeout deliberately low once and confirm what error your code raises and whether Logs shows the request finishing anyway.
- Kill the network mid-stream once and confirm your code notices the missing finish marker.
- Count retries your code made in all of the above, with the SDK's auto-retries off.
Our take: Stream every long or reasoning response by default. For calls you cannot stream, keep the client timeout above the server's 240-second window and lower reasoning effort or output length instead. Turn off SDK auto-retries, retry only the codes our docs list, and do not blindly resend a 504.
Running it on OceanToken
From our docs, as of November 30, 2026:
- One set of rules for every model. The 240-second window, the 120-second stream rule and the retry list are the same whichever model you call, so switching models with one key does not change your timeout handling.
- Failover inside the platform. A timeout on one channel of a model moves the request straight to the next channel, where the model has one; you see a normal response, a little later.
- OpenAI-compatible. Change the base URL to
https://api.oceantoken.ai/v1and the key; the OpenAI SDK's timeout and retry settings work as usual. - Prepaid, no subscription. A stream that ends before producing any output is not billed (Errors page).
Price: see the current rate on /deepseek-api, /pricing and each model's page under Models.
FAQ
What does a 504 timeout from an LLM API mean? On our API, a non-streamed request ran past 240 seconds. Stream it, shorten the request, or lower reasoning effort.
What does a 408 timeout mean during streaming? The stream received nothing from the model for 120 seconds after it started. Retry with backoff.
What client timeout should I set? For non-streamed calls, longer than 240 seconds so the server decides. Streams stay open while tokens flow.
Should I retry a 504? Not unchanged. Switch to streaming or shrink the request first; a plain resend will likely time out again.
Do idempotency keys protect chat retries? No. Our docs apply Idempotency-Key only to image, video and speech requests; chat retries run again.
Sources
- OceanToken docs: Limits (checked 2026-11-30)
- OceanToken docs: Errors (checked 2026-11-30)
- OceanToken docs: Retries and automatic failover (checked 2026-11-30)
- OceanToken docs: Text generation (checked 2026-11-30)
- OceanToken docs: GPT-6.2 Sol API (llms.txt) (checked 2026-11-30)
- OpenAI Python SDK README (checked 2026-11-30)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on /deepseek-api.
curl https://api.oceantoken.ai/v1/chat/completions \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "deepseek/deepseek-v4-pro", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Write a detailed migration plan for moving a monolith to services."}]}'
More from the blog
Speech to Text API Accuracy: Fix Names
Improve speech to text API accuracy: set language as an ISO-639-1 code, pass names in prompt, upload the file rather than a URL, and measure on your audio.
Streaming LLM API Token Usage and Cost
Streaming LLM API token usage is null by default. Fix it with stream_options include_usage, then get the cost of a streamed completion from /v1/usage by id.
Hailuo Video Problems: 10 Fixes by Symptom
Hailuo video problems sorted by symptom: morphing faces, static or frantic motion, ignored camera moves, refused requests. Causes, fixes and a triage table.