Why Multiple Workers?
Running multiple processes provides several benefits:- Utilize multiple CPU cores - Each worker can run on a different core
- Handle more requests - Distribute load across workers
- Improve fault tolerance - If one worker crashes, others continue serving requests
- Increase throughput - Process multiple requests in parallel
During development, you typically run a single process. In production, you’ll want multiple workers for better performance.
Process and Replication
From the deployment concepts, multiple workers address:- ✅ Replication - Running multiple processes
- ✅ Restarts - Process managers can restart dead workers
- ⚠️ Security (HTTPS) - Still needs external handling
- ⚠️ Running on Startup - Needs system configuration
- ⚠️ Memory - Each worker consumes memory
Using Uvicorn with Workers
Uvicorn can manage multiple worker processes directly.With FastAPI CLI
With Uvicorn Directly
1
Parent Process
One parent process (PID 27365) acts as the process manager.
2
Worker Processes
Four worker processes (PIDs 27368-27371) handle actual requests.
3
Load Balancing
The parent distributes incoming requests among workers.
4
Health Monitoring
The parent monitors workers and restarts them if they crash.
Determining Worker Count
The optimal number of workers depends on your application and hardware.General Formula
- 2 cores: 5 workers
- 4 cores: 9 workers
- 8 cores: 17 workers
Check CPU Cores
Application-Specific Considerations
I/O-Bound Applications (database queries, API calls):- Fewer workers needed
- FastAPI’s async capabilities handle many concurrent requests per worker
- Start with
workers = CPU_cores
- More workers beneficial
- Use the formula:
(2 * CPU_cores) + 1
Using Gunicorn with Uvicorn Workers
Gunicorn is a mature process manager that can use Uvicorn workers.Installation
Basic Usage
With Configuration File
Create gunicorn_conf.py:Gunicorn provides more advanced process management features than Uvicorn’s built-in worker support.
Advanced Gunicorn Configuration
Auto-Restart on Code Changes
For development (not production):Worker Lifecycle Hooks
Custom Worker Management
Process Managers for Production
For production deployments, use a system-level process manager.Systemd (Linux)
Create /etc/systemd/system/fastapi.service:Supervisor
Create /etc/supervisor/conf.d/fastapi.conf:Container Environments
Docker Compose
For Docker Compose, use workers in the container:Kubernetes
For Kubernetes, don’t use workers. Instead, run one process per container and let Kubernetes replicate:Memory Considerations
Each worker process consumes memory independently.Example Memory Usage
If your application uses 500MB per process:- 1 worker: 500MB
- 4 workers: 2GB
- 8 workers: 4GB
Large Memory Objects
If loading large objects (ML models, cached data):- Model size: 1GB
- 4 workers: 4GB total memory for models
Consider using fewer workers or shared memory solutions when dealing with large in-memory objects.
Load Balancing
When running multiple workers, the process manager handles load balancing automatically.Uvicorn Workers
Uvicorn’s parent process distributes requests using the OS scheduler.Gunicorn Workers
Gunicorn uses a pre-fork model:- Master process accepts connections
- Connections distributed to workers
- Workers process requests independently
External Load Balancers
For multiple servers, use external load balancers:- Nginx - HTTP load balancer
- HAProxy - TCP/HTTP load balancer
- Traefik - Modern reverse proxy with automatic service discovery
- Cloud Load Balancers - AWS ALB, GCP Load Balancer, Azure Load Balancer
Monitoring Workers
Using ps
Using htop
Programmatic Monitoring
Graceful Shutdown
Ensure workers shutdown gracefully to finish processing requests.Gunicorn Configuration
FastAPI Lifespan Events
Performance Tuning
Worker Timeout
Increase timeout for long-running requests:Keep-Alive Connections
Worker Connections
For Uvicorn workers, control max connections:Troubleshooting
Workers Dying Unexpectedly
Check logs for:- Memory issues: Out of memory (OOM) killer
- Timeouts: Requests taking too long
- Exceptions: Unhandled errors crashing workers
High CPU Usage
- Too many workers for available cores
- CPU-intensive operations blocking workers
- Consider reducing worker count or optimizing code
Memory Leaks
Usemax_requests to periodically restart workers:
Recap
Multiple workers improve FastAPI performance by:- ✅ Utilizing multiple CPU cores for better throughput
- ✅ Handling more concurrent requests across workers
- ✅ Providing fault tolerance if a worker crashes
- ✅ Automatic restarts with process managers
- Single server: Use
--workerswith Uvicorn or Gunicorn - Containers (Kubernetes): One process per container, let orchestrator replicate
- Worker count: Start with
(2 * CPU_cores) + 1, adjust based on monitoring - Memory: Ensure enough RAM for all workers plus overhead