Introduction
The WebSocket API provides real-time, bidirectional communication between your client application and the ComfyUI server. Use it to monitor workflow execution, receive progress updates, and get preview images as they’re generated.Connection Endpoint
Connect to the WebSocket endpoint using the following URL format:The ComfyUI server address (e.g.,
127.0.0.1:8188)A unique identifier for your client session. If not provided, the server generates one automatically. Providing a
clientId allows you to reconnect and resume an existing session.Connection Example
Here’s how to establish a WebSocket connection using Python:Initial Handshake
Server to Client: Initial Status
When you first connect, the server immediately sends astatus message with the current queue state and your session ID:
Reconnection Behavior
If you reconnect with an existingclientId and that client was executing a workflow, the server sends the current executing node:
The server removes any previous WebSocket connection with the same
clientId when you reconnect, ensuring only one active connection per client.Feature Flags Negotiation
ComfyUI supports feature flag negotiation between client and server. Send afeature_flags message as your first message after connecting:
Client to Server
Server Response
The server responds with its supported features:Feature flag negotiation is optional but recommended for advanced clients that want to leverage server capabilities.
Message Types
WebSocket messages come in two formats:JSON Messages
Text messages with the following structure:Binary Messages
Binary messages contain preview images and other binary data. The format is:Tracking Workflow Execution
Here’s a complete example that queues a prompt and waits for execution to complete:Error Handling
The WebSocket connection can fail for several reasons. Always implement proper error handling:Best Practices
Use a Unique Client ID
Use a Unique Client ID
Generate a unique
clientId (UUID) for each client instance to avoid conflicts and enable proper session management.Handle Both Message Types
Handle Both Message Types
Always check if received data is a string (JSON) or binary data. Binary messages contain preview images.
Track Prompt IDs
Track Prompt IDs
When queuing prompts, include the
client_id in the request and track prompt_id values to match execution events with your workflows.Implement Reconnection Logic
Implement Reconnection Logic
Network issues can disconnect WebSocket connections. Implement exponential backoff reconnection with your original
clientId.Close Connections Properly
Close Connections Properly
Always close WebSocket connections when done, especially in environments with repeated calls (like web servers or Gradio apps).
Next Steps
WebSocket Events
Learn about all WebSocket event types and their data structures
Queue Prompt
Submit workflows for execution via the HTTP API