Lesson 57 of 59Production
Deploying FastAPI
Run FastAPI in production behind a proxy, containerise it, add health checks and CORS, and choose where to host it.
An API that only runs on your laptop is a demo. Deploying it means answering a set of practical questions: how many processes, who handles HTTPS, where secrets come from, how the platform knows the app is healthy, where the database lives, and how you find out when something breaks. A deployed project with a live URL is also one of the strongest things you can put on a resume.
The shape of a deployed API
The React or Next.js frontend is served separately, often from a CDN on its own domain.
Running Uvicorn in production
In development you used fastapi dev with auto-reload. In production:
fastapi run app/main.py --port 8000 --workers 4# or, equivalentlyuvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4 --proxy-headers --forwarded-allow-ips="*"- No
--reload. It watches files and restarts, which wastes resources and can restart mid-request. --host 0.0.0.0so traffic from outside the container can reach it.- Workers. Each is a separate process with its own event loop and its own memory. Start with about one per CPU core and measure. On platforms that run many small containers (Kubernetes, ECS, Fly), it is common to run one process per container and let the platform add containers instead.
- Proxy headers. Behind a load balancer, every connection comes from the proxy's IP, and the original HTTPS is gone. The proxy adds
X-Forwarded-For(client IP) andX-Forwarded-Proto(original scheme).--proxy-headerstells Uvicorn to trust them, so redirects usehttps://and your logs and rate limiter see real client IPs. Only trust these headers from your own proxy, since clients can send fake ones.
Press Run (⌘ Enter) to see what happens.The second call shows why you read from the right: a client can put anything at the start of the header (6.6.6.6 here), but the entry your own proxy appended is trustworthy. The third call ignores the header entirely because the connection did not come from your proxy.
Using client_ip and proxies above, what does this print?
print(client_ip("10.0.0.5", {}, proxies))A Dockerfile for FastAPI
Containers make "it works on my machine" true everywhere. This Dockerfile uses uv, installs dependencies in their own layer so code changes do not reinstall everything, and runs as a non-root user.
FROM python:3.13-slim
# uv binary from its official image (pin an exact version in real projects)
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy PYTHONUNBUFFERED=1
# 1. Dependencies only: this layer is cached until pyproject.toml or uv.lock change
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project
# 2. Your code
COPY . .
RUN uv sync --frozen --no-dev
ENV PATH="/app/.venv/bin:$PATH"
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["fastapi", "run", "app/main.py", "--port", "8000"]docker build -t todo-api .docker run --rm -p 8000:8000 --env-file .env todo-apiAdd a .dockerignore with .venv, .env, .git and __pycache__ so secrets and junk never enter the image. PYTHONUNBUFFERED=1 makes logs appear immediately instead of sitting in a buffer. The Docker course goes much deeper on images, layers and Compose.
pyproject.toml and uv.lock and install dependencies before COPY . .?Health checks
Platforms need to know whether a container is alive and ready for traffic. Two endpoints are standard:
- Liveness (
/health): is the process up and responding? It should be trivial and never touch the database. If it fails, the platform restarts the container. - Readiness (
/ready): can it do useful work right now? Check the database (and other critical dependencies) with a short timeout. If it fails, the load balancer stops sending traffic but does not restart it.
from fastapi import APIRouter, Response, status
from sqlalchemy import text
router = APIRouter(tags=["health"])
@router.get("/health")
def health() -> dict:
return {"status": "ok"}
@router.get("/ready")
def ready(db: DB, response: Response) -> dict:
try:
db.execute(text("SELECT 1"))
except Exception:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "down", "database": "unreachable"}
return {"status": "ok", "database": "ok"}Configure the platform's health check path to /health or /ready. Return 503 Service Unavailable when not ready, because load balancers look at the status code, not the body.
CORS for a separate frontend
With the frontend on https://app.example.com and the API on https://api.example.com, the browser treats them as different origins, so you need CORSMiddleware (from the middleware lesson) with the exact production origins, loaded from settings:
app.add_middleware(
CORSMiddleware,
allow_origins=settings.allowed_origins, # ["https://app.example.com"]
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)If auth uses cookies, app.example.com and api.example.com are the same site (same registrable domain), so SameSite=Lax cookies work. If the frontend is on a completely different domain (say a vercel.app preview URL), cookies need SameSite=None; Secure, which is one more reason to put both under your own domain.
Where to host it
| Option | What you give it | Good for | Watch out for |
|---|---|---|---|
| Render, Railway, Fly.io | A Git repo or Dockerfile | Side projects to mid-size apps; managed Postgres nearby | Free tiers sleep; costs grow with always-on instances |
| AWS ECS on Fargate | A container image | Production on AWS, fine-grained networking and scaling | More setup: VPC, load balancer, IAM, task definitions |
| AWS App Runner | A container image | The simplest AWS container hosting | Fewer knobs than ECS; check it is still open to new accounts |
| Vercel (Python functions) | Your FastAPI app as a function | APIs that sit next to a Next.js frontend | Serverless limits: no long-running background work or persistent WebSockets, cold starts |
| A VM (EC2, a VPS) | SSH and Docker Compose | Full control, predictable cost | You patch, secure and monitor everything |
For the database, use a managed PostgreSQL: Neon, Supabase, Render or Railway Postgres, or AWS RDS / Aurora. They handle backups, upgrades and failover. Keep the database in the same region as the API (each query is a round trip), and use a connection pooler such as PgBouncer (or the provider's built-in pooling) when you run many processes or serverless functions, since PostgreSQL has a fairly low connection limit.
Match each need to a sensible hosting choice.
Deploying safely
A good deploy is boring and repeatable. CI (for example GitHub Actions) runs the same steps every time:
Order a typical deploy pipeline for a FastAPI service.
- Tap the steps below in the right order.
Once it is live, you need to see it:
- Logs: JSON to stdout with a request id, collected by the platform (CloudWatch, Datadog, Better Stack, Grafana Loki).
- Errors: an error tracker like Sentry captures exceptions with stack traces and the request that caused them.
- Metrics and traces: request rate, error rate and latency (p50, p95, p99), often via OpenTelemetry. Alert on error rate and p95 latency, not on every log line.
- Uptime: an external check that hits
/healthevery minute and pages you if it fails.
With that, your API is built, tested, shipped and watched. Next, the project puts the core of it to work on your own machine: you build a warehouse stock API from an empty folder, stage by stage.
Practice
Readiness report
A /ready endpoint checks each dependency and tells the load balancer whether to send traffic. Write health_report(results, critical):
resultsmaps a dependency name to whether its check passed, e.g.{"db": True, "cache": False}.criticallists the dependencies the app cannot work without.
Return {"status": ..., "code": ..., "failing": [...]}:
| Situation | status | code |
|---|---|---|
| everything passed | "ok" | 200 |
| only non-critical checks failed | "degraded" | 200 |
| any critical dependency failed | "down" | 503 |
failing is the sorted list of every failed name. A critical dependency that is missing from results was never checked, so treat it as failed (and include it in failing).
health_report({"db": True, "cache": False}, ["db"])
-> {"status": "degraded", "code": 200, "failing": ["cache"]}Compute CORS headers
Do what CORSMiddleware does for one request. Write cors_headers(origin, method, allowed_origins, allow_credentials) returning the headers dict to add to the response.
originis the request'sOriginheader, orNone(same-origin requests and non-browser clients send none). No origin: return{}.- The origin is allowed if it is in
allowed_origins(exact string match) orallowed_originscontains"*". Not allowed: return{}(the browser will then block the page from reading the response). - If allowed:
"Access-Control-Allow-Origin":"*"only when"*"is in the list andallow_credentialsisFalse. Otherwise echo the exact origin and also set"Vary": "Origin"(so caches do not serve one origin's response to another).- If
allow_credentials:"Access-Control-Allow-Credentials": "true". - If
method == "OPTIONS"(a preflight): also"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE"and"Access-Control-Max-Age": "600".
cors_headers("https://app.example.com", "GET", ["https://app.example.com"], True)
-> {"Access-Control-Allow-Origin": "https://app.example.com", "Vary": "Origin",
"Access-Control-Allow-Credentials": "true"}- reverse proxy
- A server in front of your app (Nginx, a load balancer) that terminates TLS and forwards requests.
- X-Forwarded-For
- Header a proxy adds with the client's IP. Trust it only from your own proxy, reading from the right.
- liveness check
- A cheap endpoint showing the process is up. Failing it gets the container restarted.
- readiness check
- Shows the app can serve traffic (database reachable). Failing it removes the container from the load balancer.
- managed database
- A hosted PostgreSQL (RDS, Neon, Supabase) with backups, upgrades and failover handled for you.
- rollback
- Redeploying the previous image when a release misbehaves. Tag images with the commit SHA to make it easy.