FastAPI interview question · Most asked
How do you deploy FastAPI in production?
Summary
Run Uvicorn with multiple worker processes (uvicorn --workers N or Gunicorn with uvicorn.workers.UvicornWorker), behind a reverse proxy or load balancer, usually in containers, with health checks and proper proxy header handling.
Longer Answer
Rule of thumb: start with workers ≈ CPU cores and tune with load tests. In Kubernetes, many teams run one worker per container and scale pods instead. Set --proxy-headers and --forwarded-allow-ips behind a proxy so request.client and scheme are right. The FastAPI CLI (fastapi run) wraps Uvicorn for production.
Code Example
# Dockerfile (simplified)
FROM python:3.13-slim
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN pip install uv && uv sync --frozen --no-dev
COPY app ./app
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--proxy-headers"]
Key Points
- Multiple worker processes for CPU parallelism
- Reverse proxy/LB in front (TLS, buffering)
- One worker per container in Kubernetes is common
- Health/readiness endpoints
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?