Production-ready automatic monitoring and restart solution for ComfyUI instances.
ComfyUI-Watchdog provides robust, event-driven monitoring that eliminates continuous polling loops while maintaining reliable health checking and automatic recovery capabilities. Battle-tested and ready for production deployment.
- Event-Driven Architecture: No continuous polling loops - uses timer-based callbacks for efficient resource usage
- HTTP Health Checking: Async batch health checks with configurable endpoints and retry logic
- Advanced Health Strategies: Hybrid health checking (majority consensus) and adaptive strategies that switch based on failure rates
- Process Monitoring: Three-phase process detection (port-based, pattern matching, PID file)
- Intelligent Restart: Graceful shutdown with exponential backoff and startup verification
- Advanced Restart Strategies: Exponential backoff and circuit breaker patterns for resilient recovery
- Multi-Instance Support: Monitor and manage multiple ComfyUI instances simultaneously
- CLI Management Tool: Comprehensive command-line interface for status, health checks, restarts, and service management
- Performance Optimization: Connection pooling, rate limiting, caching, and metrics collection
- Flexible Configuration: YAML/JSON configuration with environment variable overrides
- Structured Logging: JSON or text format with rotation support
- Cross-Platform: Windows and Linux support (macOS coming soon)
┌─────────────────────────────────────────────────────────────┐
│ ComfyUI-Watchdog System │
├─────────────────────────────────────────────────────────────┤
│ Configuration Manager → Watchdog Orchestrator │
│ ↓ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Health │ │ Process │ │ Restart │ │
│ │ Checker │ │ Monitor │ │ Manager │ │
│ └─────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
- Python 3.8 or higher
- ComfyUI installation
- pip package manager
# Clone the repository
git clone https://github.com/MushroomFleet/ComfyUI-Watchdog.git
cd comfy-crash-protections
# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .pip install -e ".[dev]"Create a config.yaml file based on the example:
cp config/config.example.yaml config.yamlEdit config.yaml to match your setup:
watchdog:
mode: "http" # http, process, or hybrid
check_interval: 30 # seconds between checks
instances:
- name: "comfyui-main"
host: "localhost"
port: 8188
comfyui_path: "C:\\MACHINES00\\ComfyUI_windows_portable_nvidia\\ComfyUI_windows_portable\\ComfyUI"
working_directory: "C:\\MACHINES00\\ComfyUI_windows_portable_nvidia\\ComfyUI_windows_portable"
python_path: "python_embeded\\python.exe"
startup_args: "--listen 0.0.0.0 --port 8188"
health_check:
timeout: 5
retries: 3
restart:
max_attempts: 5
cooldown: 10
exponential_backoff: true
grace_period: 5
logging:
level: "INFO"
format: "json"
rotation: "daily"
max_files: 7Override configuration via environment variables:
export COMFYUI_WATCHDOG_CONFIG=/path/to/config.yaml
export COMFYUI_WATCHDOG_MODE=http
export COMFYUI_WATCHDOG_INTERVAL=30
export COMFYUI_WATCHDOG_LOG_LEVEL=DEBUGThe watchdog includes a comprehensive CLI tool for managing instances:
# Show status of all instances
python -m src.cli --config config.yaml status
# Show status of specific instance
python -m src.cli --config config.yaml status comfyui-main
# Check health of specific instance
python -m src.cli --config config.yaml check comfyui-main
# Restart an instance
python -m src.cli --config config.yaml restart comfyui-main
# Restart without confirmation
python -m src.cli --config config.yaml restart comfyui-main --force
# List all configured instances
python -m src.cli --config config.yaml list
# Show current configuration
python -m src.cli --config config.yaml configRun the watchdog in continuous monitoring mode:
python -m src.orchestrator --config config.yamlFor cron/scheduled tasks:
python -m src.orchestrator --config config.yaml --onceOptions:
--config PATH Path to configuration file
--once Run once and exit (for scheduled execution)
--version Show version and exit
-h, --help Show help message
ComfyUI-Watchdog supports multiple deployment methods on both Windows and Linux. Use the automated installation scripts for the easiest setup.
Run the PowerShell installation script with administrator privileges:
# Run PowerShell as Administrator
.\scripts\install_windows.ps1The script will:
- Check for Python and install dependencies
- Optionally install NSSM (for Windows Service)
- Create configuration file
- Let you choose installation mode:
- Windows Service (NSSM) - Recommended for production
- Task Scheduler - Lighter weight option
- Manual - No automatic startup
Manage the service with NSSM commands:
# Start service
nssm start ComfyUIWatchdog
# Stop service
nssm stop ComfyUIWatchdog
# Check status
nssm status ComfyUIWatchdog
# Remove service
nssm remove ComfyUIWatchdog confirmManage scheduled task:
# View task
schtasks /query /tn ComfyUIWatchdog
# Run task manually
schtasks /run /tn ComfyUIWatchdog
# Delete task
schtasks /delete /tn ComfyUIWatchdog /fRun the bash installation script:
# Make script executable (if needed on Windows git checkout)
chmod +x scripts/install_linux.sh
# Run installation script
./scripts/install_linux.shThe script will:
- Check for Python 3 and install pip if needed
- Install dependencies
- Create configuration file
- Let you choose installation mode:
- systemd service - Recommended for production
- cron job - Lighter weight option
- Manual - No automatic startup
Manage the systemd service:
# Start service
sudo systemctl start comfyui-watchdog
# Stop service
sudo systemctl stop comfyui-watchdog
# Enable auto-start on boot
sudo systemctl enable comfyui-watchdog
# Check status
sudo systemctl status comfyui-watchdog
# View logs
sudo journalctl -u comfyui-watchdog -f
# Disable and remove
sudo systemctl disable comfyui-watchdog
sudo rm /etc/systemd/system/comfyui-watchdog.service
sudo systemctl daemon-reloadManage cron jobs:
# View crontab
crontab -l
# Edit crontab
crontab -e
# View logs
tail -f logs/cron.log
# Remove watchdog cron job
crontab -l | grep -v 'ComfyUI-Watchdog' | crontab -Docker support coming in Phase 4. See docs/05-implementation-phase4-docker-support.md for planned Docker integration.
- Makes HTTP requests to ComfyUI endpoints
- Fast and reliable for web-accessible instances
- Configurable timeout and retry logic
- Scans for ComfyUI processes by pattern/port
- Useful when HTTP is not available
- Slightly higher overhead
- Combines HTTP, process, and port checks
- Uses majority consensus (2 out of 3) for reliability
- More resilient to transient failures
- Example configuration:
watchdog: mode: "hybrid"
- Starts with fast HTTP checks
- Automatically switches to hybrid mode after repeated failures
- Resets to HTTP mode after successful checks
- Optimizes for both speed and reliability
- Configurable failure threshold:
from src.health_strategies import AdaptiveHealthChecker checker = AdaptiveHealthChecker(timeout=5) # Switches to hybrid after 3 failures (default)
1. HTTP Request → ComfyUI endpoint
2. Check Response Status (200 = healthy)
3. Record Response Time
4. Retry on Failure (configurable)
5. Mark as Unhealthy if all retries fail
6. Trigger Restart Process
- Fixed cooldown period between attempts
- Configurable maximum attempts
- Graceful shutdown with force kill fallback
- Increases delay between restart attempts exponentially
- Formula:
delay = cooldown * 2^(attempt_count) - Prevents rapid restart loops
- Maximum delay capped at 5 minutes
- Enable in configuration:
restart: exponential_backoff: true cooldown: 10 # Base delay in seconds
- Opens circuit after threshold failures
- Prevents restart attempts when circuit is open
- Automatically resets after timeout period
- Three states: closed (normal), open (blocking), half-open (testing)
- Example usage:
from src.restart_strategies import CircuitBreakerRestarter restarter = CircuitBreakerRestarter( circuit_threshold=3, # Open after 3 failures reset_timeout=300 # Reset after 5 minutes )
1. Detect Failure
2. Check Restart Eligibility
3. Check Circuit Breaker State (if enabled)
4. Apply Exponential Backoff Delay (if enabled)
5. Kill Existing Process (graceful → force)
6. Wait Cooldown Period
7. Execute Startup Command
8. Verify Startup (health check)
9. Update Circuit Breaker State
10. Record Success/Failure
Logs are written to:
- Console (stdout)
- File:
logs/watchdog.log
{
"timestamp": "2025-01-10T23:45:00Z",
"level": "INFO",
"logger": "comfyui_watchdog",
"message": "Health check passed for main",
"module": "health_check",
"function": "check_http",
"line": 52,
"instance": "main",
"response_time": 0.123
}2025-01-10 23:45:00 - comfyui_watchdog - INFO - Health check passed for main
- Reuses HTTP sessions for health checks
- Reduces connection overhead
- Configurable pool size:
from src.performance import ConnectionPool pool = ConnectionPool(max_size=10) session = await pool.acquire() # Use session... await pool.release(session)
- Prevents API rate limit violations
- Time-window based limiting
- Example usage:
from src.performance import RateLimiter limiter = RateLimiter(max_calls=10, time_window=60) await limiter.acquire() # Blocks if rate exceeded
- Async cache decorator with TTL
- Reduces redundant operations
- Example:
from src.performance import async_cache @async_cache(ttl=60) async def expensive_operation(arg): # Result cached for 60 seconds return result
- Counters, gauges, and histograms
- Performance monitoring and statistics
- Percentile calculations (P50, P95, P99)
- Example:
from src.performance import MetricsCollector metrics = MetricsCollector() metrics.increment('health_checks') metrics.set_gauge('active_instances', 5) metrics.record_histogram('response_time', 0.123) stats = metrics.get_histogram_stats('response_time') # {'count': 100, 'min': 0.05, 'max': 0.5, 'p50': 0.12, 'p95': 0.45}
- CPU: < 1% average, < 5% peak
- Memory: < 50MB resident
- Disk I/O: Minimal (logging only)
- Network: Health check requests only (with connection pooling)
Run the test suite:
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/test_models.py
# Run specific test category
pytest tests/test_health_strategies.py
pytest tests/test_restart_strategies.py
pytest tests/test_performance.py
pytest tests/test_cli.py
# Run with verbose output
pytest -v
# Run async tests
pytest -v -k "asyncio"The test suite includes:
- Core Components: Models, configuration, health checking, process monitoring, restart management
- Platform Integration: Windows and Linux platform adapters
- Advanced Features:
- Health strategies (hybrid, adaptive)
- Restart strategies (exponential backoff, circuit breaker)
- Performance utilities (connection pool, rate limiter, metrics)
- CLI tool (all commands and service management)
comfy-crash-protections/
├── src/
│ ├── __init__.py
│ ├── models.py # Data models
│ ├── exceptions.py # Custom exceptions
│ ├── config.py # Configuration management
│ ├── logger.py # Logging setup
│ ├── health_check.py # Health checking
│ ├── health_strategies.py # Advanced health strategies
│ ├── process_monitor.py # Process monitoring
│ ├── restart_manager.py # Restart management
│ ├── restart_strategies.py # Advanced restart strategies
│ ├── performance.py # Performance optimization
│ ├── cli.py # CLI management tool
│ ├── orchestrator.py # Main orchestrator
│ └── platform/
│ ├── __init__.py
│ ├── base.py
│ ├── windows.py
│ └── linux.py
├── tests/
│ ├── __init__.py
│ ├── test_models.py
│ ├── test_platform.py
│ ├── test_health_strategies.py
│ ├── test_restart_strategies.py
│ ├── test_performance.py
│ └── test_cli.py
├── config/
│ └── config.example.yaml
├── docs/
│ ├── 00-project-overview.md
│ ├── 01-architecture-design.md
│ ├── 02-implementation-phase1-core.md
│ ├── 03-implementation-phase2-platform-integration.md
│ ├── 04-implementation-phase3-advanced-features.md
│ └── ...
├── scripts/
│ ├── install_windows.ps1
│ └── install_linux.sh
├── logs/
├── requirements.txt
├── setup.py
└── README.md
-
Check configuration file exists and is valid:
python -c "from config import ConfigManager; ConfigManager('config.yaml').load_config()" -
Verify Python path and ComfyUI path are correct
-
Check logs in
logs/watchdog.log
-
Verify ComfyUI is accessible:
curl http://localhost:8188/
-
Check firewall/network settings
-
Increase timeout in configuration
-
Enable DEBUG logging for more details
- Verify Python path is correct
- Check ComfyUI startup args
- Review process permissions
- Check logs for startup errors
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
[Add your license here]
Built for the ComfyUI community to provide reliable, automatic crash recovery.
- Issues: GitHub Issues
- Documentation: See
docs/directory - Discussions: GitHub Discussions
- macOS support
- Docker integration
- Web dashboard
- Metrics/telemetry
- Slack/Discord notifications
- Advanced retry strategies
- Custom health check scripts
- Multi-node orchestration
Version: 1.0.0
Status: Production Ready - All Core Features Complete
Last Updated: 2025-01-11
For detailed setup and operation instructions, see:
- Windows: USER_GUIDE_Windows.md
- Linux: USER_GUIDE_Linux.md
If you use this codebase in your research or project, please cite:
@software{comfyui_watchdog,
title = {ComfyUI Watchdog: Automatic Crash Recovery for ComfyUI},
author = {[Drift Johnson]},
year = {2025},
url = {https://github.com/MushroomFleet/ComfyUI-Watchdog},
version = {1.0.0}
}