Skip to content

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.

18 min read0/5 questions

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

A typical FastAPI deployment
Private networkUsersUsersFrontend: app.example.comFrontendapp.example.comLoad balancer: TLS, api.example.comLoad balancerTLS, api.example.comAPI container 1: Uvicorn workersAPI container 1Uvicorn workersAPI container 2: Uvicorn workersAPI container 2Uvicorn workersPostgreSQL: managedPostgreSQLmanagedRedis: cache, job queueRediscache, job queueLogs and errors: Sentry, CloudWatchLogs and errorsSentry, CloudWatchHTTPSAPI callsHTTPHTTPSQLSQL

The React or Next.js frontend is served separately, often from a CDN on its own domain.

1/5

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.0 so 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) and X-Forwarded-Proto (original scheme). --proxy-headers tells Uvicorn to trust them, so redirects use https:// and your logs and rate limiter see real client IPs. Only trust these headers from your own proxy, since clients can send fake ones.
Pythonforwarded_for.py
def client_ip(peer_ip, headers, trusted_proxies): """Walk X-Forwarded-For from the right, skipping our own proxies.""" if peer_ip not in trusted_proxies: return peer_ip # not via our proxy: ignore the header hops = [h.strip() for h in headers.get("x-forwarded-for", "").split(",") if h.strip()] for ip in reversed(hops): if ip not in trusted_proxies: return ip return peer_ip proxies = {"10.0.0.5"}print(client_ip("10.0.0.5", {"x-forwarded-for": "203.0.113.9"}, proxies))print(client_ip("10.0.0.5", {"x-forwarded-for": "6.6.6.6, 203.0.113.9"}, proxies))print(client_ip("198.51.100.7", {"x-forwarded-for": "1.2.3.4"}, proxies))
Output
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.

Predict the outputPython

Using client_ip and proxies above, what does this print?

print(client_ip("10.0.0.5", {}, proxies))
Need a nudge? Hints walk you through it.

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.

Dockerfile
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-api

Add 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.

Quick check
Why copy pyproject.toml and uv.lock and install dependencies before COPY . .?
Need a nudge? A hint rules out a wrong answer.

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.
app/api/routes/health.py
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.

Quick check
Your liveness check queries the database. The database has a 30-second outage. What happens?
Need a nudge? A hint rules out a wrong answer.

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/main.py
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

OptionWhat you give itGood forWatch out for
Render, Railway, Fly.ioA Git repo or DockerfileSide projects to mid-size apps; managed Postgres nearbyFree tiers sleep; costs grow with always-on instances
AWS ECS on FargateA container imageProduction on AWS, fine-grained networking and scalingMore setup: VPC, load balancer, IAM, task definitions
AWS App RunnerA container imageThe simplest AWS container hostingFewer knobs than ECS; check it is still open to new accounts
Vercel (Python functions)Your FastAPI app as a functionAPIs that sit next to a Next.js frontendServerless limits: no long-running background work or persistent WebSockets, cold starts
A VM (EC2, a VPS)SSH and Docker ComposeFull control, predictable costYou 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 the pairs0/4 matched

Match each need to a sensible hosting choice.

Choose an item, then its match on the other side.

Deploying safely

A good deploy is boring and repeatable. CI (for example GitHub Actions) runs the same steps every time:

Put it in order5 steps

Order a typical deploy pipeline for a FastAPI service.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 /health every 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

ChallengeEasy

Readiness report

A /ready endpoint checks each dependency and tells the load balancer whether to send traffic. Write health_report(results, critical):

  • results maps a dependency name to whether its check passed, e.g. {"db": True, "cache": False}.
  • critical lists the dependencies the app cannot work without.

Return {"status": ..., "code": ..., "failing": [...]}:

Situationstatuscode
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"]}
Python
def health_report(results: dict, critical: list) -> dict: pass
ChallengeMedium

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.

  • origin is the request's Origin header, or None (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) or allowed_origins contains "*". 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 and allow_credentials is False. 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"}
Python
def cors_headers( origin: str | None, method: str, allowed_origins: list[str], allow_credentials: bool) -> dict: pass
Key terms
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.