You start a FastAPI app using Gunicorn with Uvicorn workers like this:
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
What is the expected behavior?
Think about how Gunicorn and Uvicorn work together to handle async FastAPI apps.
Gunicorn can manage multiple worker processes. Using the Uvicorn worker class allows each worker to run an async server that serves the FastAPI app concurrently.
Choose the correct command to run a FastAPI app defined in app.py with 3 Uvicorn workers using Gunicorn.
Remember the order: number of workers (-w), worker class (-k), then app module.
The correct syntax is gunicorn -w 3 -k uvicorn.workers.UvicornWorker app:app. Options A, B, and D have incorrect order or wrong flags.
Consider this main.py:
def create_app():
from fastapi import FastAPI
app = FastAPI()
return app
You run:
gunicorn -w 2 -k uvicorn.workers.UvicornWorker main:app
But Gunicorn fails to start. Why?
Think about how Gunicorn imports the app object.
Gunicorn imports the app variable at the module level. Since the function defines but does not instantiate app at module level (missing app = create_app()), app is undefined, causing the failure.
You run this command:
gunicorn -w 2 -k uvicorn.workers.UvicornWorker main:app --reload
What happens?
Consider which server handles reload in this setup.
Gunicorn's --reload flag does not work well with Uvicorn workers. Uvicorn itself supports reload, but when run under Gunicorn, reload is ignored. So no automatic reload happens.
Explain why using Gunicorn with multiple Uvicorn workers is better than running a single Uvicorn server for a FastAPI app in production.
Think about how multiple processes help with CPU usage and concurrency.
Gunicorn can spawn multiple worker processes, each running a Uvicorn server. This allows the app to use multiple CPU cores and handle many requests concurrently, improving performance and reliability in production.