LLM API Guide

Fix stream disconnected (response.completed) in Codex CLI and sub2api

Fix "stream disconnected before completion: stream closed before response.completed" in Codex CLI, New API, and sub2api by disabling Nginx proxy buffering.

Summary

  1. The error occurs when a Server-Sent Events (SSE) or WebSocket stream closes (EOF) before Codex CLI receives the final response.completed lifecycle event.
  2. Self-hosted gateways like New API and sub2api trigger this when upstream overload or Nginx's default 60s proxy_read_timeout and proxy_buffering cut streams.
  3. Fix the gateway by setting proxy_buffering off, proxy_http_version 1.1, and proxy_read_timeout 600s in Nginx.
  4. On the client side, lower reasoning effort from xhigh/high with /model, trim context via AGENTS.md, and raise stream_idle_timeout_ms in ~/.codex/config.toml.

When Codex CLI or the Codex desktop app prints Reconnecting... 1/5 (stream disconnected before completion: stream closed before response.completed) and aborts the turn after five attempts, your initial HTTP request succeeded, authentication passed, and the stream opened—but something between your terminal and the model closed the TCP connection before the final closing event arrived.

What makes this error frustrating is that you will often see the model's full text answer already printed in your terminal right before Codex declares the turn failed. Under OpenAI's Responses API streaming specification, streaming output is governed by discrete lifecycle events rather than raw text chunks. When the model finishes writing a paragraph or code block, the server emits response.output_text.done. However, the official streaming guide explicitly distinguishes text completion from response completion: a stream is not finished until the server sends response.completed, which carries the final output array and token usage payload.

Inside the Codex client (codex-rs/codex-api/src/sse/responses.rs), the SSE parser listens continuously until that exact response.completed frame arrives. If a reverse proxy, CDN, or API gateway closes the socket with an EOF after response.output_text.done—or during a long pause while the model is thinking—Codex formats the error defined in codex-rs/protocol/src/error.rs as stream disconnected before completion: stream closed before response.completed and retries up to five times.

Before you let Codex retry or manually resend your prompt, run git status and check your terminal output. A dropped SSE stream only means the final confirmation packet never reached your client; it does not roll back file edits, shell scripts, or tool calls that the agent already executed during that turn. If you also use Anthropic's CLI and have run into a similar mid-reply cutoff where partial output remains on screen, see how state recovery works in our guide to API Error: Response stalled mid-stream.

On this page

Check the Text After the Colon First

stream disconnected before completion is a catch-all prefix for any stream that dies after the initial handshake. Before changing server configs, match the exact string after the colon to see which layer closed the connection:

Suffix After the Colon Where the Drop Happened First Thing to Check
stream closed before response.completed Middlebox (Nginx, Cloudflare, New API, sub2api, VPN) or upstream closed the HTTP/SSE socket early Gateway EOF logs, Nginx proxy_buffering and proxy_read_timeout, Cloudflare 125s timeout
websocket closed by server before response.completed WebSocket connection to chatgpt.com/backend-api/codex/responses closed mid-turn Ensure HTTPS_PROXY / ALL_PROXY routes WebSocket traffic, or let Codex fall back to HTTPS
idle timeout waiting for SSE / idle timeout waiting for websocket No event arrived within Codex's client-side idle timer (default 300,000 ms) High reasoning effort (high/xhigh) pauses; raise stream_idle_timeout_ms in config.toml
os error 10061 (Windows) / os error 61 (macOS) / os error 111 (Linux) Target port actively refused the connection Dead local proxy port (such as 127.0.0.1:7890) left behind in ~/.codex/.env or shell variables
os error 10053 / Broken pipe (os error 32) Local firewall/VPN aborted the socket, or request payload exceeded the ~16 MiB WebSocket frame limit Start a fresh session without large image attachments, or test with your VPN/antivirus paused
Our servers are currently overloaded. Please try again later. Upstream compute capacity exhausted mid-stream Switch models via /model or wait out the upstream capacity spike

Why New API and sub2api Gateways Trigger This Error

If you route Codex CLI through a custom base_url powered by New API or sub2api, stream closed before response.completed happens far more often than on a direct connection to api.openai.com.

When I inspect failed turns across New API and sub2api relays, the root cause is how the relay handles upstream disconnects and capacity errors once an HTTP 200 OK streaming header has already been flushed to Codex CLI. Once a relay sends Content-Type: text/event-stream and 200 OK to your terminal, it can no longer return an HTTP 503 or 429 status code if the upstream server fails three seconds later.

When the upstream provider hits a capacity wall (returning {"type":"service_unavailable_error","code":"server_error","message":"Our servers are currently overloaded. Please try again later."}) or resets the upstream socket during a heavy reasoning turn, the relay hits an unexpected EOF on its upstream reader. Instead of catching that upstream failure and serializing a valid SSE response.failed or response.incomplete event down the wire to Codex, the relay simply closes the downstream HTTP response stream.

From Codex CLI's perspective, a healthy HTTP 200 stream abruptly ended with EOF and zero error payload. Codex assumes it was a transient network blip, prints Reconnecting... 1/5, and hammers the already overloaded relay four more times. If your relay logs show upstream overload errors right when Codex disconnects, read Codex "Selected Model Is at Capacity": OpenAI Load or Your Account? to verify whether the upstream account pool or model tier is locked.

Fix 1: Disable Nginx Proxy Buffering and Raise Read Timeouts

If you host your own New API, sub2api, or custom Responses API proxy behind Nginx, default Nginx settings will consistently sever Codex streams for two reasons.

First, Nginx enables proxy_buffering on; by default. According to the Nginx ngx_http_proxy_module documentation, Nginx collects upstream responses into internal memory buffers (4 KB or 8 KB per page) and waits until a buffer fills before flushing packets to the client. Because LLM streams emit small SSE deltas—and because the final response.completed event sits at the very tail of the stream—buffering delays token delivery and frequently drops the final chunk when the upstream connection closes.

Second, Nginx sets proxy_read_timeout to 60s by default. That 60-second timer measures the maximum silent interval between two consecutive read operations from the upstream server. When a reasoning model spends 75 seconds thinking before emitting its first tool call or text token, no bytes cross the wire during that pause, and Nginx terminates the connection at 60 seconds sharp.

Update the location block for your API gateway in your Nginx configuration with these exact directives:

nginx
location / {
    proxy_pass http://127.0.0.1:3000; # Replace with your New API / sub2api port

    # Disable buffering and caching so SSE events flush immediately
    proxy_buffering off;
    proxy_cache off;

    # Force HTTP/1.1 and clear the Connection header for chunked keep-alive streams
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    chunked_transfer_encoding on;

    # Raise upstream read/send timeouts from the 60s default to 10 minutes
    proxy_read_timeout 600s;
    proxy_send_timeout 600s;
    proxy_connect_timeout 60s;

    # Forward standard client headers
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Test and reload Nginx with nginx -t && systemctl reload nginx. If you are writing your own lightweight Node.js, Go, or Python proxy and do not have access to the host's nginx.conf, return the header X-Accel-Buffering: no in your application's HTTP response; Nginx recognizes this header natively and disables proxy buffering for that specific request.

Fix 2: Bypass Cloudflare's 125-Second Proxy Read Timeout

Raising Nginx's timeout to 600 seconds will not help if your gateway domain sits behind an orange-cloud Cloudflare proxy.

Per Cloudflare's Error 524 documentation, Cloudflare enforces a hard Proxy Read Timeout of 125 seconds (previously 100 seconds) on Free, Pro, and Business plans. If your upstream model takes longer than 125 seconds to think between SSE events, Cloudflare cuts the connection between its edge node and your origin server. When the stream headers have already been established, Codex CLI does not show a Cloudflare 524 HTML page—it simply sees the stream close before response.completed.

Unless you are on a Cloudflare Enterprise plan—where you can raise proxy_read_timeout up to 6,000 seconds via Cache Rules or the Zone Settings API—the reliable fix is to bypass Cloudflare's CDN proxy for your API endpoint. Open your Cloudflare dashboard, go to DNS > Records, find the A or CNAME record for your API subdomain (for example, api.yourdomain.com), and toggle the proxy status from Proxied (orange cloud) to DNS-only (gray cloud). Once DNS propagates, Codex CLI connects directly to your Nginx server and respects your 600-second timeout.

Fix 3: Lower Reasoning Effort and Tune ~/.codex/config.toml

When you do not control the gateway server—or when you connect through a commercial relay with a fixed 120-to-150-second timeout—you have to prevent single turns from stalling the stream for two minutes at a time.

Start by reducing the silent pre-token thinking window inside Codex CLI. Type /model in your active session and step the reasoning effort down one notch from xhigh or high to medium. high and xhigh reasoning frequently pause for 90 to 150 seconds on multi-file refactors before emitting a single SSE delta, which trips middlebox timeouts every time.

Next, check the size of your current conversation. As a session accumulates full file reads and terminal diffs, Time to First Token (TTFT) climbs sharply. Start a clean session for the next step of your task, and store your repository conventions in AGENTS.md at the root of your project rather than pasting long instructions into the chat history.

Finally, make sure Codex CLI's own timeout settings match your gateway's behavior. According to the Codex configuration reference, both Codex CLI and the VS Code extension read ~/.codex/config.toml, which defines three separate retry and timeout parameters per custom provider: request_max_retries (default 4), stream_max_retries (default 5), and stream_idle_timeout_ms (default 300000, or 5 minutes).

Open ~/.codex/config.toml and add or update these lines inside your active [model_providers.<name>] block:

toml
[model_providers.my_gateway]
name = "My Custom Gateway"
base_url = "https://api.yourdomain.com/v1"
env_key = "OPENAI_API_KEY"
request_max_retries = 4
stream_max_retries = 8
stream_idle_timeout_ms = 600000

Keep in mind that stream_idle_timeout_ms only controls how long Codex CLI waits for an SSE or WebSocket event before giving up on its own end; it cannot stop an upstream Nginx proxy or Cloudflare node from closing the socket at 60 or 125 seconds.

If you frequently switch between official endpoints, New API relays, and sub2api gateways and want to verify whether a Base URL is timing out before you launch a coding session, you can use our free, open-source LLM API Config GUI on Windows or macOS to configure your Codex and Claude Code endpoints and run a quick connection and timeout diagnostic.

Sources and checks

  1. Responses API streaming specification
  2. official streaming guide
  3. Nginx ngx_http_proxy_module documentation
  4. Cloudflare's Error 524 documentation
  5. Codex configuration reference