Fix "stream disconnected before completion: Upstream request failed" in Codex
Fix the "stream disconnected before completion: Upstream request failed" error in Codex CLI, Cherry Studio, New API, and sub2api by adjusting Nginx timeouts.
Summary
- The error combines two layers: Codex CLI's SSE parser reporting a missing terminal event (response.completed) and a gateway failure (New API, One API).
- Check the failure timing first: disconnects at exact 60-second or 100-second marks point to Nginx proxy_read_timeout or Cloudflare limits.
- Mid-stream retries fail because HTTP streaming cannot switch channels after sending the initial HTTP 200 header.
When stream disconnected before completion: Upstream request failed appears in Codex CLI or Cherry Studio, you are looking at two separate error messages stitched together from two different points in your network path.
The first part, stream disconnected before completion, is generated locally by the Codex SSE parser. Under the OpenAI Responses streaming protocol, a streaming turn is not finished just because the text stops printing on your screen (response.output_text.done). The client waits for one of three terminal lifecycle events: response.completed, response.incomplete, or response.failed. If the socket closes or an unrecoverable error frame arrives before that final event lands, Codex prepends stream disconnected before completion:.
The second part, Upstream request failed, is not a native OpenAI message. It comes from the API gateway sitting between your client and the model provider—almost always New API, One API, or sub2api. It means the gateway accepted your request, opened a connection to an upstream channel, and then lost that upstream connection (or received an unhandled error) before the model finished generating.
Before you hit retry in Codex CLI, run git status --short and git diff in your project directory. Because this disconnect frequently triggers after Codex has already executed a shell command or written a file edit—right when the model is generating its final explanation—blindly re-sending the prompt can duplicate file patches or re-run state-changing commands. This is the exact same precaution needed when a response stalls mid-stream in Claude Code.
On this page
Is It a Gateway Timeout or a Dead Upstream Account?
You do not need to guess whether the problem is your client config, Nginx, or a bad API key in the gateway pool. You can tell which layer broke by watching the clock from the moment you send the prompt to the moment the error prints.
| When the Error Appears | Where the Connection Broke | What Happened Under the Hood | Where to Fix It |
|---|---|---|---|
| Within 1–3 seconds (before any text streams) | Upstream channel / account pool (sub2api or New API) |
The gateway routed your request to a rate-limited (429), expired (401), or capacity-locked account right as the stream initialized. |
Clean dead keys in New API / sub2api or switch channel groups. |
| At ~60 seconds of silence (during thinking or prefill) | Nginx reverse proxy in front of the gateway | The model spent more than 60 seconds reasoning without emitting an SSE chunk, hitting Nginx's default proxy_read_timeout 60s. |
Raise proxy_read_timeout to 600s and set proxy_buffering off in Nginx. |
| At ~100 seconds of silence | Cloudflare proxy (Orange Cloud) | Cloudflare cuts proxied HTTP connections that go 100 seconds without upstream data (HTTP 524), which the gateway surfaces as an upstream failure. | Set the gateway DNS record to DNS-only (Grey Cloud) or enable SSE keep-alive pings. |
| At 300 seconds (5 minutes) | Gateway internal HTTP timeout or Codex idle timer | Long code generation or multi-file refactoring hit New API's default channel timeout or Codex's stream_idle_timeout_ms. |
Raise RELAY_TIMEOUT in New API and tune ~/.codex/config.toml. |
| Randomly mid-sentence | Upstream reverse-engineered session (sub2api) |
The upstream session hit a token quota cliff, a WAF reset, or an account-level concurrency limit mid-generation. | Lower reasoning effort, compact context, or replace pooled session accounts. |
Why New API Cannot Switch Channels Once Streaming Starts
When I first ran into this error behind a self-hosted New API instance, my immediate question was why the gateway did not simply retry another channel. I had five healthy backup channels in the same group and the retry count set to three.
The reason is a fundamental constraint of HTTP Server-Sent Events (stream: true), which is also documented in New API's upstream issue tracker.
When you send a non-streaming request (stream: false), New API waits for the entire upstream response before sending anything back to your client. If Channel A returns a 502 or drops the connection, New API catches the failure in memory, discards it, and silently forwards the request to Channel B. Your client never knows Channel A failed.
When you use Codex CLI or Cherry Studio with streaming enabled, the workflow changes as soon as the upstream channel accepts the request. The gateway immediately sends HTTP 200 OK headers and flushes the initial SSE event (response.created) down the wire to your terminal. Once those bytes leave the gateway, the HTTP response is committed. If the upstream connection drops forty seconds later—whether because Nginx timed out a long reasoning pause or because a pooled account in sub2api hit a rate limit mid-reply—New API cannot pull back the tokens already printed on your screen and restart generation on another channel. Its only option is to write Upstream request failed into the error event and close the stream.
Fix 1: Configure Nginx for Long-Running SSE Streams
If you manage the server running New API, One API, or sub2api, default Nginx settings are the number one cause of stream disconnected before completion: Upstream request failed.
In the official Nginx ngx_http_proxy_module documentation, two default values work directly against reasoning models and coding agents:
First, proxy_read_timeout defaults to 60s. This directive does not measure the total duration of the response; it measures the maximum silent interval between two consecutive read operations from the upstream server. When you run a complex task at high or xhigh reasoning effort, or feed Codex a massive repository context, the upstream model can easily spend 70 to 150 seconds thinking before emitting the next SSE data frame. At exactly 60.0 seconds of silence, Nginx closes the upstream socket.
Second, proxy_buffering defaults to on. When buffering is enabled, Nginx accumulates small upstream SSE chunks in memory buffers before flushing them to the client. Holding back small stream events makes the connection appear idle to downstream proxies and clients until it trips a timeout.
Update the location block for your API gateway in your Nginx configuration:
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Disable buffering so SSE chunks flush to Codex immediately
proxy_buffering off;
proxy_cache off;
chunked_transfer_encoding on;
# Allow up to 10 minutes of silent reasoning between SSE chunks
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_connect_timeout 60s;
}
Run nginx -t && systemctl reload nginx after saving. If your gateway domain is routed through Cloudflare with the proxy toggle turned on (Orange Cloud), remember that Cloudflare Free and Pro plans enforce a hard 100-second read timeout regardless of what you put in nginx.conf. For dedicated API relay subdomains, switch the DNS record to DNS-only (Grey Cloud) or configure the gateway to emit periodic SSE comment heartbeats (: keep-alive\n\n) during long reasoning waits.
Fix 2: Tune New API and sub2api Channel Timeouts and Pool Rules
Once Nginx stops cutting the connection at 60 seconds, check the gateway container itself. Both New API and sub2api have internal request timers and channel routing quirks that trigger Upstream request failed.
Raise the Gateway Relay Timeout
In New API, the internal Go HTTP client uses the RELAY_TIMEOUT environment variable (measured in seconds) to cap how long a channel connection can remain open. If this value is unset or left too low, New API cancels the upstream context during long multi-file generations even when Nginx is configured for 600 seconds.
Add or update RELAY_TIMEOUT in your docker-compose.yml file:
services:
new-api:
image: calciumion/new-api:latest
environment:
- TZ=Asia/Shanghai
- RELAY_TIMEOUT=600
Restart the container with docker compose up -d.
Isolate Bad Accounts in Multi-Key Channels
If your errors happen within the first two or three seconds of sending a prompt, timeout settings will not help. Open the Logs tab in the New API or sub2api admin dashboard and filter for failures at the exact timestamp of your disconnect.
When a sub2api channel converts subscription accounts into API endpoints, an individual account in the pool may hit a temporary quota lock (similar to Codex's Selected model is at capacity routing lock), require verification, or reject a specific endpoint format (such as when a sub2api group blocks /v1/messages dispatch). If the upstream failure happens right after the stream handshake, New API surfaces it as Upstream request failed.
Make sure you are running New API v1.0.0-rc.10 or newer, which fixed the multi-key channel cache eviction logic so that automatically disabled keys are immediately purged from memory instead of continuing to receive traffic. Also check whether your upstream channel is rejecting Codex-specific request fields; if an upstream relay throws an error on unsupported caching parameters, see how to strip them in our guide on fixing prompt_cache_retention is not supported on this model gateway errors.
Fix 3: Adjust Codex CLI (config.toml) and Cherry Studio Settings
If you do not control the New API or sub2api server—meaning you bought a key from a third-party relay provider—you have to work around the gateway's limits from the client side.
Configure Retries and Idle Timeouts in Codex CLI
Codex CLI and the Codex VS Code extension read their provider settings from ~/.codex/config.toml. According to the official Codex configuration reference, custom model providers support three parameters that control how Codex handles stalled or dropped streams:
stream_idle_timeout_ms: How long (in milliseconds) Codex waits without receiving an SSE event before declaring the stream dead. The default is300000(5 minutes).stream_max_retries: How many times Codex automatically attempts to reconnect a dropped stream before aborting the turn. The default is5.request_max_retries: How many times Codex retries a failed initial HTTP connection. The default is4.
Open ~/.codex/config.toml and update your custom provider block. Make sure base_url ends with /v1 so Codex appends /responses to the correct path:
[model_providers.my_relay]
name = "my_relay"
base_url = "https://api.your-relay-domain.com/v1"
wire_api = "responses"
request_max_retries = 4
stream_max_retries = 10
stream_idle_timeout_ms = 600000
Save the file and restart Codex CLI.
Keep Thinking Time Under the Relay's Hard Timeout
Raising stream_idle_timeout_ms to 10 minutes on your machine only prevents Codex itself from hanging up early. If your relay provider left their Nginx proxy_read_timeout at 60 or 120 seconds, their server will still sever the connection whenever the model thinks for too long.
When you are stuck behind a relay with a strict timeout ceiling, you need to shorten the silent prefill and reasoning window on each turn. In Codex CLI, type /model and step the reasoning effort down one level (for example, from xhigh to high or medium) for heavy file-generation turns. If your current session has accumulated dozens of file reads and tool outputs, start a fresh session and pass only the current git diff so the upstream model does not spend 90 seconds processing context before emitting its first token.
Reveal Hidden Status Codes in Cherry Studio
If you get Upstream request failed in Cherry Studio during long responses, first open Settings → Model Provider, select your New API or sub2api provider, and increase the client request timeout from the default 60s–120s range to 600s (or 600000 ms depending on your version).
If the error still triggers immediately upon sending a message, temporarily toggle Stream Output off in your Cherry Studio assistant settings and send a short test prompt like Reply with OK. With streaming disabled, New API does not commit to an SSE stream prematurely; instead of masking the problem behind a generic Upstream request failed chunk, it will return the actual upstream HTTP status code (401, 403, 429, or 504 Gateway Time-out) so you know whether to replace the API key or switch to a faster model channel.