The Review That Died at 330 Seconds: Long API Calls Behind CGNAT

· 5 min read · Tutorials openai-apistreamingcgnattimeoutsbackground-jobspythonretriesautomation

330 Seconds of SSE Silence

I now have two transports for sending a review request: the existing browser-based broker client (Neon) and a new API wrapper, gpt_ask.py (+ gpt-ask.cmd), defaulting to gpt-6.2-astra with --effort high. Both read the same ask file and write the same answer file, so the choice is about reliability, not about what the model can see.

Two runs succeeded cleanly:

AskAnswerTimeCost
4.3 KB, five judgment items4.4 K chars106 s$0.16
16.4 KB review ask6.2 K chars250 s$0.34

The second row is the one that matters, because it was the second attempt on that file — and the first one that finished. The initial streaming attempt failed with:

urllib3.exceptions.ProtocolError: ('Connection aborted.',
ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host'))

after 330 seconds, with the answer file never created.

Two facts made that diagnosis quick. The request had been in the model’s reasoning phase — no output tokens yet, therefore no SSE bytes — for the entire time. And the host sits behind Maxis CGNAT: my public IP is shared, NAT state lives outside my control, and idle-connection timeouts follow carrier policy.

With no SSE bytes flowing during reasoning, an idle TCP socket behind Maxis CGNAT is the primary suspect for the reset at 330 seconds.

Switching Prompts Over 12,000 Chars to Background Polling

The instinct is to add a timeout and retry. That is the wrong first move, because the failure is not a slow server — it is an idle socket. Retrying a stream that will go idle again just spends the same silence twice.

The API provides a second pattern: submit with background: true, receive a job ID, and poll /responses/<id>. Each poll is a short HTTP request, so no single TCP connection has to stay open across the reasoning phase.

Three details decide whether this holds up in practice:

  1. The size threshold has to be automatic. The 4.3 KB ask streamed and finished in 106 s. Making the transport a per-file decision means the decision gets made wrong under deadline pressure. Above 12,000 characters the client switches to background: true on its own; below it, streaming keeps the interactive latency.
  2. A mid-stream drop has to degrade. If a streaming request drops mid-flight, --mode auto falls back to the background submission path instead of retrying the same streaming call. That branch is wired but has not yet been triggered by a live drop.
  3. The job ID is the only handle. This run came back as job 44c9aeebaa16, and the answer is fetched by polling /responses/<id> — the handle for a 250-second job is a short string, not a socket held open for minutes.

The core of the change is the transport decision:

from pathlib import Path
from urllib3.exceptions import ProtocolError

# submit_background / poll_until_done / stream are thin HTTP wrappers (omitted here)

def ask(prompt_file: str, out_file: str, mode: str = "auto") -> str:
    text = Path(prompt_file).read_text(encoding="utf-8")
    use_background = mode == "background" or (
        mode == "auto" and len(text) > 12_000
    )
    if use_background:
        job_id = submit_background(text)        # returns a job id immediately
        answer = poll_until_done(job_id)        # GET /responses/<id> until done
    else:
        try:
            answer = stream(text)               # short asks keep their low latency
        except (ConnectionResetError, ProtocolError):
            # degrade: re-submit as a background job, do not retry the stream
            answer = poll_until_done(submit_background(text))

    Path(out_file).write_text(answer, encoding="utf-8")
    return answer

Fixing Missing MARKER Lines and Checking Prompt Cache Hits

Switching transports exposed two contract differences that had nothing to do with networking, and both would have corrupted results silently:

The 12,000-character threshold is a pragmatic split between the 4.3 KB run that streamed cleanly in 106 s and the 16.4 KB run that reset at 330 s. Setting it too high leaves long asks exposed to idle disconnects; setting it too low pushes short asks through polling overhead unnecessarily.

🔍 View the two flags passed to the CLI (same ask file as the broker client)
# same ask file either way — this is what makes the two transports comparable
python gpt_ask.py --effort high --mode auto "$ASK_FILE"

--effort high is the default reasoning level and --mode auto is the 12,000-character switch. The rest is the same ask-file-in, answer-file-out interface the broker client already used, which is why a failed transport is never a reason to rewrite the prompt.

Same Ask, 250 Seconds to Exit 0

The lesson lands on the idle socket. Streaming fits interactive chat, but for long reasoning jobs whose stream stays byte-silent until the final answer, holding an open socket across CGNAT is fragile; decoupling submission from polling removes the idle-socket dependency.

🚀 Automation & Custom AI Systems

Want a 24/7 bot or automation pipeline that never drops a lead?

Don't let customer inquiries slip away at midnight or on weekends. I build custom Telegram/WhatsApp AI assistants and deterministic workflows that connect directly to your catalogue, CRM, and order fulfillment.

Lee Teong Hoe

Lee Teong Hoe · Mr Hoelee

Full-stack developer & DevOps engineer based in Malaysia. I run my own production infrastructure and build web systems for small businesses — this blog is the living record.

Hiring? Profile & stack · Malaysian SME? Website design & development ↗ · All posts