
ComfyUI WebSocket API: Every Message, Tested on 0.33
To use the ComfyUI WebSocket API, connect to /ws?clientId=<uuid> before you queue, send the same client_id in POST /prompt, keep only messages whose prompt_id matches, and stop on execution_success, execution_error or execution_interrupted. That's the short version. The long version is what happens on cache hits, reconnects, missing client IDs and a crashed worker. I captured every message ComfyUI 0.33.0 sent across all of those this morning, and my own render box gave me the nastiest case for free.
What Does a Normal ComfyUI WebSocket Run Look Like?
Here's a real 12-step job on ComfyUI 0.33.0, timestamped from the moment my client opened the socket. The node is a small probe I wrote that behaves like a sampler: it reports progress every step and sends a JPEG preview, then a SaveImage writes the result.
t (s) message data
1.063 HTTP 200 /prompt {"prompt_id": "df7b...", "number": 6, "node_errors": {}}
1.110 status {"exec_info": {"queue_remaining": 0}, "sid": "<your clientId>"}
1.127 status (x2) {"exec_info": {"queue_remaining": 1}}
1.129 execution_start {"prompt_id": "df7b...", "timestamp": ...}
1.129 execution_cached {"nodes": [], "prompt_id": "df7b..."}
1.129 progress_state {"1": running 0/1}
1.129 executing {"node": "1", "display_node": "1", "prompt_id": "df7b..."}
1.497 progress_state + progress {"value": 1, "max": 12, "node": "1", ...}
1.498 BINARY type=1 fmt=1 2,943 bytes, JPEG preview
... (x12, one trio per step)
5.771 progress_state {"1": finished 12/12, "2": running}
5.771 executing {"node": "2", ...}
5.775 executed {"node": "2", "output": {"images": [{"filename": "zz_00002_.png", ...}]}}
5.776 execution_success {"prompt_id": "df7b...", "timestamp": ...}
5.777 executing {"node": null, "prompt_id": "df7b..."}Three things in there aren't in the official message table. progress_state fires about as often as progress (16 times in this 12-step run) and carries the state of every node in the graph: running or finished, plus value and max. The binary frames are the previews. And the first status message hands back your own clientId as sid, which is a cheap way to confirm the server registered the ID you think it did.
The executed message is where your output filenames come from. It only fires for nodes that return UI data (SaveImage, PreviewImage and similar), not for every node that finishes.
Which Message Means the Job Is Done?
Two candidates. The official websockets example waits for executing with node: null. Newer clients wait for execution_success. In 0.33.0 the success event is sent from inside the executor, and the null executing is sent from the queue worker after it writes history. Over 10 runs the gap between them was 1.0 to 2.8 ms, and GET /history/<prompt_id> already had the outputs when I called it on the success event in all 10.
I end on the three execution_* terminal events, because they cover failure too. In main.py the null executing is also sent after a failed job, so if you rely on it you still have to look back for an execution_errorto know which way it went. If you've ever had history come back empty right after a job, my post on why /history returns an empty object covers the other causes.
Why Does My Progress Bar Never Move on Some Runs?
Because the run was cached. I queued the same graph twice. The second run took 1 ms and sent this:
execution_start {"prompt_id": "1609..."}
execution_cached {"nodes": ["1", "2"], "prompt_id": "1609..."}
executed {"node": "2", "output": {"images": [{"filename": "zz_00002_.png"}]}}
progress_state {"2": finished 1/1}
execution_success {"prompt_id": "1609..."}
# no executing, no progress, no previews. Total: 1 ms.No executing, no progress, no previews. The executed message is replayed from cache with the same filename as the first run, so a client that tracks outputs by filename gets zz_00002_.png twice and nothing new is written to disk. Any client that finishes when progress.value == progress.maxwaits forever here. Any UI that shows the "current node" from executingsits on its last value. Fixed seeds in production are the usual trigger: same inputs, same cache key, instant "done".
Who Receives Which Messages?
I kept two extra sockets open on every run, one with a random clientId and one with none, and then queued one job with no client_id at all:
| Socket | Receives | Never sees |
|---|---|---|
| Socket with the job's clientId | Everything: status, execution_*, executing, progress, progress_state, executed, previews | Nothing |
| Socket with a different clientId | status (queue_remaining) only | All job messages, including errors |
| Socket with no clientId | status only (the server assigns a hex sid) | All job messages |
| Any socket, job queued WITHOUT client_id | status, progress, progress_state, previews (broadcast) | execution_start, executing, executed, execution_success |
That last row is a trap: without a client_id, everyone sees the progress bar and nobody sees the job finish. Progress hooks broadcast when there's no target, but the execution messages are only sent to a known client. The same split means an execution_error goes to the submitting socket only. A dashboard watching the server from a second connection never learns that a job failed. It only sees queue_remaining drop back to 0.
How Do I Decode the Binary Preview Frames?
Every binary message starts with a 4-byte big-endian event type. By default you get type 1, which has no prompt_idin it, so with two jobs in flight you can't tell whose preview it is. Send a feature_flags message as the very first thing on the socket and the server switches you to type 4, which has JSON metadata in front of the image:
# first message after connecting
{"type": "feature_flags", "data": {"supports_preview_metadata": true}}
# server reply on 0.33.0
{"type": "feature_flags", "data": {"supports_preview_metadata": true,
"supports_model_type_tags": true, "max_upload_size": 104857600,
"extension": {"manager": {"supports_v4": true}}, "node_replacements": true, "assets": false}}# Type 1 (default) # Type 4 (after the feature_flags handshake)
[0:4] event type = 1 [0:4] event type = 4
[4:8] format: 1 = JPEG, 2 = PNG [4:8] metadata length N
[8:] image bytes [8:8+N] {"node_id": "1", "prompt_id": "a2e1...",
"display_node_id": "1", "real_node_id": "1",
"parent_node_id": null, "image_type": "image/jpeg"}
[8+N:] image bytesIt has to be the first message. The server only checks for the handshake on the first frame it receives. Whether you get previews at all depends on the server's --preview-method. My render box runs latent2rgb, which gives a cheap low-res preview per sampler step. Type 3 frames carry streamed text from nodes that call send_progress_text (4-byte node id length, node id, then UTF-8 text), and type 2 never reaches you over the wire, because the server encodes it to type 1 first.
What Happens When the Socket Drops Mid-Job?
The job doesn't care. I closed my socket at step 10 of 40, waited 4 seconds, and reconnected with the same clientId:
4.893 A progress 10/40
4.896 A client closes the socket
8.907 A2 reconnect with the SAME clientId
8.907 A2 status {"exec_info": {"queue_remaining": 1}, "sid": "<same clientId>"}
8.907 A2 executing {"node": "1"} <- no prompt_id
9.139 A2 progress 22/40 <- steps 11-21 never arrive
15.896 A2 execution_successReconnecting with the same clientId resumes the stream, but nothing is replayed. The server sends one courtesy executing for the current node, and that message has no prompt_id, so a strict filter drops it. Steps 11 through 21 are gone. You still get execution_successbecause it's addressed to the clientId, not the socket. If you reconnect with a new UUID, you get nothing for that job ever again. So keep the clientId for the life of the job, and after any reconnect read GET /queue and GET /history/<prompt_id> to find out what you missed.
What Do Errors, Interrupts and Silence Look Like?
A node that raises at step 5 produces one execution_error with node_id, node_type, exception_type, exception_message, the full traceback and the list of nodes that had already run. POST /interrupt at step 10 produced execution_interrupted about 400 ms later, and one more preview frame arrived after the interrupt request. Don't treat "a preview arrived" as "still running".
A graph that fails validation gets an HTTP 400 and zero WebSocket messages. The job never existed. I covered how to read that body in prompt outputs failed validation.
The worst case came from my own GPU box. While I rendered this post's hero on La Bestia (an RTX 5090 running ComfyUI 0.33.0), the first job died loading a checkpoint with 'NoneType' object has no attribute 'is_dynamic'. That one at least sent a clean execution_error. The next job got 200 and a prompt_id, and then this happened in the server log:
09:11:03 got prompt <- POST /prompt answered 200
09:11:03 Exception in thread Thread-23 (prompt_worker):
File "C:\AI\ComfyUI\comfy\model_management.py", line 828, in is_dead
return self.real_model() is not None and self.model is None
TypeError: 'NoneType' object is not callable
# socket: status queue_remaining=1, then ~1 custom-node broadcast per second, for 400 s.
# /queue: the prompt sits in queue_running forever.The worker thread died. The HTTP server and the socket did not. ComfyUI kept accepting prompts, the socket stayed open, and a custom node kept broadcasting a system-monitor message about once a second. To a client that looks exactly like a long queue. My capture script sat there for 400 seconds until its outer timeout killed it. The first draft of the client below had the same blind spot: it only checked its watchdog when recv() timed out, and a chatty socket never goes quiet long enough for that. I only caught it because a test job stuck behind another job's broadcast progress never timed out. The only fix for a dead worker is a restart, so the client's job is to notice fast and tell a human.
A ComfyUI WebSocket Client That Handles All of This
This is the client I ended up with. I ran it against 0.33.0 for a normal run, a cache hit, a forced error, and a job stuck behind a 60-step job that another client had queued. The watchdog fired at 6.1 s with a 6 s start_timeout.
import json, struct, time, uuid, urllib.request
import websocket # pip install websocket-client
SERVER = "127.0.0.1:8188"
TERMINAL = {"execution_success", "execution_error", "execution_interrupted"}
def run(graph, start_timeout=30, idle_timeout=120):
client_id = str(uuid.uuid4())
ws = websocket.create_connection(f"ws://{SERVER}/ws?clientId={client_id}", timeout=5)
ws.send(json.dumps({"type": "feature_flags", "data": {"supports_preview_metadata": True}}))
req = urllib.request.Request(f"http://{SERVER}/prompt",
data=json.dumps({"prompt": graph, "client_id": client_id}).encode(),
headers={"Content-Type": "application/json"})
resp = json.loads(urllib.request.urlopen(req).read()) # a 400 raises here: no socket message comes
if resp.get("node_errors"):
raise RuntimeError(f"partial validation failure: {resp['node_errors']}")
prompt_id, started, last_msg = resp["prompt_id"], False, time.time()
while True:
limit = idle_timeout if started else start_timeout
if time.time() - last_msg > limit: # check every loop: chatter never times out recv()
ws.close()
raise TimeoutError(f"no events for {prompt_id} in {limit}s, check GET /queue")
try:
msg = ws.recv()
except websocket.WebSocketTimeoutException:
continue
if isinstance(msg, bytes):
if struct.unpack(">I", msg[:4])[0] == 4: # preview with metadata
n = struct.unpack(">I", msg[4:8])[0]
meta, jpeg = json.loads(msg[8:8 + n]), msg[8 + n:]
if meta["prompt_id"] == prompt_id:
pass # show jpeg in your UI
continue
m = json.loads(msg)
data = m.get("data") or {}
if data.get("prompt_id") != prompt_id:
continue # status heartbeats and custom-node broadcasts land here
last_msg = time.time()
if m["type"] == "execution_start":
started = True
elif m["type"] == "progress":
print(f"node {data['node']}: {data['value']}/{data['max']}")
elif m["type"] in TERMINAL:
ws.close()
if m["type"] != "execution_success":
raise RuntimeError(f"{m['type']}: {data.get('exception_message', '')}")
hist = json.loads(urllib.request.urlopen(f"http://{SERVER}/history/{prompt_id}").read())
return hist[prompt_id]["outputs"]Set start_timeout to cover your normal queue wait, or have it check GET /queue and only fail if your prompt is stuck in queue_running with no events. If your ComfyUI sits behind Cloudflare or nginx, the WebSocket handshake goes through the same origin check as everything else. My ComfyUI 403 behind a reverse proxy post has the headers.
How I Tested This
ComfyUI 0.33.0 (tag v0.33.0, frontend 1.48.7) on a Mac mini with --cpu, plus a probe node that sleeps per step, calls ProgressBar.update_absolute with a JPEG preview and returns a flat image. No model was needed, which made every run repeatable. Each scenario used three sockets: the submitter, a second clientId, and a socket with no clientId. Python websockets17.4 logged every frame with a timestamp. The dead-worker trace came from my real ComfyUI server (reports 0.33.0, frontend 1.49.6) on Windows with an RTX 5090, reached through a Cloudflare Tunnel. I didn't restart it, so that capture is one event, not a pattern. The message sources are server.py, execution.py, main.py and comfy_execution/progress.py in the same tag. If custom node packs are what keep breaking your server, start with ComfyUI IMPORT FAILED.
Building an App on Top of ComfyUI?
I build ComfyUI backends that queue, track and recover jobs without someone watching a terminal. If yours hangs, double-renders or loses outputs, send me the client code.
Related Posts
AI Models
ComfyUI Prompt Outputs Failed Validation: API Fix
ComfyUI's validation error is an HTTP 400 whose real reason lives in node_errors. Tested 11 broken graphs on ComfyUI 0.33.0, found a 200 response that silently skips broken outputs, and built a preflight against /object_info that catches all of them.
AI Models
ComfyUI API /history Empty? Why and the Fix
ComfyUI only writes a history entry when a job finishes, so an empty /history/{prompt_id} can mean still running, never accepted, wiped by a restart, or evicted. Checking /queue tells them apart; status_str and the actual file tell you if it worked.
AI Models
ComfyUI IMPORT FAILED: How to Fix Custom Node Errors
IMPORT FAILED means a custom node pack crashed while loading. 17 failures from my own ComfyUI logs came from four causes: a broken stdout, the wrong Python, a moved diffusers module, and a bug. Plus one pack that failed silently.