What is the difference between using Gunicorn with Uvicorn workers and using Uvicorn directly with multiple workers?
Gunicorn with Uvicorn workers provides a top-level Gunicorn process that supervises and manages multiple Uvicorn worker subprocesses. Running Uvicorn directly with multiple workers can also start several workers, but it does not do process management, so the Gunicorn method is usually preferred.
The book explains that Gunicorn is a WSGI server, while FastAPI is based on ASGI, so you use a special Uvicorn worker class managed by Gunicorn. In Example 13-1, the command starts a top-level Gunicorn process that supervises four Uvicorn worker subprocesses, all sharing port 8000. Example 13-2 shows that Uvicorn itself can also start multiple workers with the --workers flag. However, the Uvicorn approach does not include process management, which is why Gunicorn with Uvicorn workers is usually preferred in production. A process manager handles starting, monitoring, and restarting workers, and Gunicorn fills that role when used this way.
Key points
- Gunicorn is a WSGI server, but FastAPI is ASGI-based, so Gunicorn uses a special Uvicorn worker class.
- Gunicorn starts a top-level process that supervises multiple Uvicorn worker subprocesses.
- Uvicorn can also start multiple workers directly using the --workers flag.
- Uvicorn's direct multi-worker mode does not provide process management.
- The Gunicorn-with-Uvicorn-workers method is usually preferred because it includes process management.
Related questions
FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition · O'Reilly Media, Inc.