Skip to content
FramesField
FIX 32 · COMFYUI & LOCAL GPU
raw .md ↗ Verified Dec 1, 2026

Fix Headless ComfyUI Python API Stalls and Queue Timeouts

Direct Fix: Stop relying on bare blocking ws.recv() loops: pass a client_id before queueing, enforce WebSocket ping_interval=20 with a finite read timeout, and drive completion deterministically from GET /history/{prompt_id} + GET /queue so proxy drops and execution_error events never stall a batch.
Exact Error / Visual Signature
websocket._exceptions.WebSocketConnectionClosedException: Connection to remote host was lost | Python client blocks indefinitely on ws.recv() while ComfyUI /history shows completed
OBSERVED SYMPTOM

Your headless Python batch runner submits a job to local or cloud-GPU ComfyUI (RunPod, Modal, or remote RTX server) and then freezes forever waiting on ws.recv(), or crashes mid-render with a 60–100 second WebSocket timeout even though the GPU is still sampling cleanly.

TECHNICAL ROOT CAUSE

Three compounding protocol bugs: (1) opening ws://<host>/ws?clientId=... AFTER posting to /prompt misses the terminal executing:null event on fast or cached jobs; (2) reverse proxies (Nginx, Cloudflare, RunPod proxy) silently drop idle WebSockets during long 60–120s single-step DiT samples or VAEDecode passes when no ping frames flow; (3) listening only for executing:null ignores execution_error and execution_interrupted frames.

Copy-Paste Verified Fix

Zero-Dependency Resilient ComfyUI Headless Queue & Timeout Guard comfy_resilient_queue.sh
# Save and run a resilient stdlib-only ComfyUI API dispatcher (works on local & RunPod proxies)
cat <<'PY' > comfy_resilient_queue.py
import json, os, sys, time, uuid, urllib.request, urllib.error

COMFY_URL = os.environ.get("COMFY_URL", "http://127.0.0.1:8188").rstrip("/")
TIMEOUT_SEC = int(os.environ.get("COMFY_JOB_TIMEOUT", "900"))
POLL_SEC = float(os.environ.get("COMFY_POLL_INTERVAL", "4.0"))

def req_json(method, path, payload=None, http_timeout=20):
    data = json.dumps(payload).encode("utf-8") if payload is not None else None
    headers = {"Content-Type": "application/json"} if data else {}
    req = urllib.request.Request(f"{COMFY_URL}{path}", data=data, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=http_timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))

def wait_for_prompt(prompt_id, deadline):
    missing_ticks = 0
    while time.monotonic() < deadline:
        try:
            hist = req_json("GET", f"/history/{prompt_id}")
            if prompt_id in hist:
                entry = hist[prompt_id]
                status = entry.get("status", {})
                if status.get("status_str") == "error":
                    raise RuntimeError(f"ComfyUI execution_error: {json.dumps(status.get('messages', []))}")
                if status.get("completed") or entry.get("outputs"):
                    return entry
            queue = req_json("GET", "/queue")
            active_ids = [item[1] for item in queue.get("queue_running", []) + queue.get("queue_pending", [])]
            if prompt_id in active_ids:
                missing_ticks = 0
            else:
                missing_ticks += 1
                if missing_ticks >= 3:
                    raise RuntimeError(f"Job {prompt_id} vanished from /queue and /history (possible worker restart).")
        except urllib.error.URLError as err:
            print(f"[warn] Transient HTTP/proxy error while polling: {err}", file=sys.stderr)
        time.sleep(POLL_SEC)
    req_json("POST", "/interrupt")
    raise TimeoutError(f"Job {prompt_id} exceeded {TIMEOUT_SEC}s wall-clock limit; sent /interrupt.")

def main():
    graph = json.load(open(sys.argv[1], "r", encoding="utf-8"))
    req_json("GET", "/system_stats")  # Pre-flight health check before submitting
    client_id = str(uuid.uuid4())
    res = req_json("POST", "/prompt", {"prompt": graph, "client_id": client_id})
    if res.get("node_errors"):
        raise RuntimeError(f"Validation node_errors: {json.dumps(res['node_errors'])}")
    prompt_id = res["prompt_id"]
    print(f"Queued prompt_id={prompt_id} client_id={client_id}")
    entry = wait_for_prompt(prompt_id, time.monotonic() + TIMEOUT_SEC)
    print("Completed outputs:", json.dumps(entry.get("outputs", {}), indent=2))

if __name__ == "__main__":
    main()
PY

# Run against local ComfyUI or set COMFY_URL=https://<pod-id>-8188.proxy.runpod.net
COMFY_URL="http://127.0.0.1:8188" COMFY_JOB_TIMEOUT=600 python3 comfy_resilient_queue.py workflow.api.json

Before vs. After (Broken Pattern vs. Verified Fix)

Broken · Fragile Script (Opens WS Late, No Timeout, Ignores execution_error)
# POSTs first -> fast jobs finish before WS opens; proxy idle drop hangs forever
resp = requests.post(f"{COMFY}/prompt", json={"prompt": graph}).json()
ws = websocket.create_connection(f"ws://{HOST}/ws?clientId=batch")
while True:
    msg = json.loads(ws.recv())   # Blocks forever on proxy drop or CUDA OOM!
    if msg["type"] == "executing" and msg["data"]["node"] is None:
        break
Verified · Resilient State Machine (Bounded HTTP /history + /queue + Error Inspection)
# Authoritative /history + /queue polling survives proxy resets & catches node tracebacks
prompt_id = post_json(f"{COMFY}/prompt", {"prompt": graph, "client_id": cid})["prompt_id"]
while time.monotonic() < deadline:
    hist = get_json(f"{COMFY}/history/{prompt_id}")
    if prompt_id in hist:
        status = hist[prompt_id].get("status", {})
        if status.get("status_str") == "error":
            raise RuntimeError(status.get("messages"))
        if status.get("completed"):
            return hist[prompt_id]["outputs"]
    time.sleep(4)

Why this works: Polling /history/{prompt_id} alongside /queue liveness checks survives 60-second cloud proxy disconnects, never misses fast cached completions, and surfaces exact Python node tracebacks immediately on failure.

Under the Hood

Why This Failure Happens in Real Pipelines

Most copied ComfyUI Python examples follow a naive sequence: call POST /prompt, grab the returned prompt_id, open a WebSocket connection, and enter an unbounded while True: ws.recv() loop until an executing message arrives with node == None. That pattern breaks under two everyday production conditions. First, if a node graph hits ComfyUI cache or finishes in under 50 milliseconds, the server emits executing:null before your WebSocket handshake finishes, guaranteeing an infinite hang. Second, if a node fails with CUDA out of memory or a missing checkpoint, ComfyUI sends an execution_error event rather than executing:null, leaving scripts without explicit error handling stalled until someone manually kills the process.

Remote cloud-GPU setups add a third failure layer: HTTP reverse proxies such as RunPod proxy endpoints, Nginx (default proxy_read_timeout 60s), and Cloudflare Tunnels (100s idle limit) sever WebSocket sockets that go silent during heavy compute phases. While KSampler emits progress ticks between steps, long single-call stages—loading a 20GB checkpoint into VRAM, compiling Torch graphs, encoding T5-XXL prompts, or running a full 121-frame VAEDecode—send zero WebSocket messages for 45 to 110 seconds. The proxy closes the TCP connection silently while ComfyUI keeps rendering on the GPU, causing your script to crash or hang on a half-open socket.

The production-grade architecture separates submission from state verification. Generate one UUID client_id up front, treat GET /history/{prompt_id} plus GET /queue as your authoritative completion state machine on a 3–5 second polling cadence with a strict per-job wall-clock deadline, and use WebSocket solely for optional progress logging with explicit ping_interval=20 and socket read timeouts. If a WebSocket drops mid-batch, your runner simply falls back to /history/{prompt_id} without losing the running GPU render or wasting cloud rental minutes.

Step-by-Step Resolution & Verification

  1. 01

    Inspect /queue and clear any stuck zombie jobs first

    Query GET /queue to see whether an earlier stalled graph is still occupying the GPU slot. If a dead job is stuck in queue_running, post to /interrupt and POST {"clear": true} to /queue before launching your updated client.

  2. 02

    Switch completion logic to /history/{prompt_id} + /queue state polling

    Replace blocking while True: ws.recv() waits with bounded /history/{prompt_id} polling that checks status.completed, status.status_str == "error", and /queue presence every 3–5 seconds. If you still want real-time progress bars over WebSocket, open the socket BEFORE POST /prompt and configure ping_interval=20 with a finite socket timeout.

  3. 03

    Enforce a hard per-job deadline and automatic /interrupt cleanup

    Set a realistic wall-clock deadline (for example 600–900 seconds for 121-frame video renders) so an unexpected CUDA lockup triggers POST /interrupt and logs the failing prompt_id instead of burning overnight cloud GPU billing.

Verification Check · Confirm Server Liveness, Empty Zombie Queue & Clean History Access
curl -sf http://127.0.0.1:8188/system_stats | python3 -c "import sys,json; d=json.load(sys.stdin); print('comfyui:', d['system']['comfyui_version'], '| vram_free_gb:', round(d['devices'][0]['vram_free']/1e9, 2))" && curl -sf http://127.0.0.1:8188/queue
Expected healthy output:
comfyui: 0.3.x | vram_free_gb: 14.82
{"queue_running": [], "queue_pending": []}

How to Prevent This Error From Recurring

GUARDRAIL 01

Use SSH port forwarding instead of public HTTP proxies for long WebSockets

Tunneling remote RunPod or workstation ports with ssh -L 8188:127.0.0.1:8188 bypasses 60–100 second Nginx and Cloudflare idle socket timeouts completely.

GUARDRAIL 02

Always parse node_errors from POST /prompt and status_str from /history

Treating non-empty node_errors or status_str == "error" as fatal exceptions stops batch scripts from hanging silently on missing checkpoints or VRAM spikes.

GUARDRAIL 03

Log every prompt_id to a local manifest immediately on submission

Writing prompt_id to comfy-manifest.json before polling lets your script resume and download completed outputs via /view even if your laptop sleeps or loses Wi-Fi mid-render.

Troubleshooting FAQs

If I want live step-by-step progress bars over WebSocket, how do I prevent proxy drops?
Open the WebSocket with your UUID clientId BEFORE sending POST /prompt, enable client-side keepalive pings every 20 seconds (ping_interval=20, ping_timeout=10 in websocket-client or websockets), set a 30-second recv timeout, and query /history/{prompt_id} on every timeout or disconnect exception.
Why does ComfyUI return an empty JSON object {} from GET /history/{prompt_id}?
An empty {} response means the job has not finished yet—it is either actively executing in queue_running or waiting in queue_pending. Always cross-check GET /queue so you can distinguish a healthy running job from a crashed worker that lost its in-memory queue.
Does polling /history every 4 seconds slow down GPU sampling speed?
No. Reading an in-memory dictionary over aiohttp takes under 1 millisecond on the CPU event loop and has zero measurable impact on PyTorch CUDA sampling throughput.
How do I cancel a hung ComfyUI batch remotely without restarting the container?
Send POST /interrupt to abort the currently sampling node, followed by POST /queue with JSON body {"clear": true} to flush all pending jobs, then optionally POST /free with {"unload_models": true, "free_memory": true} to reclaim VRAM.
Why did my script still wait forever even when ComfyUI printed "Prompt executed in 0.01 seconds"?
Because the graph hit ComfyUI execution cache and completed before your WebSocket subscribed, so your client never observed the executing:null message. Polling /history/{prompt_id} immediately resolves cached runs cleanly.
Use this page in AI tools or notes
raw .md