Production ASGI Architecture: Gunicorn with Uvicorn Workers
1Concept
Gunicorn acts as the master process manager (handling worker restarts, OS signals, and socket bindings), while Uvicorn worker classes (`UvicornWorker`) execute the asynchronous event loops.
2Architecture Diagram
Gunicorn Master Process (Monitors workers, binds port 8000) ├── Worker 1 (Uvicorn Worker - Async Event Loop) ├── Worker 2 (Uvicorn Worker - Async Event Loop) └── Worker 3 (Uvicorn Worker - Async Event Loop)
3Code Example
Python 3.12
gunicorn_cmd = '''
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--timeout 60 \
--access-logfile - \
--error-logfile -
'''
print("=== Production Gunicorn + Uvicorn Deployment ===")
print(gunicorn_cmd.strip())4Expected Output
=== Production Gunicorn + Uvicorn Deployment ===
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--timeout 60 \
--access-logfile - \
--error-logfile -5Key Takeaways
- ✓Rule of thumb for workers: `workers = (2 * CPU_cores) + 1`.
- ✓Gunicorn gracefully restarts workers that exceed memory limits (`--max-requests 1000`).
- ✓Logs are streamed directly to stdout (`-`) for container aggregation (Fluentd/Datadog).