Full answer
FastAPI is an ASGI application object. A separate ASGI server runs it.
Development:
pip install "fastapi[standard]"installs thefastapiCLI, Uvicorn and common extras.fastapi dev main.pystarts Uvicorn with auto-reload on127.0.0.1:8000.- Equivalent:
uvicorn main:app --reload(mainis the module,appthe variable).
Production:
fastapi run main.py(Uvicorn without reload, listening on0.0.0.0) oruvicorn main:app --host 0.0.0.0 --port 8000 --workers 4.- Each worker is a separate process with its own event loop and memory. Use several to use all CPU cores. A starting point is one worker per core, then load test.
- Alternatives: Gunicorn as process manager with
-k uvicorn_worker.UvicornWorker; or in Kubernetes, one worker per container and scale with replicas, letting the orchestrator restart crashed pods. - Put a reverse proxy or load balancer in front for TLS, request size limits and buffering. Run with
--proxy-headersand--forwarded-allow-ipsset to the proxy's address sorequest.client.hostandrequest.url.schemereflect the real client. - Never use
--reloadin production; it watches files and runs a single process.
Containers: base on an official Python slim image, install dependencies first (better layer caching), run as a non-root user, and use the exec form CMD ["fastapi", "run", "app/main.py", "--port", "80"] so signals reach the server for graceful shutdown.
Running programmatically (uvicorn.run(app) inside if __name__ == "__main__":) is handy for debugging in an IDE.
import socket
import threading
import time
import httpx
import uvicorn
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/healthz")
def health(request: Request):
return {"status": "ok", "scheme": request.url.scheme}
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
port = free_port()
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning",
proxy_headers=True, forwarded_allow_ips="127.0.0.1")
server = uvicorn.Server(config)
thread = threading.Thread(target=server.run)
thread.start()
while not server.started:
time.sleep(0.05)
print(httpx.get(f"http://127.0.0.1:{port}/healthz").json())
print(httpx.get(f"http://127.0.0.1:{port}/healthz", headers={"X-Forwarded-Proto": "https"}).json())
server.should_exit = True
thread.join()
print("server stopped cleanly")
# Command-line equivalents (not run here):
# fastapi dev main.py
# uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 --proxy-headers --forwarded-allow-ips 10.0.0.5
Standalone script. It starts a real Uvicorn server on a free local port in a thread, calls it with httpx, and shuts it down. The CLI commands are shown as comments and were not run. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'status': 'ok', 'scheme': 'http'} {'status': 'ok', 'scheme': 'https'} server stopped cleanly
Key points
- fastapi dev or uvicorn --reload for development
- fastapi run or uvicorn --workers for production
- Each worker is a separate process
- Reverse proxy for TLS; --proxy-headers for real client info
- Never use --reload in production
Common mistakes
- Running uvicorn --reload in production
- Running one worker on a multi-core machine and wondering why CPU sits idle
- Forgetting --proxy-headers so every request appears to come from the proxy IP over http
- Using the shell form of CMD in Docker so shutdown signals do not reach the server
Follow-ups
- How many workers would you run on a 4-core machine, and why?
- What is the difference between Gunicorn with Uvicorn workers and Kubernetes replicas?
- How does graceful shutdown work for in-flight requests?
Tips
- Separate dev and production commands clearly
- Explain what a worker is
- Mention proxy headers, a frequent production bug