How Parallel Execution Works
Pyinfra uses a two-phase approach that enables fast, parallel execution:Phase 1: Prepare (Sequential)
Deploy code runs once per host to determine what operations to execute:- Executes deploy code for each host
- Builds operation order and dependencies
- Gathers facts needed for change detection
- Determines what commands will run
Phase 2: Execute (Parallel)
Operations execute in parallel across all hosts:Operations are sequential (ordered), but each operation executes in parallel across all hosts.
Operation Ordering
Operations execute in the order they appear in your deploy file:deploy.py
Performance Benefits
Parallel execution provides massive time savings:Controlling Parallelism
Limit Parallel Hosts
Control how many hosts execute operations simultaneously:- Rate limiting - Avoid overwhelming external services
- Resource constraints - Limit load on control machine
- Staged rollouts - Deploy to small batches first
Serial Execution for Specific Operations
Force an operation to run serially with_serial=True:
Group-Based Execution
Execute operations on specific groups in order:deploy.py
Handling Failures
By default, pyinfra continues executing even if some hosts fail:Fail Fast
Stop execution on first failure:Continue on Error
Force an operation to continue even if it fails:The deploy continues even if this operation fails on some hosts.
Progress Monitoring
Watch execution progress in real-time:Large-Scale Deployments
Optimizations for deploying to many hosts:Use Connection Pooling
SSH connections are pooled and reused:Limit Fact Gathering
Only gather facts you actually use:Batch Operations
Group similar operations together:Real-World Example: Rolling Update
Deploy updates in waves to maintain availability:deploy.py
Targeted Execution
Run operations on specific hosts:Performance Comparison
Real-world deployment times:Times assume each operation takes ~3 seconds per host. Actual times vary based on operation complexity and network speed.
Best Practices
Understanding the Prepare Phase
The prepare phase is critical for parallel execution:deploy.py
The prepare phase must complete for all hosts before any operations execute. This ensures correct operation ordering.
Next Steps
- Idempotent Operations - Optimize parallel execution with idempotency
- Deploying Applications - Build scalable deployments
- Inventory and Data - Organize large host inventories
