Skip to content

FastAPI in Production: Uvicorn/Gunicorn Workers, Lifespan, Settings, Logging, Docker Image, Performance ​

"Processes shut down gracefully when they receive a SIGTERM signal from the process manager. For a web process, graceful shutdown is achieved by ceasing to listen on the service port (thereby refusing any new requests), allowing any current requests to finish, and then exiting." — The Twelve-Factor App, "IX. Disposability", 12factor.net/disposability

Summary: A FastAPI app is an ASGI callable; in production something has to run it, and that something decides most of how the service behaves under load and during a deploy. Uvicorn is the ASGI server: it accepts connections, parses HTTP with httptools on a uvloop event loop, and hands each request to the app. One Uvicorn process is one event loop, one GIL and one thread pool of 40 tokens for def endpoints, so a service uses several worker processes, managed either by Uvicorn's own supervisor (uvicorn --workers, fastapi run --workers) or by Gunicorn with uvicorn_worker.UvicornWorker (pre-fork master, heartbeat timeout, max_requests recycling). Each worker runs the app's lifespan, so pools and clients are created per process and their sizes multiply. Configuration comes from the environment through one pydantic-settings BaseSettings class, cached with @lru_cache and validated at startup; secrets are SecretStr and never part of the image. Logs are JSON lines on stdout with a request ID that a pure ASGI middleware puts into a contextvars.ContextVar. The Docker image is multi-stage with uv, non-root, exec-form CMD behind tini, and the shutdown path (SIGTERM → stop accepting → drain → lifespan shutdown) is measured, not assumed. Focus: uvicorn vs fastapi run/fastapi dev, --workers, the Uvicorn supervisor vs Gunicorn + UvicornWorker (pre-fork, master process, worker recycling with max_requests/max_requests_jitter/--limit-max-requests, boot failures), process managers, lifespan for pools and clients, connection pool size vs workers, pydantic-settings (BaseSettings, .env/env_file, env_prefix, secrets_dir, SecretStr, the lru_cache settings dependency, dev/staging/prod, fail-fast validation), logging (uvicorn.error, uvicorn.access, --log-config, dictConfig, JSON logs, structlog, request ID / correlation ID middleware, contextvars, log levels, access log on/off), the production Docker image (multi-stage uv, --no-dev, compile bytecode, non-root user, PYTHONUNBUFFERED, HEALTHCHECK, exec form, PID 1, tini), graceful shutdown (--timeout-graceful-shutdown, drain, readiness vs liveness, Kubernetes preStop, rolling deploys), proxies (--proxy-headers, --forwarded-allow-ips, X-Forwarded-For, --root-path), performance (sync vs async endpoints, the thread pool and AnyIO's capacity limiter, run_in_threadpool, uvloop/httptools, keep-alive, --limit-concurrency, --backlog, StreamingResponse, GZipMiddleware, ORJSONResponse, validation cost, CPU-bound work and ProcessPoolExecutor, load testing with p50/p99, py-spy and cProfile), security middlewares (CORS, TrustedHost, HTTPS redirect, security headers, docs off in prod), Prometheus metrics and an OpenTelemetry preview, and the Laravel (Octane, FrankenPHP, Swoole, PHP-FPM, config:cache) and Go (http.Server timeouts, GOMAXPROCS, Shutdown(ctx)) comparisons. Learning goal: Ship a FastAPI service that starts only with valid configuration, logs one correlated JSON line per event, reports liveness and readiness truthfully, survives a rolling deploy without failed requests, uses exactly the database connections you budgeted, and whose throughput you have measured (p50 and p99) and can explain from the process model.

This page owns running FastAPI in production: the server, the process model, configuration, logging, the image, shutdown and performance. It does not re-teach its neighbours. Routes, ASGI and the lifespan basics are in FastAPI Fundamentals; the BaseSettings field syntax, sources and env_nested_delimiter are in Typing & Pydantic v2 and APIRouter & Project Structure; the event loop, to_thread, the GIL and ProcessPoolExecutor are in Async Python; per-request vs per-process resources are in Dependency Injection with Depends; uv, the lock file and the first Dockerfile are in Python Project Tooling; StreamingResponse and response classes are in Exceptions & Responses; TestClient and fixtures are in Testing FastAPI; outbound httpx clients, retries and caching are in Background Tasks, Caching & External APIs. On the platform side, layers and multi-stage builds are in Images & Dockerfiles, rootless containers and capabilities in Container Security, docker run and Compose in Running Containers, CPU limits and HPA in Resources, Scheduling & Autoscaling, rolling and canary deploys in Deployment Strategies, and logs/metrics/traces as concepts in Observability. The Go twins are HTTP Server & Client and CLI Flags, Env & Logging.

Facts below were checked against the FastAPI deployment guide (concepts, server workers, Docker, HTTPS, manual, cloud, versions), the FastAPI advanced guide (settings, behind a proxy, middleware, custom responses, lifespan events), the FastAPI CLI page, the FastAPI release notes up to 0.165.0 (2026-11-18), the Uvicorn docs (settings, deployment, server behaviour, release notes), the Gunicorn docs (design, settings, signals, deploy, the native ASGI worker, news up to 27.0.1), the uvicorn-worker README, pydantic-settings, the Python logging.config, logging cookbook, contextvars, functools, profile and concurrent.futures docs, structlog, AnyIO's thread docs, Starlette (middleware, responses, lifespan, thread pool), the uvloop, httptools, orjson, py-spy and prometheus-fastapi-instrumentator READMEs, the Prometheus Python client's multiprocess page, the OpenTelemetry FastAPI instrumentation docs, uv's Docker and FastAPI guides, the Dockerfile reference and Docker's build best practices, the tini README, the Kubernetes pod lifecycle, container hooks and probes pages, the Twelve-Factor App, OWASP Secure Headers and MDN, Laravel 13 (Octane, deployment, configuration, Horizon), FrankenPHP, the PHP-FPM configuration manual, Go's net/http/server.go, the Go 1.25 release notes and the Go blog on container-aware GOMAXPROCS. The page is written for Python 3.12+ and current releases (FastAPI 0.165.0, Uvicorn 0.55.0, Gunicorn 27.0.1, pydantic-settings 2.16.3 on PyPI on 2026-11-29). The snippets ran on the only interpreter on the build machine, CPython 3.9.6 on a 12-core arm64 Mac (8 performance + 4 efficiency cores), with the newest releases that still install there: FastAPI 0.128.8, Starlette 0.49.3, Pydantic 2.13.5, pydantic-settings 2.11.0, Uvicorn 0.39.0 with uvloop 0.23.0 and httptools 0.9.0, Gunicorn 23.0.0, uvicorn-worker 0.4.0, SQLAlchemy 2.0.58, httpx 0.28.1, orjson 3.11.5, prometheus-fastapi-instrumentator 7.1.0 and pytest 8.4.2, locked with uv 0.13.10. Every log line, status code, header and number marked "real" below is what those runs printed (transcripts in pipeline/sources/fastapi-production-uvicorn/runs/). Docker was not available: the image is written and its rules are checked by a test that reads the Dockerfile; the build is "expected, not run".

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
Why "uvicorn main:app" is not a deploymentWhy it exists
WSGI, Gunicorn 2010, ASGI, Uvicorn, 12-factorWhere it comes from
A before/after production appPython
uvicorn, fastapi run, fastapi devRunning the ASGI server
--workers, supervisor, spawnWorker processes
Gunicorn, UvicornWorker, pre-fork, masterGunicorn as the process manager
max_requests, --limit-max-requests, jitterWorker recycling
Startup and shutdown, pools in the lifespanLifespan in production
Pool size vs workers vs database max_connectionsConnection pool sizing
BaseSettings, .env, SecretStr, lru_cacheSettings with pydantic-settings
dev / staging / prod, fail fastEnvironments and fail-fast configuration
uvicorn.error, uvicorn.access, --log-configLogging: Uvicorn's loggers and dictConfig
JSON logs, structlogStructured JSON logs
X-Request-ID, correlation, contextvarsRequest ID middleware
/healthz, /readyz, probesHealth endpoints: liveness vs readiness
SIGTERM, drain, --timeout-graceful-shutdownGraceful shutdown
preStop, rolling deploysRolling deploys and Kubernetes
Multi-stage uv image, non-root, tiniThe production Docker image
--proxy-headers, X-Forwarded-For, --root-pathBehind a reverse proxy
CORS, TrustedHost, HTTPS redirect, headers, /docsSecurity middlewares
def vs async def, 40 threadsSync vs async endpoints and the thread pool
uvloop, httptools, keep-alive, backlog, limitsServer knobs
GZip, ORJSON, validation cost, streamingResponse cost
CPU-bound workCPU-bound work and processes
Load testing, p50/p99, py-spy, cProfileMeasuring
Prometheus, OpenTelemetryMetrics and tracing
os.environ everywhere, secrets in imagesConfiguration anti-patterns
What runs underneathMechanics
Bugs and fixesSolving the classic problems
Which server, how many workersChoosing
Monolith to distributedIn architecture
Run it yourselfLab
Octane, FrankenPHP, PHP-FPM, config:cacheFor PHP/Laravel developers
http.Server, GOMAXPROCS, Shutdown(ctx)The Go angle

Everything in one minute ​

The pieces. Each row is unpacked in the concept catalogue.

PieceWhat it isPlain wordsIn the snippet
ASGI serverProgram that speaks HTTP and calls the ASGI app"The waiter between the kitchen and the street"Uvicorn 0.39.0
Worker processOne OS process with its own event loop, GIL and copy of the app"One kitchen"--workers 4, WEB_CONCURRENCY
Process managerStarts, watches, restarts and stops workers"The shift manager"Uvicorn supervisor or Gunicorn master
LifespanCode around yield that runs once per worker at startup and shutdown"Open and close the kitchen"app/main.py lifespan()
SettingsOne typed object built from env, .env, secrets, defaults"The order sheet, checked once"app/settings.py
Request IDPer-request ID in a header, a ContextVar and every log line"The ticket number"app/middleware.py
Liveness / readiness"Restart me?" vs "send me traffic?""Alive vs open for business"/healthz, /readyz
Graceful shutdownSIGTERM → stop accepting → drain → lifespan shutdown → exit"Last orders, then close"tools/shutdown_probe.py
Thread poolAnyIO's limiter, 40 tokens, runs def endpoints"40 extra hands"APP_THREADPOOL_TOKENS

Which command, which process tree (real, ps output in runs/).

CommandProcessesManager restarts dead workers?Startup failure in a workerTypical use
uvicorn app.main:app1No managerProcess exits 1One process per container (Kubernetes)
uvicorn app.main:app --workers 4supervisor + 4 spawnedYesSupervisor keeps respawning, stays up (real)VM, bare container with several CPUs
fastapi run app/main.py --workers 2same as aboveYesSame as aboveSame; binds 0.0.0.0:8000 by default
fastapi dev app/main.pyreloader + 1Reloads on file changeWaits for a fixDevelopment only
gunicorn -k uvicorn_worker.UvicornWorker -w 4master + 4 forkedYes, plus heartbeat timeoutMaster exits with code 3, "Worker failed to boot" (real)Hooks, recycling, USR2 binary upgrade

The numbers measured on this page (one worker unless stated; Python load tool, 12-core arm64).

ExperimentResultWhere
CPU-bound endpoint (21 ms of pure Python), 16 users, 1 vs 4 workers47.9 → 184.1 req/s; p99 493.5 → 248.9 msWorker processes
I/O-bound async def (20 ms sleep), 32 users, 1 vs 4 workers1,385.5 vs 1,353.3 req/s (no gain)Worker processes
async def + await asyncio.sleep(0.1), 100 users842.0 req/s, p50 112.9 ms, p99 165.3 msSync vs async
def + time.sleep(0.1), 100 users, 40 tokens355.3 req/s, p50 246.4 ms, p99 481.7 msSync vs async
Same with 100 tokens811.0 req/s, p50 110.2 ms, p99 179.8 msSync vs async
time.sleep(0.1) inside async def, 10 users9.6 req/s, p50 942.2 msSync vs async
SIGTERM with a 3 s request in flightnew connection refused at +0.3 s, request 200, exit 2.0 s after SIGTERMGraceful shutdown
Same with --timeout-graceful-shutdown 2 and a 5 s request"Cancel 1 running task(s)", client gets 500Graceful shutdown
--limit-concurrency 10, 40 keep-alive users387 of 400 answers were 503Server knobs
2,000 objects: stdlib json vs orjson vs Pydantic validate + dump8.18 vs 0.09 vs 0.93 msResponse cost

Why it exists ​

uvicorn main:app --reload on a laptop is one process that restarts when a file changes, prints coloured text, trusts every Host header, serves /docs to the world, reads whatever .env happens to be in the current directory and dies with whatever requests it was serving when you press Ctrl+C. Production needs the opposite on every axis: several processes because one Python process uses one core for Python code, a manager that restarts them, configuration that is validated before the first request, secrets that never land in the image, logs a machine can parse and correlate, health endpoints the orchestrator can trust, a shutdown that finishes in-flight requests, and numbers that say how much traffic one container can take. None of this is FastAPI code in the narrow sense; it is the space between the app and the platform, and most outages of Python web services happen there: a pool that opened 400 connections because someone set 20 workers, a deploy that cut every in-flight request because the CMD was in shell form, a 30-second p99 because a requests.get sat inside an async def.

Laptop defaultProduction setup on this page
One process, --reload--workers N or Gunicorn, N chosen from CPU limits; no reload
print(), coloured textJSON lines on stdout, one logger hierarchy, request ID on every line
os.environ.get(...) scattered, stringsOne Settings class, typed, validated at startup, SecretStr
.env in the image.env in .dockerignore; env vars and mounted secrets at runtime
/health that queries the database/healthz (process only) and /readyz (dependencies)
Ctrl+C kills requestsSIGTERM → drain → lifespan shutdown, inside the grace period
Shell-form CMD, PID 1 is /bin/shExec form behind tini; signals reach Uvicorn
Root user, dev tools in the imageMulti-stage uv build, --no-dev, non-root user
/docs public, any HostDocs off in prod, TrustedHostMiddleware, security headers
"It feels fast"Load tool with p50/p99, profiler, measured worker and thread counts

An everyday picture. A restaurant. The ASGI server is the front door and the waiters; each worker process is a separate kitchen with its own cooks (the event loop), a fixed number of extra hands for slow manual jobs (the 40-token thread pool) and its own pantry (the connection pool). The process manager is the shift manager who opens kitchens, notices when one burns down and opens a replacement, and every so often closes a kitchen after its hundredth order to clean it (worker recycling). The order sheet that says what is on the menu tonight and which supplier to call is read once at opening and checked for mistakes before the doors open (settings). Every order gets a ticket number that is written on every note the kitchen makes about it (the request ID). The health inspector asks two different questions: "is anyone alive in there?" (liveness) and "can you take a table right now?" (readiness). At closing time the doors are locked first, the tables already seated get their food, and only then is the gas turned off (graceful shutdown). Adding a fourth kitchen helps when the cooks are the bottleneck (CPU-bound work), and does nothing when everyone is waiting for the same delivery truck (I/O-bound work).

Three common misunderstandings, up front ​

  1. "More workers make every endpoint faster." Only CPU-bound work scales with processes. In the real run, 4 workers took a CPU-bound endpoint from 47.9 to 184.1 req/s, while an async def endpoint that waits 20 ms stayed at about 1,350 req/s with 1 or 4 workers. Each worker also multiplies memory and database connections.
  2. "The lifespan runs once for the service." It runs once per worker process, and again every time a worker is recycled. Four workers with pool_size=5, max_overflow=5 can hold 40 database connections; ten replicas of that container hold 400.
  3. "Kubernetes sends SIGTERM, the app stops, done." SIGTERM only reaches Uvicorn if PID 1 forwards it (exec form, tini); Uvicorn then stops accepting, waits for in-flight requests up to --timeout-graceful-shutdown, runs the lifespan shutdown, and all of that must fit inside terminationGracePeriodSeconds (30 s by default), which already started when the preStop hook began.

Where it comes from ​

Python web servers grew up around WSGI (PEP 3333, 2010), a synchronous call per request; Gunicorn's design page describes the model: "Gunicorn uses a pre-fork worker model: an arbiter process manages worker processes, while the workers handle requests and responses. The arbiter never touches individual client sockets." ASGI replaced the single call with an async callable and message passing, and its lifespan sub-protocol gave apps a startup and shutdown hook per server process. Uvicorn implemented ASGI on uvloop and httptools; for years production setups ran Gunicorn as the process manager with Uvicorn's worker class inside it, and FastAPI shipped a tiangolo/uvicorn-gunicorn-fastapi image for exactly that. The FastAPI Docker page now says that image "is now deprecated" and explains why: "The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn". Uvicorn's deployment page describes its own manager: "Unlike gunicorn, uvicorn does not use pre-fork, but uses spawn", and "The default process manager monitors the status of child processes and automatically restarts child processes that die unexpectedly." At the same time it warns that "The uvicorn.workers module is deprecated and will be removed in a future release. You should use the uvicorn-worker package instead." Gunicorn moved the other way: 24.0.0 (2026-01-23) added an "ASGI Worker (Beta): Native asyncio-based ASGI support for running async Python frameworks like FastAPI, Starlette, and Quart without external dependencies", and its docs now show gunicorn main:app --worker-class asgi.

On the FastAPI side, fastapi run and fastapi dev (the fastapi-cli package) wrap Uvicorn with production and development defaults. FastAPI 0.130.0 (2026-02-22) made responses with a Pydantic return type or response model "Serialize JSON response with Pydantic (in Rust)", and 0.131.0 the same day deprecated ORJSONResponse and UJSONResponse. The Twelve-Factor App (2011) gave the vocabulary for the configuration and process rules this page follows: "strict separation of config from code", config "in environment variables", logs as "event stream, unbuffered, to stdout", and processes that are "disposable". On the Go side, Go 1.25 (August 2025) made GOMAXPROCS container-aware; a Python process has no such knob, so the worker count is yours to derive from the CPU limit.

1  2010     Gunicorn: pre-fork WSGI server, arbiter (master) + workers
2  2011     The Twelve-Factor App: config in env vars, logs to stdout, disposable processes
3  2018-06  Uvicorn on uvloop + httptools; ASGI lifespan; Gunicorn + UvicornWorker becomes the pattern
4  2018-12  FastAPI released; tiangolo/uvicorn-gunicorn-fastapi image (now deprecated)
5  2024-08  Gunicorn 23.0.0 (the pin here; last release for Python 3.9)
6  2025-09  uvicorn-worker 0.4.0 (the pin here): the maintained home of UvicornWorker
7  2025-12  Uvicorn 0.39.0 (the pin here); FastAPI 0.128.8 pin (Feb 2026, last for 3.9)
8  2026-01  Gunicorn 24.0.0: native ASGI worker (beta), --worker-class asgi
9  2026-02  FastAPI 0.130.0 Pydantic (Rust) JSON serialisation; 0.131.0 deprecates ORJSONResponse
10 2026-11  FastAPI 0.165.0, Uvicorn 0.55.0 (drops 3.10), Gunicorn 27.0.1: current releases

Rows 1 to 4 are dated from general knowledge of the projects, not from a release page fetched for this chapter; the rows from 2024 on come from the saved release notes, news pages and PyPI.

Python ​

Before ​

The "works on my laptop" app. It runs and answers; it is just not operable. Configuration is read from os.environ at import time as strings (so DEBUG=false is truthy), a missing secret silently falls back to "changeme", the engine is a module global that nobody disposes, the health check does blocking database I/O inside async def, /report calls time.sleep on the event loop, logs are print(), docs are public and uvicorn.run(..., reload=True) is the "production" entry point.

py
"""The "works on my laptop" version: every production problem this chapter fixes, in one file.

Not broken code; it runs and answers. It is just not operable.
"""

import os
import time

from fastapi import FastAPI
from sqlalchemy import create_engine, text

# Configuration read from os.environ at import time, all over the code, as strings
DEBUG = os.environ.get("DEBUG", "true")  # "false" is a non-empty string: still truthy below
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./orders.db")
SECRET_KEY = os.environ.get("SECRET_KEY", "changeme")  # silently used in prod if unset

# A module-level engine: created at import, never disposed, shared by whatever imports this
engine = create_engine(DATABASE_URL)

# Docs always on; no host check; no request ID; print() instead of logging
app = FastAPI(debug=bool(DEBUG))


@app.get("/health")
async def health():
    # Liveness and readiness mixed: a slow database makes the orchestrator kill a healthy process
    with engine.connect() as conn:  # blocking I/O inside async def
        conn.execute(text("SELECT 1"))
    return {"ok": True}


@app.get("/report")
async def report():
    print("building report")  # no level, no request ID, no JSON, buffered when stdout is a pipe
    time.sleep(0.2)  # blocks the event loop: every other request of this worker waits
    return {"secret_prefix": SECRET_KEY[:3]}  # a secret leaking into a response


if __name__ == "__main__":
    import uvicorn

    # reload=True in production, one process, no graceful-shutdown budget, no proxy settings
    uvicorn.run("app.before:app", host="0.0.0.0", port=8000, reload=True)

The tests assert each problem (bool("false") is True, the fallback secret leaks into a response, /docs is public, five concurrent /report calls take at least 1.0 s instead of 0.2 s because the loop is blocked):

py
"""What the Before app gets wrong, asserted."""

import importlib
import time

from fastapi.testclient import TestClient


def load_before(monkeypatch, **env):
    for key in ("DEBUG", "DATABASE_URL", "SECRET_KEY"):
        monkeypatch.delenv(key, raising=False)
    for key, value in env.items():
        monkeypatch.setenv(key, value)
    import app.before as before

    return importlib.reload(before)  # configuration is only read at import time


def test_debug_false_is_still_true(monkeypatch, tmp_path):
    before = load_before(monkeypatch, DEBUG="false", DATABASE_URL=f"sqlite:///{tmp_path / 'b.db'}")
    assert before.app.debug is True  # bool("false") == True


def test_missing_secret_falls_back_silently(monkeypatch, tmp_path):
    before = load_before(monkeypatch, DATABASE_URL=f"sqlite:///{tmp_path / 'b.db'}")
    with TestClient(before.app) as c:
        assert c.get("/report").json() == {"secret_prefix": "cha"}


def test_docs_are_public_and_no_request_id(monkeypatch, tmp_path):
    before = load_before(monkeypatch, DATABASE_URL=f"sqlite:///{tmp_path / 'b.db'}")
    with TestClient(before.app) as c:
        assert c.get("/docs").status_code == 200
        assert "x-request-id" not in c.get("/health").headers


def test_blocking_report_serialises_concurrent_requests(monkeypatch, tmp_path):
    import anyio
    import httpx

    before = load_before(monkeypatch, DATABASE_URL=f"sqlite:///{tmp_path / 'b.db'}")

    async def five_at_once() -> float:
        transport = httpx.ASGITransport(app=before.app)
        async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
            start = time.perf_counter()
            async with anyio.create_task_group() as tg:
                for _ in range(5):
                    tg.start_soon(c.get, "/report")
            return time.perf_counter() - start

    elapsed = anyio.run(five_at_once)
    assert elapsed >= 1.0  # 5 x 0.2 s one after another, not 0.2 s in parallel

After ​

One Settings class is the only place that reads the environment; get_settings() caches it per process.

py
"""Typed configuration: one Settings class, read once per process, validated at startup.

Priority (highest first): keyword arguments > environment variables > .env file
> secrets directory > field defaults. Nothing else in the app reads os.environ.
"""

from functools import lru_cache
from typing import List, Literal, Optional

from pydantic import Field, SecretStr, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict

DEV_SECRET = "dev-only-not-a-secret"


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_prefix="APP_",
        env_file=".env",
        env_file_encoding="utf-8",
        # Kubernetes/Docker secrets mounted as files: /run/secrets/app_secret_key
        secrets_dir=None,
        extra="ignore",
    )

    env: Literal["dev", "staging", "prod"] = "dev"
    service_name: str = "orders-api"
    version: str = "0.1.0"

    database_url: str = "sqlite:///./orders.db"
    db_pool_size: int = Field(default=5, ge=1)
    db_max_overflow: int = Field(default=5, ge=0)
    db_pool_timeout: float = 5.0

    secret_key: SecretStr = SecretStr(DEV_SECRET)
    upstream_url: str = "http://127.0.0.1:9"

    log_level: str = "INFO"
    log_json: bool = True

    # None means "decide from env": docs on in dev/staging, off in prod
    docs_enabled: Optional[bool] = None
    allowed_hosts: List[str] = ["localhost", "127.0.0.1", "testserver"]
    cors_origins: List[str] = []
    https_redirect: bool = False

    # Tokens of AnyIO's default thread limiter: how many sync endpoints run at once
    threadpool_tokens: int = Field(default=40, ge=1)
    process_pool_workers: int = Field(default=2, ge=1)

    @model_validator(mode="after")
    def prod_needs_real_secrets(self) -> "Settings":
        if self.env == "prod":
            if self.secret_key.get_secret_value() == DEV_SECRET:
                raise ValueError("APP_SECRET_KEY must be set in prod")
            if "*" in self.allowed_hosts:
                raise ValueError("APP_ALLOWED_HOSTS must not be '*' in prod")
        return self

    @property
    def show_docs(self) -> bool:
        if self.docs_enabled is not None:
            return self.docs_enabled
        return self.env != "prod"


@lru_cache
def get_settings() -> Settings:
    """The settings dependency: built on first call, then the same object per process."""
    return Settings()

Logging is one dictConfig dictionary used by every entry point; a filter copies the request ID from a ContextVar onto every record and a small formatter writes one JSON object per line.

py
"""Logging for production: one JSON object per line on stdout, a request ID on every record.

build_log_config() returns a logging.config.dictConfig dictionary. The same dictionary is
saved as conf/log-config.json for `uvicorn --log-config`, and passed to Gunicorn as
logconfig_dict, so all three entry points log the same way.
"""

import json
import logging
import time
from contextvars import ContextVar
from typing import Any, Dict

# One value per request; asyncio tasks and run_in_threadpool copy the context, so sync
# endpoints running in worker threads see the same ID.
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")

_RESERVED = set(vars(logging.makeLogRecord({})).keys()) | {"message", "asctime", "request_id"}


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = request_id_var.get()
        return True


class JsonFormatter(logging.Formatter):
    """Minimal structured formatter (stdlib only). structlog or python-json-logger do the same."""

    def format(self, record: logging.LogRecord) -> str:
        payload: Dict[str, Any] = {
            "ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created))
            + f".{int(record.msecs):03d}Z",
            "level": record.levelname,
            "logger": record.name,
            "msg": record.getMessage(),
            "request_id": getattr(record, "request_id", "-"),
            "pid": record.process,
        }
        # Fields passed with logger.info("...", extra={...})
        for key, value in vars(record).items():
            if key not in _RESERVED and not key.startswith("_"):
                payload[key] = value
        if record.exc_info:
            payload["exc"] = self.formatException(record.exc_info)
        return json.dumps(payload, default=str)


def build_log_config(level: str = "INFO", json_logs: bool = True) -> Dict[str, Any]:
    formatter = "json" if json_logs else "plain"
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {"request_id": {"()": "app.logging_setup.RequestIdFilter"}},
        "formatters": {
            "json": {"()": "app.logging_setup.JsonFormatter"},
            "plain": {"format": "%(asctime)s %(levelname)s [%(request_id)s] %(name)s: %(message)s"},
        },
        "handlers": {
            "stdout": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": formatter,
                "filters": ["request_id"],
            }
        },
        "loggers": {
            # uvicorn.error is the server's own log (startup, shutdown, tracebacks), not only errors
            "uvicorn.error": {"level": level, "handlers": ["stdout"], "propagate": False},
            # one line per request from Uvicorn; this app writes its own app.access line instead
            "uvicorn.access": {"level": "WARNING", "handlers": ["stdout"], "propagate": False},
            "gunicorn.error": {"level": level, "handlers": ["stdout"], "propagate": False},
            "gunicorn.access": {"level": "WARNING", "handlers": ["stdout"], "propagate": False},
            "app": {"level": level, "handlers": ["stdout"], "propagate": False},
        },
        "root": {"level": "WARNING", "handlers": ["stdout"]},
    }


if __name__ == "__main__":
    # Regenerates conf/log-config.json: python -m app.logging_setup > conf/log-config.json
    print(json.dumps(build_log_config(), indent=2))
json
{
  "version": 1,
  "disable_existing_loggers": false,
  "filters": {
    "request_id": {
      "()": "app.logging_setup.RequestIdFilter"
    }
  },
  "formatters": {
    "json": {
      "()": "app.logging_setup.JsonFormatter"
    },
    "plain": {
      "format": "%(asctime)s %(levelname)s [%(request_id)s] %(name)s: %(message)s"
    }
  },
  "handlers": {
    "stdout": {
      "class": "logging.StreamHandler",
      "stream": "ext://sys.stdout",
      "formatter": "json",
      "filters": [
        "request_id"
      ]
    }
  },
  "loggers": {
    "uvicorn.error": {
      "level": "INFO",
      "handlers": [
        "stdout"
      ],
      "propagate": false
    },
    "uvicorn.access": {
      "level": "WARNING",
      "handlers": [
        "stdout"
      ],
      "propagate": false
    },
    "gunicorn.error": {
      "level": "INFO",
      "handlers": [
        "stdout"
      ],
      "propagate": false
    },
    "gunicorn.access": {
      "level": "WARNING",
      "handlers": [
        "stdout"
      ],
      "propagate": false
    },
    "app": {
      "level": "INFO",
      "handlers": [
        "stdout"
      ],
      "propagate": false
    }
  },
  "root": {
    "level": "WARNING",
    "handlers": [
      "stdout"
    ]
  }
}

Two pure ASGI middlewares: the request ID (header, ContextVar, JSON access line, a 500 that still carries the ID) and the security headers.

py
"""Pure ASGI middlewares: request ID + access log, and security headers.

Pure ASGI (not BaseHTTPMiddleware) so the contextvar set here is visible to the endpoint,
to sync endpoints in the thread pool, and to StreamingResponse bodies, and so nothing
buffers the response.
"""

import json
import logging
import re
import time
import uuid
from typing import Iterable, Tuple

from starlette.datastructures import Headers, MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send

from app.logging_setup import request_id_var

access_log = logging.getLogger("app.access")
error_log = logging.getLogger("app.error")

# Accept a caller's ID only if it is short and boring; anything else could be log injection
_VALID_ID = re.compile(r"^[A-Za-z0-9._-]{8,128}$")


class RequestIDMiddleware:
    def __init__(self, app: ASGIApp, header_name: str = "x-request-id") -> None:
        self.app = app
        self.header_name = header_name

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        incoming = Headers(scope=scope).get(self.header_name, "")
        request_id = incoming if _VALID_ID.match(incoming) else uuid.uuid4().hex
        token = request_id_var.set(request_id)
        started = time.perf_counter()
        status = 500
        response_started = False

        async def send_with_id(message: Message) -> None:
            nonlocal status, response_started
            if message["type"] == "http.response.start":
                response_started = True
                status = message["status"]
                MutableHeaders(scope=message).append("X-Request-ID", request_id)
            await send(message)

        try:
            await self.app(scope, receive, send_with_id)
        except Exception:
            # Unhandled error: answer here so the 500 carries the ID; Starlette's
            # ServerErrorMiddleware sits outside us and would answer without it.
            error_log.exception("unhandled error")
            if not response_started:
                body = json.dumps({"detail": "Internal Server Error", "request_id": request_id})
                await send_with_id(
                    {
                        "type": "http.response.start",
                        "status": 500,
                        "headers": [(b"content-type", b"application/json")],
                    }
                )
                await send({"type": "http.response.body", "body": body.encode()})
        finally:
            access_log.info(
                "request",
                extra={
                    "method": scope["method"],
                    "path": scope["path"],
                    "status": status,
                    "duration_ms": round((time.perf_counter() - started) * 1000, 2),
                    "client": scope["client"][0] if scope.get("client") else None,
                },
            )
            request_id_var.reset(token)


DEFAULT_SECURITY_HEADERS: Tuple[Tuple[str, str], ...] = (
    ("X-Content-Type-Options", "nosniff"),
    ("X-Frame-Options", "DENY"),
    ("Referrer-Policy", "no-referrer"),
    ("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'"),
    ("Cross-Origin-Opener-Policy", "same-origin"),
)


# Swagger UI and ReDoc load CDN assets and an inline script: the strict API CSP would blank them
DOCS_PATHS: Tuple[str, ...] = ("/docs", "/redoc")


class SecurityHeadersMiddleware:
    def __init__(
        self,
        app: ASGIApp,
        hsts: bool = False,
        extra: Iterable[Tuple[str, str]] = (),
        csp_exempt_paths: Tuple[str, ...] = DOCS_PATHS,
    ) -> None:
        self.app = app
        self.headers = list(DEFAULT_SECURITY_HEADERS) + list(extra)
        self.csp_exempt_paths = csp_exempt_paths
        if hsts:
            # Only when every client reaches us over HTTPS (the proxy terminates TLS)
            self.headers.append(("Strict-Transport-Security", "max-age=31536000; includeSubDomains"))

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        skip_csp = scope["path"].startswith(self.csp_exempt_paths)

        async def send_with_headers(message: Message) -> None:
            if message["type"] == "http.response.start":
                headers = MutableHeaders(scope=message)
                for name, value in self.headers:
                    if skip_csp and name == "Content-Security-Policy":
                        continue
                    if name not in headers:
                        headers[name] = value
            await send(message)

        await self.app(scope, receive, send_with_headers)

The connection pool belongs to the worker process; readiness is one cheap round trip.

py
"""The connection pool lives for the whole worker process: created in the lifespan, disposed at shutdown."""

from typing import Any, Dict

from sqlalchemy import Engine, create_engine, text

from app.settings import Settings


def make_engine(settings: Settings) -> Engine:
    kwargs: Dict[str, Any] = {"pool_pre_ping": True}
    if settings.database_url not in ("sqlite://", "sqlite:///:memory:"):
        # QueuePool: per worker process. 4 workers x (5 + 5) = up to 40 server connections.
        kwargs.update(
            pool_size=settings.db_pool_size,
            max_overflow=settings.db_max_overflow,
            pool_timeout=settings.db_pool_timeout,
        )
    return create_engine(settings.database_url, **kwargs)


def check_database(engine: Engine) -> Dict[str, Any]:
    """Readiness check: one cheap round trip plus the pool's own counters."""
    with engine.connect() as conn:
        conn.execute(text("SELECT 1"))
    return {"db": "ok", "pool": engine.pool.status()}

The factory wires it together: lifespan (thread-pool size, engine, httpx.AsyncClient, ProcessPoolExecutor), liveness and readiness, docs only outside prod, Prometheus metrics, and the middleware order.

py
"""Application factory: settings in, a fully wired production app out."""

import logging
import os
from concurrent.futures import ProcessPoolExecutor
from contextlib import asynccontextmanager
from typing import Annotated, AsyncIterator, Optional

import anyio.to_thread
import httpx
from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse, ORJSONResponse
from prometheus_client import CollectorRegistry
from prometheus_fastapi_instrumentator import Instrumentator

from app import work
from app.db import check_database, make_engine
from app.middleware import RequestIDMiddleware, SecurityHeadersMiddleware
from app.settings import Settings, get_settings

log = logging.getLogger("app.lifespan")


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    settings: Settings = app.state.settings
    # Startup: runs once per worker process, before the worker accepts requests
    limiter = anyio.to_thread.current_default_thread_limiter()
    limiter.total_tokens = settings.threadpool_tokens
    app.state.engine = make_engine(settings)
    app.state.http = httpx.AsyncClient(
        base_url=settings.upstream_url,
        timeout=httpx.Timeout(5.0, connect=2.0),
        limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
    )
    app.state.process_pool = ProcessPoolExecutor(max_workers=settings.process_pool_workers)
    log.info(
        "startup complete",
        extra={"env": settings.env, "threadpool_tokens": limiter.total_tokens, "worker_pid": os.getpid()},
    )
    try:
        yield
    finally:
        # Shutdown: runs after Uvicorn stopped accepting and drained in-flight requests
        log.info("shutdown: closing http client, process pool and db pool")
        await app.state.http.aclose()
        app.state.process_pool.shutdown(wait=True, cancel_futures=True)
        app.state.engine.dispose()
        log.info("shutdown complete")


SettingsDep = Annotated[Settings, Depends(get_settings)]


def create_app(settings: Optional[Settings] = None, metrics_registry: Optional[CollectorRegistry] = None) -> FastAPI:
    settings = settings or get_settings()
    show_docs = settings.show_docs
    app = FastAPI(
        title=settings.service_name,
        version=settings.version,
        lifespan=lifespan,
        # Interactive docs and the schema are off in prod unless explicitly enabled
        docs_url="/docs" if show_docs else None,
        redoc_url="/redoc" if show_docs else None,
        openapi_url="/openapi.json" if show_docs else None,
        default_response_class=ORJSONResponse,
    )
    app.state.settings = settings

    @app.get("/healthz", include_in_schema=False)
    async def liveness() -> dict:
        # Liveness: "the process can answer". No database, no upstreams.
        return {"status": "ok"}

    @app.get("/readyz", include_in_schema=False)
    def readiness(request: Request):
        # Readiness: "send me traffic". Checks what a request needs; sync, so it uses the pool thread.
        try:
            checks = check_database(request.app.state.engine)
        except Exception as exc:  # report, do not crash
            return JSONResponse({"status": "unavailable", "db": type(exc).__name__}, status_code=503)
        return {"status": "ready", **checks}

    @app.get("/info")
    async def info(request: Request, current: SettingsDep) -> dict:
        return {
            "service": current.service_name,
            "env": current.env,
            "pid": os.getpid(),
            "client": request.client.host if request.client else None,
            "scheme": request.url.scheme,
            "root_path": request.scope.get("root_path", ""),
            "threadpool_tokens": anyio.to_thread.current_default_thread_limiter().total_tokens,
            "secret_key": str(current.secret_key),  # prints '**********', never the value
        }

    app.include_router(work.router)

    # Metrics middleware first, so it sits innermost (closest to the routes).
    # The default registry is process-wide: a second app in the same process records nothing.
    Instrumentator(
        excluded_handlers=["/metrics", "/healthz", "/readyz"], registry=metrics_registry
    ).instrument(app).expose(
        app, endpoint="/metrics", include_in_schema=False
    )

    # add_middleware wraps the current stack: the LAST one added is the OUTERMOST.
    app.add_middleware(GZipMiddleware, minimum_size=1000)
    if settings.cors_origins:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=settings.cors_origins,
            allow_methods=["GET", "POST"],
            allow_headers=["Authorization", "Content-Type", "X-Request-ID"],
            expose_headers=["X-Request-ID"],
        )
    if settings.https_redirect:
        app.add_middleware(HTTPSRedirectMiddleware)
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)
    app.add_middleware(RequestIDMiddleware)
    # Outermost: even the 400 from TrustedHost and the 500 from RequestIDMiddleware get the headers
    app.add_middleware(SecurityHeadersMiddleware, hsts=settings.env == "prod")
    return app


# `uvicorn app.main:app` / `fastapi run app/main.py`; or `uvicorn app.main:create_app --factory`
app = create_app()

The endpoints that make the concurrency model visible under load:

py
"""Endpoints that make the server's concurrency model visible under load."""

import asyncio
import logging
import os
import time
from typing import AsyncIterator

from fastapi import APIRouter, Query, Request
from fastapi.responses import StreamingResponse

router = APIRouter(prefix="/work", tags=["work"])
log = logging.getLogger("app.work")


def burn(n: int) -> int:
    """Pure-Python CPU work; holds the GIL the whole time."""
    total = 0
    for i in range(n):
        total += i * i
    return total


@router.get("/async")
async def async_io(ms: int = Query(50, ge=0, le=10_000)) -> dict:
    # Non-blocking wait: the event loop serves other requests meanwhile
    await asyncio.sleep(ms / 1000)
    return {"kind": "async", "pid": os.getpid()}


@router.get("/sync")
def sync_io(ms: int = Query(50, ge=0, le=10_000)) -> dict:
    # Plain def: FastAPI runs it in AnyIO's thread pool (40 tokens by default)
    time.sleep(ms / 1000)
    return {"kind": "sync", "pid": os.getpid()}


@router.get("/blocking")
async def blocking_in_async(ms: int = Query(50, ge=0, le=10_000)) -> dict:
    # The bug: a blocking call inside async def freezes the whole event loop of this worker
    time.sleep(ms / 1000)
    return {"kind": "blocking", "pid": os.getpid()}


@router.get("/cpu")
def cpu(n: int = Query(200_000, ge=1, le=50_000_000)) -> dict:
    # Threads do not help here: one GIL per process. More processes do.
    return {"kind": "cpu", "result": burn(n) % 1000, "pid": os.getpid()}


@router.get("/cpu-process")
async def cpu_in_process(request: Request, n: int = Query(200_000, ge=1, le=50_000_000)) -> dict:
    # Offload to the worker's ProcessPoolExecutor (created in the lifespan)
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(request.app.state.process_pool, burn, n)
    return {"kind": "cpu-process", "result": result % 1000, "pid": os.getpid()}


@router.get("/slow")
async def slow(seconds: float = Query(3.0, ge=0, le=120)) -> dict:
    # Used by the graceful-shutdown experiment: an in-flight request during SIGTERM
    log.info("slow request started", extra={"seconds": seconds})
    await asyncio.sleep(seconds)
    log.info("slow request finished")
    return {"kind": "slow", "seconds": seconds, "pid": os.getpid()}


@router.get("/stream")
async def stream(chunks: int = Query(5, ge=1, le=1000), delay_ms: int = Query(0, ge=0, le=1000)):
    async def body() -> AsyncIterator[bytes]:
        for i in range(chunks):
            if delay_ms:
                await asyncio.sleep(delay_ms / 1000)
            yield f'{{"chunk": {i}}}\n'.encode()

    return StreamingResponse(body(), media_type="application/x-ndjson")


@router.get("/big")
async def big(items: int = Query(2000, ge=1, le=100_000)) -> dict:
    # A large JSON body: shows serialisation cost and GZipMiddleware
    return {"items": [{"id": i, "sku": f"SKU-{i:06d}", "price": i * 1.5} for i in range(items)]}


@router.get("/boom")
async def boom() -> dict:
    raise RuntimeError("deliberate failure")

The deployment files: Gunicorn's configuration (read by a test, run for real below), the Dockerfile (read by a test, build expected, not run), .dockerignore and the example environment.

py
"""Gunicorn as the process manager, Uvicorn inside every worker.

Run: gunicorn -c conf/gunicorn.conf.py app.main:app
"""

import json
import os
from pathlib import Path

bind = os.environ.get("GUNICORN_BIND", "0.0.0.0:8000")
# Async workers: about one per CPU the container may use (not 2 x cores + 1, which is for sync workers)
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
# uvicorn.workers.UvicornWorker still exists in uvicorn 0.39 but is deprecated
worker_class = "uvicorn_worker.UvicornWorker"

# Worker recycling: restart each worker after ~1000 requests (jitter spreads the restarts)
max_requests = int(os.environ.get("GUNICORN_MAX_REQUESTS", "1000"))
max_requests_jitter = int(os.environ.get("GUNICORN_MAX_REQUESTS_JITTER", "100"))

timeout = 30  # a worker that does not heartbeat for 30 s is killed and replaced
graceful_timeout = int(os.environ.get("GUNICORN_GRACEFUL_TIMEOUT", "25"))  # below the pod's grace period
keepalive = 5  # longer than 2 when a load balancer keeps idle connections open
backlog = 2048

# Behind a reverse proxy: trust X-Forwarded-* only from it
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")

accesslog = None  # the app writes its own JSON access line (app.access)
logconfig_dict = json.loads((Path(__file__).parent / "log-config.json").read_text())


def post_worker_init(worker):  # Gunicorn server hook
    worker.log.info("worker %s ready", worker.pid)
# syntax=docker/dockerfile:1
# Build: docker build -t orders-api .   (expected, not run on the build machine)

# ---- 1. builder: uv resolves and installs into /app/.venv ----
FROM python:3.12-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:0.13.10 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=never
WORKDIR /app
# Dependencies only: this layer is rebuilt only when uv.lock or pyproject.toml change
RUN --mount=type=cache,target=/root/.cache/uv \
    --mount=type=bind,source=uv.lock,target=uv.lock \
    --mount=type=bind,source=pyproject.toml,target=pyproject.toml \
    uv sync --locked --no-install-project --no-dev

# ---- 2. runtime: no uv, no compilers, no dev dependencies, non-root ----
FROM python:3.12-slim AS runtime
RUN apt-get update \
    && apt-get install -y --no-install-recommends tini \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd --system --gid 10001 app \
    && useradd --system --uid 10001 --gid app --no-create-home app
ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    APP_ENV=prod
WORKDIR /app
COPY --from=builder --chown=app:app /app/.venv /app/.venv
COPY --chown=app:app app ./app
COPY --chown=app:app conf ./conf
USER app
EXPOSE 8000
# Liveness from Docker's point of view; Kubernetes ignores HEALTHCHECK and uses its own probes
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD ["python", "-c", "import urllib.request,sys; sys.exit(urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status != 200)"]
# Exec form: tini is PID 1, forwards SIGTERM to uvicorn and reaps zombies (ProcessPoolExecutor children)
ENTRYPOINT ["tini", "--"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", \
     "--workers", "2", "--log-config", "conf/log-config.json", "--no-access-log", \
     "--proxy-headers", "--forwarded-allow-ips", "10.0.0.0/8", \
     "--timeout-graceful-shutdown", "20", "--timeout-keep-alive", "5"]
ini
.venv
.env
.env.*
!.env.example
**/__pycache__
.pytest_cache
tests
*.db
Dockerfile
.dockerignore
ini
# Copy to .env for local development only. Never bake .env into an image; never commit secrets.
APP_ENV=dev
APP_DATABASE_URL=sqlite:///./orders.db
APP_SECRET_KEY=change-me
APP_LOG_LEVEL=DEBUG
APP_LOG_JSON=false
APP_ALLOWED_HOSTS=["localhost","127.0.0.1"]
APP_CORS_ORIGINS=["http://localhost:5173"]
APP_THREADPOOL_TOKENS=40

The load tool, the shutdown probe and the serialisation benchmark:

py
"""A small closed-loop load generator: N concurrent clients, each sends the next request
as soon as the previous one returns. Reports throughput, p50/p90/p99 and the worker PIDs.

    python -m loadtool.load http://127.0.0.1:8000/work/async?ms=50 -c 100 -n 3000

The client is Python too: past a few thousand requests per second it becomes the bottleneck,
so keep per-request latency in the tens of milliseconds when comparing servers.
"""

import argparse
import asyncio
import json
import math
import time
from collections import Counter
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Sequence

import httpx


def percentile(sorted_values: Sequence[float], p: float) -> float:
    """Nearest-rank percentile on an already sorted list (p in 0..100)."""
    if not sorted_values:
        return float("nan")
    rank = max(1, math.ceil(p / 100 * len(sorted_values)))
    return sorted_values[rank - 1]


@dataclass
class Result:
    latencies_ms: List[float] = field(default_factory=list)
    statuses: Counter = field(default_factory=Counter)
    pids: Counter = field(default_factory=Counter)
    errors: Counter = field(default_factory=Counter)
    elapsed_s: float = 0.0

    def summary(self) -> Dict[str, object]:
        lat = sorted(self.latencies_ms)
        done = len(lat)
        return {
            "requests": done,
            "elapsed_s": round(self.elapsed_s, 3),
            "rps": round(done / self.elapsed_s, 1) if self.elapsed_s else 0.0,
            "p50_ms": round(percentile(lat, 50), 1),
            "p90_ms": round(percentile(lat, 90), 1),
            "p99_ms": round(percentile(lat, 99), 1),
            "max_ms": round(lat[-1], 1) if lat else float("nan"),
            "statuses": dict(self.statuses),
            "errors": dict(self.errors),
            "pids": dict(self.pids),
        }


async def run(
    url: str, concurrency: int, total: int, warmup: int = 0, timeout: float = 30.0, shared_pool: bool = False
) -> Result:
    """One AsyncClient (one keep-alive connection) per virtual user.

    shared_pool=True puts every user on one client with `concurrency` connections; on httpx 0.28
    that pool itself became the bottleneck above ~16 users (see runs/loadtool-calibration.txt).
    """
    result = Result()
    remaining = total

    def new_client(connections: int) -> httpx.AsyncClient:
        limits = httpx.Limits(max_connections=connections, max_keepalive_connections=connections)
        # trust_env=False: never route through HTTP(S)_PROXY or the OS proxy settings
        return httpx.AsyncClient(limits=limits, timeout=timeout, trust_env=False)

    async def one_user(client: httpx.AsyncClient) -> None:
        nonlocal remaining
        while remaining > 0:
            remaining -= 1
            start = time.perf_counter()
            try:
                resp = await client.get(url)
            except httpx.HTTPError as exc:
                result.errors[type(exc).__name__] += 1
                continue
            result.latencies_ms.append((time.perf_counter() - start) * 1000)
            result.statuses[resp.status_code] += 1
            pid: Optional[int] = None
            if resp.headers.get("content-type", "").startswith("application/json"):
                try:
                    pid = resp.json().get("pid")
                except (ValueError, AttributeError):
                    pid = None
            if pid is not None:
                result.pids[pid] += 1

    if shared_pool:
        clients = [new_client(concurrency)] * concurrency
    else:
        clients = [new_client(1) for _ in range(concurrency)]
    try:
        # Warm-up: open every connection before the clock starts
        await asyncio.gather(*(c.get(url) for c in clients[:warmup] or clients[:1]))
        started = time.perf_counter()
        await asyncio.gather(*(one_user(c) for c in clients))
        result.elapsed_s = time.perf_counter() - started
    finally:
        for c in set(clients):
            await c.aclose()
    return result


def main(argv: Optional[Sequence[str]] = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("url")
    parser.add_argument("-c", "--concurrency", type=int, default=50)
    parser.add_argument("-n", "--requests", type=int, default=1000)
    parser.add_argument("--warmup", type=int, default=20)
    parser.add_argument("--label", default="")
    parser.add_argument("--shared-pool", action="store_true", help="all users on one client (slower)")
    args = parser.parse_args(argv)
    result = asyncio.run(run(args.url, args.concurrency, args.requests, args.warmup, shared_pool=args.shared_pool))
    out = {"label": args.label, "url": args.url, "concurrency": args.concurrency, **result.summary()}
    print(json.dumps(out))


if __name__ == "__main__":
    main()
py
"""Graceful-shutdown probe: start a server, put a slow request in flight, send SIGTERM,
try a new connection, and print a timeline of what the client and the server saw.

    python tools/shutdown_probe.py --port 18751 --slow 3 --term-after 1 -- \
        uvicorn app.main:app --port 18751 --log-config conf/log-config.json
"""

import argparse
import asyncio
import os
import signal
import subprocess
import sys
import time

import httpx

T0 = time.perf_counter()


def stamp(msg: str) -> None:
    print(f"[client t={time.perf_counter() - T0:6.3f}s] {msg}", flush=True)


async def wait_ready(base: str, timeout: float = 15.0) -> None:
    deadline = time.perf_counter() + timeout
    async with httpx.AsyncClient(trust_env=False) as c:
        while time.perf_counter() < deadline:
            try:
                if (await c.get(f"{base}/healthz")).status_code == 200:
                    return
            except httpx.TransportError:
                pass
            await asyncio.sleep(0.1)
    raise RuntimeError("server did not become ready")


async def slow_request(base: str, seconds: float) -> None:
    async with httpx.AsyncClient(timeout=60, trust_env=False) as c:
        stamp(f"GET /work/slow?seconds={seconds} sent")
        try:
            r = await c.get(f"{base}/work/slow", params={"seconds": seconds})
            stamp(f"slow request finished: {r.status_code} {r.text}")
        except httpx.HTTPError as exc:
            stamp(f"slow request failed: {type(exc).__name__}: {exc!r}")


async def new_request_after_term(base: str) -> None:
    async with httpx.AsyncClient(timeout=3, trust_env=False) as c:
        try:
            r = await c.get(f"{base}/healthz")
            stamp(f"new request after SIGTERM: {r.status_code}")
        except httpx.HTTPError as exc:
            stamp(f"new request after SIGTERM: {type(exc).__name__}")


async def main(args: argparse.Namespace) -> int:
    base = f"http://127.0.0.1:{args.port}"
    proc = subprocess.Popen(args.cmd, stdout=sys.stdout, stderr=subprocess.STDOUT)
    stamp(f"server started, pid {proc.pid}: {' '.join(args.cmd)}")
    try:
        await wait_ready(base)
        stamp("server ready")
        tasks = [asyncio.create_task(slow_request(base, args.slow)) for _ in range(args.inflight)]
        await asyncio.sleep(args.term_after)
        os.kill(proc.pid, signal.SIGTERM)
        stamp(f"SIGTERM sent to pid {proc.pid}")
        await asyncio.sleep(0.3)
        await new_request_after_term(base)
        await asyncio.gather(*tasks)
        code = await asyncio.get_running_loop().run_in_executor(None, proc.wait, 60)
        stamp(f"server exited with code {code}")
        return 0
    finally:
        if proc.poll() is None:
            proc.kill()
            stamp("server killed (did not exit)")


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--port", type=int, required=True)
    p.add_argument("--slow", type=float, default=3.0)
    p.add_argument("--term-after", type=float, default=1.0)
    p.add_argument("--inflight", type=int, default=1)
    p.add_argument("cmd", nargs=argparse.REMAINDER)
    a = p.parse_args()
    if a.cmd and a.cmd[0] == "--":
        a.cmd = a.cmd[1:]
    sys.exit(asyncio.run(main(a)))
py
"""Where the time goes when an endpoint returns 2,000 objects: validation and JSON encoding.

    python tools/serialization_cost.py            # timings
    python tools/serialization_cost.py --profile  # cProfile of one request through the app
"""

import cProfile
import json
import pstats
import sys
import timeit
from typing import List

import orjson
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, TypeAdapter


class Item(BaseModel):
    id: int
    sku: str
    price: float


ITEMS = [{"id": i, "sku": f"SKU-{i:06d}", "price": i * 1.5} for i in range(2000)]
ADAPTER = TypeAdapter(List[Item])


def stdlib_json() -> bytes:
    # What JSONResponse does after FastAPI's jsonable_encoder
    return json.dumps(jsonable_encoder(ITEMS), separators=(",", ":")).encode()


def orjson_dicts() -> bytes:
    return orjson.dumps(ITEMS)


def pydantic_validate_and_dump() -> bytes:
    # What response_model=List[Item] costs: validate, then serialise in Rust
    return ADAPTER.dump_json(ADAPTER.validate_python(ITEMS))


def main() -> None:
    assert json.loads(stdlib_json()) == json.loads(orjson_dicts()) == json.loads(pydantic_validate_and_dump())
    for fn in (stdlib_json, orjson_dicts, pydantic_validate_and_dump):
        best = min(timeit.repeat(fn, number=50, repeat=5)) / 50
        print(f"{fn.__name__:28s} {best * 1000:7.2f} ms per 2,000 items")


def profile() -> None:
    # Same thread as the profiler: drive the ASGI app with httpx.ASGITransport (TestClient
    # would run the app in another thread, which cProfile does not see)
    import asyncio

    import httpx

    from app.main import create_app
    from app.settings import Settings

    app = create_app(Settings(_env_file=None, database_url="sqlite://"))

    async def twenty_requests() -> None:
        transport = httpx.ASGITransport(app=app)
        async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
            for _ in range(20):
                assert (await client.get("/work/big?items=2000")).status_code == 200

    prof = cProfile.Profile()
    prof.enable()
    asyncio.run(twenty_requests())
    prof.disable()
    pstats.Stats(prof).sort_stats("tottime").print_stats(8)


if __name__ == "__main__":
    profile() if "--profile" in sys.argv else main()

The tests (62, all real): settings precedence and validation, the request-ID middleware, the app (health, readiness, lifespan, security, CORS, gzip, metrics, streaming), logging, the load tool and the deployment files.

py
from typing import Callable, Iterator

import pytest
from fastapi.testclient import TestClient
from prometheus_client import CollectorRegistry

from app.main import create_app
from app.settings import Settings, get_settings


@pytest.fixture(autouse=True)
def clean_env(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
    """No APP_* variable from the developer's shell may leak into a test."""
    import os

    for key in list(os.environ):
        if key.startswith("APP_"):
            monkeypatch.delenv(key)
    get_settings.cache_clear()
    yield
    get_settings.cache_clear()


@pytest.fixture
def make_settings(tmp_path) -> Callable[..., Settings]:
    def factory(**overrides) -> Settings:
        values = {"database_url": f"sqlite:///{tmp_path / 'test.db'}", "_env_file": None}
        values.update(overrides)
        return Settings(**values)

    return factory


@pytest.fixture
def client(make_settings) -> Iterator[TestClient]:
    # A fresh metrics registry per app: the default one is process-wide
    app = create_app(make_settings(), metrics_registry=CollectorRegistry())
    with TestClient(app) as c:  # the with-block runs the lifespan
        yield c
py
import pytest
from pydantic import SecretStr, ValidationError

from app.settings import Settings, get_settings


def test_defaults_without_env_or_file():
    s = Settings(_env_file=None)
    assert s.env == "dev"
    assert s.threadpool_tokens == 40
    assert s.show_docs is True


def test_dotenv_overrides_default(tmp_path):
    env_file = tmp_path / ".env"
    env_file.write_text("APP_SERVICE_NAME=from-dotenv\nAPP_DB_POOL_SIZE=7\n")
    s = Settings(_env_file=env_file)
    assert s.service_name == "from-dotenv"
    assert s.db_pool_size == 7  # "7" in the file, int after validation


def test_real_environment_beats_dotenv(tmp_path, monkeypatch):
    env_file = tmp_path / ".env"
    env_file.write_text("APP_SERVICE_NAME=from-dotenv\n")
    monkeypatch.setenv("APP_SERVICE_NAME", "from-environ")
    assert Settings(_env_file=env_file).service_name == "from-environ"


def test_init_kwargs_beat_everything(tmp_path, monkeypatch):
    env_file = tmp_path / ".env"
    env_file.write_text("APP_SERVICE_NAME=from-dotenv\n")
    monkeypatch.setenv("APP_SERVICE_NAME", "from-environ")
    assert Settings(_env_file=env_file, service_name="from-kwargs").service_name == "from-kwargs"


def test_secrets_dir_is_the_lowest_source(tmp_path, monkeypatch):
    secrets = tmp_path / "secrets"
    secrets.mkdir()
    (secrets / "app_secret_key").write_text("from-secret-file")
    assert Settings(_env_file=None, _secrets_dir=secrets).secret_key.get_secret_value() == "from-secret-file"
    monkeypatch.setenv("APP_SECRET_KEY", "from-environ")
    assert Settings(_env_file=None, _secrets_dir=secrets).secret_key.get_secret_value() == "from-environ"


def test_unprefixed_variable_is_ignored(monkeypatch):
    monkeypatch.setenv("SERVICE_NAME", "no-prefix")
    assert Settings(_env_file=None).service_name == "orders-api"


def test_list_from_json_environment_variable(monkeypatch):
    monkeypatch.setenv("APP_ALLOWED_HOSTS", '["api.example.com","*.internal"]')
    assert Settings(_env_file=None).allowed_hosts == ["api.example.com", "*.internal"]


def test_wrong_type_fails_at_startup(monkeypatch):
    monkeypatch.setenv("APP_DB_POOL_SIZE", "many")
    with pytest.raises(ValidationError) as err:
        Settings(_env_file=None)
    assert err.value.errors()[0]["loc"] == ("db_pool_size",)


def test_secretstr_is_masked_everywhere_but_get_secret_value(monkeypatch):
    monkeypatch.setenv("APP_SECRET_KEY", "s3cr3t-value")
    s = Settings(_env_file=None)
    assert isinstance(s.secret_key, SecretStr)
    assert str(s.secret_key) == "**********"
    assert "s3cr3t-value" not in repr(s)
    assert "s3cr3t-value" not in s.model_dump_json()
    assert s.secret_key.get_secret_value() == "s3cr3t-value"


def test_prod_refuses_the_dev_secret():
    with pytest.raises(ValidationError, match="APP_SECRET_KEY must be set in prod"):
        Settings(_env_file=None, env="prod")


def test_prod_refuses_wildcard_hosts():
    with pytest.raises(ValidationError, match="must not be"):
        Settings(_env_file=None, env="prod", secret_key="x" * 32, allowed_hosts=["*"])


def test_prod_hides_docs_unless_enabled():
    prod = Settings(_env_file=None, env="prod", secret_key="x" * 32)
    assert prod.show_docs is False
    assert Settings(_env_file=None, env="prod", secret_key="x" * 32, docs_enabled=True).show_docs is True


def test_unknown_env_name_is_rejected():
    with pytest.raises(ValidationError):
        Settings(_env_file=None, env="production")


def test_get_settings_is_cached_until_cache_clear(monkeypatch):
    monkeypatch.setenv("APP_SERVICE_NAME", "first")
    first = get_settings()
    monkeypatch.setenv("APP_SERVICE_NAME", "second")
    assert get_settings() is first  # lru_cache: environment changes are not seen
    get_settings.cache_clear()
    assert get_settings().service_name == "second"
py
import logging
import re

import anyio
from fastapi import FastAPI
from fastapi.testclient import TestClient

from app.logging_setup import RequestIdFilter, request_id_var
from app.middleware import RequestIDMiddleware

HEX32 = re.compile(r"^[0-9a-f]{32}$")


def probe_app() -> FastAPI:
    app = FastAPI()
    log = logging.getLogger("app.probe")

    @app.get("/async")
    async def in_async():
        log.info("inside async endpoint")
        return {"rid": request_id_var.get()}

    @app.get("/sync")
    def in_sync():
        # Runs in a worker thread: the context was copied by run_in_threadpool
        log.info("inside sync endpoint")
        return {"rid": request_id_var.get()}

    @app.get("/fail")
    async def fail():
        raise RuntimeError("boom")

    app.add_middleware(RequestIDMiddleware)
    return app


def test_generates_an_id_when_none_is_sent():
    with TestClient(probe_app()) as c:
        r = c.get("/async")
    assert HEX32.match(r.headers["x-request-id"])
    assert r.json()["rid"] == r.headers["x-request-id"]


def test_keeps_a_valid_incoming_id():
    with TestClient(probe_app()) as c:
        r = c.get("/async", headers={"X-Request-ID": "edge-7f3a9c01"})
    assert r.headers["x-request-id"] == "edge-7f3a9c01"
    assert r.json()["rid"] == "edge-7f3a9c01"


def test_replaces_an_unsafe_incoming_id():
    with TestClient(probe_app()) as c:
        r = c.get("/async", headers={"X-Request-ID": "bad id\twith spaces"})
        r2 = c.get("/async", headers={"X-Request-ID": "x" * 500})
    assert HEX32.match(r.headers["x-request-id"])
    assert HEX32.match(r2.headers["x-request-id"])


def test_sync_endpoint_in_threadpool_sees_the_same_id():
    with TestClient(probe_app()) as c:
        r = c.get("/sync", headers={"X-Request-ID": "thread-check-01"})
    assert r.json()["rid"] == "thread-check-01"


def test_every_log_record_of_the_request_carries_the_id(caplog):
    caplog.handler.addFilter(RequestIdFilter())
    with caplog.at_level(logging.INFO):
        with TestClient(probe_app()) as c:
            c.get("/sync", headers={"X-Request-ID": "log-check-0001"})
    ours = [r for r in caplog.records if r.name in ("app.probe", "app.access")]
    assert [r.name for r in ours] == ["app.probe", "app.access"]
    assert {r.request_id for r in ours} == {"log-check-0001"}
    access = ours[-1]
    assert (access.method, access.path, access.status) == ("GET", "/sync", 200)
    assert access.duration_ms >= 0


def test_unhandled_error_still_returns_the_id():
    with TestClient(probe_app(), raise_server_exceptions=False) as c:
        r = c.get("/fail", headers={"X-Request-ID": "error-check-01"})
    assert r.status_code == 500
    assert r.headers["x-request-id"] == "error-check-01"
    assert r.json() == {"detail": "Internal Server Error", "request_id": "error-check-01"}


def test_context_is_reset_after_the_request():
    with TestClient(probe_app()) as c:
        c.get("/async")
    assert request_id_var.get() == "-"


def test_concurrent_requests_do_not_mix_ids():
    import httpx

    app = probe_app()
    seen = {}

    async def main():
        transport = httpx.ASGITransport(app=app)
        async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:

            async def one(i: int):
                r = await c.get("/async", headers={"X-Request-ID": f"concurrent-{i:04d}"})
                seen[i] = r.json()["rid"]

            async with anyio.create_task_group() as tg:
                for i in range(50):
                    tg.start_soon(one, i)

    anyio.run(main)
    assert seen == {i: f"concurrent-{i:04d}" for i in range(50)}
py
import gzip

from fastapi.testclient import TestClient
from prometheus_client import CollectorRegistry

from app.main import create_app


def test_liveness_needs_nothing(client):
    r = client.get("/healthz")
    assert r.status_code == 200 and r.json() == {"status": "ok"}


def test_readiness_checks_the_database(client):
    r = client.get("/readyz")
    assert r.status_code == 200
    body = r.json()
    assert body["status"] == "ready" and body["db"] == "ok"
    assert body["pool"].startswith("Pool size: 5")


def test_readiness_is_503_when_the_database_is_unreachable(make_settings):
    app = create_app(make_settings(database_url="sqlite:////nonexistent-dir/x.db"))
    with TestClient(app) as c:
        r = c.get("/readyz")
        live = c.get("/healthz")
    assert r.status_code == 503
    assert r.json() == {"status": "unavailable", "db": "OperationalError"}
    assert live.status_code == 200  # liveness must not fail because the DB is down


def test_lifespan_creates_and_closes_resources(make_settings):
    app = create_app(make_settings(threadpool_tokens=7))
    with TestClient(app) as c:
        http = app.state.http
        assert not http.is_closed
        assert c.get("/info").json()["threadpool_tokens"] == 7
    assert http.is_closed  # shutdown half of the lifespan ran


def test_security_headers_on_every_response(client):
    r = client.get("/healthz")
    assert r.headers["x-content-type-options"] == "nosniff"
    assert r.headers["x-frame-options"] == "DENY"
    assert "strict-transport-security" not in r.headers  # HSTS only in prod


def test_hsts_in_prod(make_settings):
    app = create_app(make_settings(env="prod", secret_key="k" * 32))
    with TestClient(app) as c:
        assert c.get("/healthz").headers["strict-transport-security"].startswith("max-age=31536000")


def test_trusted_host_rejects_unknown_host(client):
    r = client.get("/healthz", headers={"Host": "evil.example"})
    assert r.status_code == 400 and r.text == "Invalid host header"
    assert "x-request-id" in r.headers  # the ID middleware sits outside TrustedHost
    assert r.headers["x-content-type-options"] == "nosniff"  # security headers are outermost


def test_unhandled_error_is_json_with_id_and_headers(make_settings):
    app = create_app(make_settings(), metrics_registry=CollectorRegistry())
    with TestClient(app, raise_server_exceptions=False) as c:
        r = c.get("/work/boom")
    assert r.status_code == 500
    assert r.json()["request_id"] == r.headers["x-request-id"]
    assert r.headers["x-frame-options"] == "DENY"


def test_strict_csp_everywhere_except_the_docs_pages(client):
    assert client.get("/healthz").headers["content-security-policy"].startswith("default-src 'none'")
    docs = client.get("/docs")
    # Swagger UI needs its CDN bundle and an inline script; the strict API policy would blank it
    assert "cdn.jsdelivr.net/npm/swagger-ui-dist" in docs.text and "<script>" in docs.text
    assert "content-security-policy" not in docs.headers
    assert docs.headers["x-frame-options"] == "DENY"


def test_probe_with_pod_ip_host_is_rejected_unless_host_header_set(client):
    # kubelet httpGet probes send the pod IP as Host unless httpHeaders sets "Host"
    assert client.get("/healthz", headers={"Host": "10.1.2.3:8000"}).status_code == 400
    assert client.get("/healthz", headers={"Host": "localhost"}).status_code == 200
    assert client.get("/healthz", headers={"Host": "127.0.0.1:8000"}).status_code == 200  # port ignored


def test_docs_on_in_dev_off_in_prod(client, make_settings):
    assert client.get("/docs").status_code == 200
    assert client.get("/openapi.json").status_code == 200
    app = create_app(make_settings(env="prod", secret_key="k" * 32))
    with TestClient(app) as c:
        assert c.get("/docs").status_code == 404
        assert c.get("/redoc").status_code == 404
        assert c.get("/openapi.json").status_code == 404


def test_cors_preflight_for_an_allowed_origin(make_settings):
    app = create_app(make_settings(cors_origins=["https://shop.example"]))
    with TestClient(app) as c:
        ok = c.options(
            "/info",
            headers={"Origin": "https://shop.example", "Access-Control-Request-Method": "GET"},
        )
        bad = c.options(
            "/info",
            headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "GET"},
        )
    assert ok.status_code == 200
    assert ok.headers["access-control-allow-origin"] == "https://shop.example"
    assert bad.status_code == 400


def test_https_redirect_when_enabled(make_settings):
    app = create_app(make_settings(https_redirect=True))
    with TestClient(app) as c:
        r = c.get("/healthz", follow_redirects=False)
    assert r.status_code == 307
    assert r.headers["location"] == "https://testserver/healthz"


def test_gzip_only_above_minimum_size(client):
    small = client.get("/healthz", headers={"Accept-Encoding": "gzip"})
    big = client.get("/work/big?items=2000", headers={"Accept-Encoding": "gzip"})
    assert "content-encoding" not in small.headers
    assert big.headers["content-encoding"] == "gzip"
    assert len(big.json()["items"]) == 2000
    raw = client.get("/work/big?items=2000", headers={"Accept-Encoding": "identity"}).content
    assert len(gzip.compress(raw)) < len(raw) / 3


def test_orjson_is_the_default_response_class(client):
    r = client.get("/info")
    assert r.headers["content-type"] == "application/json"
    assert r.content.startswith(b'{"service":"orders-api"')  # compact: no spaces


def test_info_never_prints_the_secret(make_settings):
    app = create_app(make_settings(secret_key="very-secret-value"))
    with TestClient(app) as c:
        body = c.get("/info").text
    assert "very-secret-value" not in body and "**********" in body


def _counter(text: str, series: str) -> float:
    for line in text.splitlines():
        if line.startswith(series + " "):
            return float(line.split()[-1])
    return 0.0


def test_metrics_after_traffic(client):
    series = 'http_requests_total{handler="/work/async",method="GET",status="2xx"}'
    before = _counter(client.get("/metrics").text, series)  # the registry is per process, shared by tests
    client.get("/work/async?ms=0")
    client.get("/work/async?ms=0")
    text = client.get("/metrics").text
    assert _counter(text, series) == before + 2
    assert "http_request_duration_seconds_bucket" in text
    assert 'handler="/healthz"' not in text  # excluded handler


def test_streaming_response_chunks(client):
    with client.stream("GET", "/work/stream?chunks=3") as r:
        lines = [line for line in r.iter_lines() if line]
    assert r.headers["content-type"] == "application/x-ndjson"
    assert lines == ['{"chunk": 0}', '{"chunk": 1}', '{"chunk": 2}']


def test_sync_async_cpu_and_process_endpoints_answer(client):
    for path in ("/work/async?ms=1", "/work/sync?ms=1", "/work/blocking?ms=1", "/work/cpu?n=10"):
        assert client.get(path).json()["pid"] > 0
    r = client.get("/work/cpu-process?n=10")
    assert r.json()["result"] == sum(i * i for i in range(10)) % 1000


def test_validation_error_still_gets_headers(client):
    r = client.get("/work/async?ms=-1")
    assert r.status_code == 422
    assert "x-request-id" in r.headers and r.headers["x-frame-options"] == "DENY"


def test_second_app_on_the_default_registry_records_nothing(make_settings):
    # app.main already instrumented its module-level app on the default registry at import;
    # the duplicate metrics are swallowed and this app silently gets no counters
    app = create_app(make_settings())
    with TestClient(app) as c:
        c.get("/work/async?ms=0")
        text = c.get("/metrics").text
    assert "http_requests_total{" not in text
    assert "python_gc_objects_collected_total" in text  # the process collectors are still there
py
import json
import logging
import subprocess
import sys
from pathlib import Path

from app.logging_setup import JsonFormatter, RequestIdFilter, build_log_config, request_id_var

ROOT = Path(__file__).resolve().parents[1]


def make_record(msg="hello", **extra):
    record = logging.LogRecord("app.test", logging.INFO, __file__, 1, msg, None, None)
    for k, v in extra.items():
        setattr(record, k, v)
    return record


def test_json_formatter_emits_one_json_object():
    token = request_id_var.set("fmt-check-0001")
    try:
        record = make_record(status=201, path="/orders")
        RequestIdFilter().filter(record)
        line = JsonFormatter().format(record)
    finally:
        request_id_var.reset(token)
    data = json.loads(line)
    assert "\n" not in line
    assert data["msg"] == "hello" and data["level"] == "INFO" and data["logger"] == "app.test"
    assert data["request_id"] == "fmt-check-0001"
    assert data["status"] == 201 and data["path"] == "/orders"
    assert data["ts"].endswith("Z")


def test_exceptions_are_inside_the_json_line():
    try:
        raise ValueError("bad")
    except ValueError:
        record = logging.LogRecord("app.test", logging.ERROR, __file__, 1, "failed", None, sys.exc_info())
    data = json.loads(JsonFormatter().format(record))
    assert "ValueError: bad" in data["exc"]


def test_checked_in_log_config_matches_the_builder():
    on_disk = json.loads((ROOT / "conf" / "log-config.json").read_text())
    assert on_disk == build_log_config()


def test_dictconfig_accepts_it_and_uvicorn_loggers_are_routed():
    # A child process, so the test runner's own logging stays untouched
    code = (
        "import json, logging, logging.config;"
        "logging.config.dictConfig(json.load(open('conf/log-config.json')));"
        "logging.getLogger('uvicorn.error').info('server says hi');"
        "logging.getLogger('uvicorn.access').info('dropped: below WARNING');"
        "logging.getLogger('app.access').info('request', extra={'status': 200})"
    )
    out = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, check=True)
    lines = [json.loads(line) for line in out.stdout.splitlines()]
    assert [(entry["logger"], entry["msg"]) for entry in lines] == [
        ("uvicorn.error", "server says hi"),
        ("app.access", "request"),
    ]
    assert lines[1]["status"] == 200 and lines[1]["request_id"] == "-"


def test_plain_format_for_local_development():
    cfg = build_log_config(level="DEBUG", json_logs=False)
    assert cfg["handlers"]["stdout"]["formatter"] == "plain"
    assert cfg["loggers"]["app"]["level"] == "DEBUG"
py
import math

import httpx
import pytest

from loadtool import load


def test_percentile_nearest_rank():
    values = sorted(float(v) for v in range(1, 101))  # 1..100
    assert load.percentile(values, 50) == 50
    assert load.percentile(values, 99) == 99
    assert load.percentile(values, 100) == 100
    assert load.percentile([7.0], 99) == 7.0
    assert math.isnan(load.percentile([], 50))


def test_summary_counts_and_rates():
    r = load.Result(latencies_ms=[10.0, 20.0, 30.0, 40.0], elapsed_s=2.0)
    r.statuses[200] = 4
    r.pids[123] = 4
    s = r.summary()
    assert s["requests"] == 4 and s["rps"] == 2.0
    assert (s["p50_ms"], s["p99_ms"], s["max_ms"]) == (20.0, 40.0, 40.0)
    assert s["pids"] == {123: 4}


def test_run_against_an_in_process_app(monkeypatch):
    from fastapi import FastAPI

    app = FastAPI()

    @app.get("/x")
    async def x():
        return {"pid": 42}

    real_client = httpx.AsyncClient

    def patched(**kwargs):
        kwargs["transport"] = httpx.ASGITransport(app=app)
        return real_client(**kwargs)

    monkeypatch.setattr(load.httpx, "AsyncClient", patched)
    import asyncio

    for shared in (False, True):
        result = asyncio.run(load.run("http://t/x", concurrency=5, total=23, warmup=5, shared_pool=shared))
        assert len(result.latencies_ms) == 23
        assert result.statuses == {200: 23} and result.pids == {42: 23}


@pytest.mark.parametrize("bad", [0, -1])
def test_zero_requests_means_no_work(bad):
    r = load.Result(elapsed_s=0.0)
    assert r.summary()["rps"] == 0.0 and bad <= 0
py
"""The Dockerfile and Gunicorn config are not run here; these tests read them for the rules the page states."""

import json
import re
import runpy
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def test_gunicorn_config_values(monkeypatch):
    monkeypatch.setenv("WEB_CONCURRENCY", "4")
    cfg = runpy.run_path(str(ROOT / "conf" / "gunicorn.conf.py"))
    assert cfg["workers"] == 4
    assert cfg["worker_class"] == "uvicorn_worker.UvicornWorker"
    assert cfg["max_requests"] == 1000 and cfg["max_requests_jitter"] == 100
    assert cfg["graceful_timeout"] < 30  # inside Kubernetes' default 30 s grace period
    assert cfg["logconfig_dict"]["loggers"]["gunicorn.error"]["handlers"] == ["stdout"]


def test_worker_class_is_importable():
    from uvicorn_worker import UvicornWorker

    assert UvicornWorker.CONFIG_KWARGS["loop"] == "auto"


def _dockerfile() -> str:
    return (ROOT / "Dockerfile").read_text()


def test_dockerfile_is_multi_stage_and_non_root():
    text = _dockerfile()
    assert len(re.findall(r"^FROM ", text, re.M)) == 2
    assert "--no-dev" in text and "--locked" in text and "UV_COMPILE_BYTECODE=1" in text
    users = re.findall(r"^USER (\S+)", text, re.M)
    assert users == ["app"]


def test_dockerfile_uses_exec_form_and_an_init():
    text = _dockerfile()
    entry = re.search(r"^ENTRYPOINT (.+)$", text, re.M).group(1)
    assert json.loads(entry) == ["tini", "--"]
    cmd = re.search(r"^CMD (\[.*?\])$", text, re.M | re.S).group(1)
    argv = json.loads(cmd.replace("\\\n", ""))
    assert argv[0] == "uvicorn" and "--timeout-graceful-shutdown" in argv
    assert "PYTHONUNBUFFERED=1" in text and "HEALTHCHECK" in text


def test_no_secrets_baked_into_the_image():
    text = _dockerfile()
    assert not re.search(r"^(ENV|ARG) .*SECRET", text, re.M)
    assert ".env" in (ROOT / ".dockerignore").read_text().split()
    assert "COPY . ." not in text
toml
[project]
name = "orders-api"
version = "0.1.0"
description = "Snippets for the FastAPI in Production chapter: settings, lifespan, logging, request IDs, health, metrics, workers, Docker"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ move to the latest releases (see the page).
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "pydantic-settings==2.11.0",
    # [standard] pulls uvloop, httptools, websockets, watchfiles and python-dotenv
    "uvicorn[standard]==0.39.0",
    "fastapi-cli==0.0.22",
    "gunicorn==23.0.0",
    "uvicorn-worker==0.4.0",
    "sqlalchemy==2.0.58",
    "httpx==0.28.1",
    "orjson==3.11.5",
    "prometheus-fastapi-instrumentator==7.1.0",
]

[dependency-groups]
dev = [
    "pytest==8.4.2",
]

[tool.uv]
# An application, not a library: uv installs the dependencies, never the project itself.
package = false

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]

The Python angle ​

Python's production story is shaped by three facts. First, the GIL: one CPython process runs Python bytecode on one core at a time, so parallelism for Python code means processes, and processes share nothing (not the pool, not the metrics registry, not an in-memory cache). Second, ASGI separates the server from the framework: Uvicorn, Hypercorn, Granian and now Gunicorn's own asgi worker can all run the same FastAPI app, and the process manager is a separate choice again. Third, FastAPI runs def endpoints and def dependencies through Starlette's run_in_threadpool, which uses AnyIO's default thread limiter (40 tokens), so a sync endpoint is concurrent but bounded. The pins here are the newest that install on CPython 3.9.6; on Python 3.12+ the same code runs on FastAPI 0.165.0, Uvicorn 0.55.0 and Gunicorn 27.0.1 (the import of ORJSONResponse still works there but is deprecated since 0.131.0; see Response cost). The snippet uses typing.Optional/List because a class body on 3.9 evaluates str | None at import time and fails; on 3.10+ write str | None.

The concept catalogue ​

Process model: one manager, N workers, each a complete copy of the appuvicorn app.main:app --workers 4Supervisor (parent process): binds :8000, spawns childrenspawn, not fork: each worker imports the app itselfrestarts dead workers; SIGHUP rolling restart;SIGTTIN / SIGTTOU add or remove one workergunicorn -k uvicorn_worker.UvicornWorker -w 4Master (arbiter): binds :8000, pre-forks workerstimeout 30: silent worker is killed and replacedmax_requests + jitter: worker recyclingboot failure: master exits with code 3Worker 1 (pid A)event loop: async defthread pool: 40 tokenslifespan: engine, httpxDB pool 5 + overflow 5own /metrics registryone GILWorker 2 (pid B)event loop: async defthread pool: 40 tokenslifespan: engine, httpxDB pool 5 + overflow 5own /metrics registryone GILWorker 3 (pid C)same as worker 1shares nothing in memorywith the othersWorker 4 (pid D)recycled aftermax_requests: new pid,lifespan runs againShared: the listening socket only (backlog 2048). The kernel hands each new connection to one worker;keep-alive connections stay on that worker. Budget: 4 workers x (5 + 5) = 40 DB connections per container.Measured here: CPU endpoint 47.9 req/s with 1 worker, 184.1 req/s with 4 (12-core arm64, uvicorn 0.39).

Running the ASGI server: uvicorn, fastapi run, fastapi dev Must-know ​

In plain words: FastAPI does not listen on a port; an ASGI server does. uvicorn app.main:app imports the module, finds the app object and serves it. fastapi run and fastapi dev are the same Uvicorn with different defaults.

Common misunderstanding: "fastapi dev is fine in a container." It turns on auto-reload (a watcher process restarts the server on file changes) and binds 127.0.0.1; the real run printed Started reloader process [2750] using WatchFiles. Reload and workers are exclusive: with WEB_CONCURRENCY=2 in the environment, Uvicorn under fastapi dev warned "workers" flag is ignored when reloading is enabled. (real, runs/fastapi-dev-web-concurrency.txt).

Definition: an ASGI server owns the socket, the HTTP parser, connection keep-alive and timeouts, and calls the application as await app(scope, receive, send). Uvicorn selects --loop auto (uvloop when installed) and --http auto (httptools when installed). fastapi run (from fastapi-cli) discovers the app from a path, prints the import string it used, and starts Uvicorn bound to 0.0.0.0:8000 without reload; fastapi dev binds 127.0.0.1 with reload. uvicorn.run(app, ...) from Python works for one process; the Uvicorn docs note that passing the app object "only works if you are not using multiprocessing (workers=NUM) or reloading (reload=True), so we recommend using the import string style". --factory calls a factory instead: uvicorn app.main:create_app --factory.

fastapi run app/main.py --port 18758 --workers 2       (real, rich output stripped)
1  FastAPI   Starting production server
2  module    app / __init__.py, main.py
3  code      from app.main import app
4  app       Using import string: app.main:app
5  server    Server started at http://0.0.0.0:18758
6  INFO      Uvicorn running on http://0.0.0.0:18758
7  INFO      Started parent process [2564]
8  INFO      Started server process [2567]        <- worker 1
9  INFO      Started server process [2568]        <- worker 2
10 INFO      Application startup complete.        (twice: one lifespan per worker)

Real scenario: a Compose service runs fastapi dev and every docker cp restarts the server mid-request; a Kubernetes container runs uvicorn ... --reload and burns a core on file watching; a team writes uvicorn.run(app, workers=4) and gets a warning instead of four workers; an image uses fastapi run and is surprised that it listens on all interfaces (fine in a container, not on a shared host).

Entry pointBindsReloadWorkersLog format
uvicorn app.main:app127.0.0.1:8000off$WEB_CONCURRENCY or 1Uvicorn default or --log-config
fastapi run app/main.py0.0.0.0:8000off--workersFastAPI CLI (rich) formatting
fastapi dev app/main.py127.0.0.1:8000on (WatchFiles)ignoredFastAPI CLI formatting
gunicorn -k uvicorn_worker.UvicornWorker127.0.0.1:8000--reload possible-w or $WEB_CONCURRENCYGunicorn + logconfig_dict
uvicorn.run(app) in codeas givenonly with import stringonly with import stringas given

Worker processes: --workers and Uvicorn's supervisor Must-know ​

In plain words: one worker is one complete copy of the app in its own process. --workers 4 starts a parent that owns the socket and four children that serve requests; the parent restarts any child that dies.

Common misunderstanding: "Four workers make my async API four times faster." The real run: a CPU-bound endpoint (21 ms of pure Python per request) went from 47.9 to 184.1 req/s with 4 workers, while an async def endpoint that waits 20 ms served 1,385.5 req/s with one worker and 1,353.3 with four: the single event loop was not the bottleneck.

Definition: --workers N (default $WEB_CONCURRENCY or 1) starts Uvicorn's multiprocess supervisor. Uvicorn's docs: "Unlike gunicorn, uvicorn does not use pre-fork, but uses spawn", so each child imports the app itself. The supervisor restarts children that die and pings them (--timeout-worker-healthcheck, default 5 s); on Unix, SIGHUP restarts the workers one at a time, SIGTTIN adds one and SIGTTOU removes one. The kernel hands each new connection on the shared listening socket to one worker, and a keep-alive connection stays on that worker.

uvicorn app.main:app --port 18742 --workers 4     (real ps output, repeat run)
1  85567 85566  uvicorn app.main:app --port 18742 --workers 4         <- supervisor
2  85588 85567  multiprocessing.resource_tracker
3  85589 85567  multiprocessing.spawn spawn_main(... ) --multiprocessing-fork   <- worker
4  85590 85567  ... worker
5  85591 85567  ... worker
6  85592 85567  ... worker
load: /work/cpu?n=600000 (21 ms CPU), 16 users, 600 requests
7  1 worker : 47.9 req/s   p50 333.1 ms  p99 493.5 ms
8  4 workers: 184.1 req/s  p50  52.2 ms  p99 248.9 ms   pids 150 / 150 / 149 / 151 requests

Real scenario: a report endpoint that renders PDFs in Python scales with workers; a JSON proxy that awaits upstreams does not and just uses more memory; a VM with 8 cores runs one container with --workers 8, while Kubernetes runs eight pods with one worker each; a batch of identical PIDs in the logs shows that one long-lived keep-alive connection from the load balancer pins its traffic to one worker.

Workload (real, this machine)1 worker4 workersWhy
CPU-bound def, 16 users47.9 req/s, p99 493.5 ms184.1 req/s, p99 248.9 ms (repeat run; first run 140.3 with one idle worker)Four GILs, four cores
CPU-bound def, 32 users47.3 req/s, p99 886.9 ms170.7 and 186.1 req/sSame; latency queues behind the cores
async def with 20 ms await1,385.5 req/s1,353.3 req/sOne loop already overlaps the waits

The first 4-worker CPU run left one worker idle (3 of 4 PIDs served requests, 140.3 req/s); the repeat run spread 600 requests 150/150/149/151. Connection-to-worker assignment is the kernel's choice and is not guaranteed to be even, which is one more reason to measure with enough connections.

Gunicorn as the process manager: UvicornWorker, pre-fork, master process Must-know ​

In plain words: Gunicorn is a mature process manager. Its master process binds the socket and forks workers; with -k uvicorn_worker.UvicornWorker each worker runs Uvicorn's event loop and HTTP stack, so you get Gunicorn's management with Uvicorn's speed.

Common misunderstanding: "Gunicorn is required for production FastAPI." The FastAPI docs now recommend --workers on uvicorn/fastapi run and say that the old Gunicorn-based image is deprecated. Gunicorn is a choice for its extras: server hooks, the heartbeat timeout, max_requests recycling, --preload, USR2 binary upgrades, and a master that exits when workers cannot boot.

Definition: Gunicorn's design: "an arbiter process manages worker processes, while the workers handle requests and responses. The arbiter never touches individual client sockets." The worker class comes from the uvicorn-worker package (uvicorn_worker.UvicornWorker, or UvicornH11Worker for PyPy); uvicorn.workers.UvicornWorker still exists in Uvicorn 0.39 and is deprecated. Uvicorn's docs add that "some options such as --limit-concurrency are not yet supported when running with Gunicorn"; extra Uvicorn settings go into a subclass's CONFIG_KWARGS. Gunicorn's workers setting defaults to $WEB_CONCURRENCY or 1, timeout 30 ("Workers silent for more than this many seconds are killed and restarted"), graceful_timeout 30, keepalive 2, backlog 2048, forwarded_allow_ips '127.0.0.1,::1', bind 127.0.0.1:8000 (quoted from the current docs and identical in the installed 23.0.0 gunicorn/config.py, saved). Gunicorn 24.0.0+ also has its own --worker-class asgi (beta at 24.0.0), which removes Uvicorn from the picture entirely.

GUNICORN_BIND=127.0.0.1:18755 WEB_CONCURRENCY=2 gunicorn -c conf/gunicorn.conf.py app.main:app   (real)
1  gunicorn.error  Starting gunicorn 23.0.0
2  gunicorn.error  Listening at: http://127.0.0.1:18755 (1162)        <- master pid
3  gunicorn.error  Using worker: uvicorn_worker.UvicornWorker
4  gunicorn.error  Booting worker with pid: 1163
5  gunicorn.error  Booting worker with pid: 1164
6  gunicorn.error  worker 1163 ready                                  <- post_worker_init hook
7  app.lifespan    startup complete  worker_pid=1163                 <- lifespan inside the worker
boot failure (APP_ENV=prod, no APP_SECRET_KEY):
8  gunicorn.error  Exception in worker process
9  gunicorn.error  Reason: Worker failed to boot.
10 gunicorn.error  Shutting down: Master                              <- exit code 3

Real scenario: a service that leaks memory in a C extension is kept healthy by max_requests; a deploy with a broken secret fails loudly because the Gunicorn master exits with code 3 (while uvicorn --workers 2 with the same error kept respawning children: 10 failed worker starts in 8 s, the supervisor still alive); a team runs Gunicorn's gthread workers for a Django app and Uvicorn workers for the FastAPI app with the same operational tooling.

Concernuvicorn --workers (0.39 real)Gunicorn 23 + UvicornWorker (real)
Child creationspawn: each worker imports the appfork after the master loads the config (--preload loads the app in the master)
Dead workerrestartedrestarted
Stuck workerping timeout, killed (--timeout-worker-healthcheck)heartbeat timeout 30 s, killed and replaced
Recycling--limit-max-requests (jitter flag only in newer Uvicorn)max_requests + max_requests_jitter
Worker fails to bootsupervisor keeps respawning, stays upmaster stops, exit code 3
SIGTERM to the managerchildren drained, exit 0children drained, "Shutting down: Master", exit 0
--limit-concurrencyyesnot supported (subclass CONFIG_KWARGS)
Extra noise in logsnoneWorker (pid:…) was sent SIGTERM! at ERROR level on a normal stop; Error while closing socket [Errno 9] from the worker

Worker recycling: max_requests, --limit-max-requests and jitter Important ​

In plain words: after N requests a worker finishes its current requests, exits, and the manager starts a fresh one. It is a pressure valve for memory that grows slowly, not a fix for it.

Common misunderstanding: "Recycling is free." In the real run with max_requests=50 and no jitter, both workers hit the limit within 75 ms of each other, the p99 latency of 300 requests jumped to 577.3 ms (p50 6.8 ms), and five requests failed with ReadError because their keep-alive connections were closed by the exiting worker.

Definition: Gunicorn: max_requests ("The maximum number of requests a worker will process before restarting", default 0 = off) and max_requests_jitter ("The maximum jitter to add to the max_requests setting"). With UvicornWorker the limit is enforced by Uvicorn inside the worker, which logs Maximum request limit of 50 exceeded. Terminating process.. Uvicorn alone: --limit-max-requests ("Useful when running together with a process manager, for preventing memory leaks"); current Uvicorn adds --limit-max-requests-jitter, which is not in 0.39.0's --help. Each new worker runs the lifespan again: new pool, new clients, new metrics registry.

GUNICORN_MAX_REQUESTS=50 GUNICORN_MAX_REQUESTS_JITTER=0, 2 workers, 300 requests, 4 users (real)
1  14:00:06.416  uvicorn.error  Maximum request limit of 50 exceeded. Terminating process.  pid 1064
2  14:00:06.490  uvicorn.error  Maximum request limit of 50 exceeded. Terminating process.  pid 1068
3  14:00:06.517  app.lifespan   shutdown: closing http client, process pool and db pool     pid 1064
4  14:00:06.579  gunicorn.error Booting worker with pid: 1108
5  14:00:07.060  app.lifespan   startup complete                                            pid 1108
result: 295 x 200, 5 x ReadError, p50 6.8 ms, p99 577.3 ms; pids 1064, 1068, 1108, 1113, 1134

Real scenario: an image-processing service with a slowly growing C allocator heap recycles every 5,000 requests with jitter 500; a Laravel team moving from PHP-FPM (pm.max_requests) expects the same behaviour and gets it; a team turns recycling on to "fix" a leak and the leak's cause (an unbounded lru_cache on request data) stays unfound until a heap profile.

SettingServerDefaultEffect
max_requestsGunicorn0 (off)Restart a worker after N requests
max_requests_jitterGunicorn0Adds randint(0, jitter) so workers do not restart together
--limit-max-requestsUvicornnoneWorker exits after N requests (manager restarts it)
--limit-max-requests-jitterUvicorn (newer than 0.39)0Same jitter idea
pm.max_requestsPHP-FPM0The PHP equivalent
--max-requestsLaravel Octane500Octane's worker recycling

Lifespan in production: startup, shutdown, connection pool in lifespan Must-know ​

In plain words: the lifespan is the code before and after yield in one async context manager. Before yield: open what every request will share (engine and pool, HTTP client, process pool, thread-pool size). After yield: close it. It runs in every worker, once per worker life.

Common misunderstanding: "The shutdown half always runs." It runs only when the server shuts down gracefully: after SIGTERM and the drain. It does not run on SIGKILL (the grace period expired, or OOM), and with Uvicorn's --timeout-graceful-shutdown exceeded it runs after the remaining tasks were cancelled. The basics of @asynccontextmanager lifespans, app.state and lifespan state are in FastAPI Fundamentals and APIRouter & Project Structure; this block is about what goes into it in production.

Definition: Uvicorn sends the ASGI lifespan.startup event before it accepts requests (logged as Waiting for application startup. / Application startup complete.) and lifespan.shutdown after the drain (Waiting for application shutdown. / Application shutdown complete.). If startup raises, the worker does not serve. The snippet's lifespan sets anyio.to_thread.current_default_thread_limiter().total_tokens, creates the SQLAlchemy engine (pool_pre_ping=True, pool_size, max_overflow, pool_timeout), an httpx.AsyncClient with explicit timeouts and limits, and a ProcessPoolExecutor; after yield it closes the client, shuts down the process pool with cancel_futures=True and disposes the engine.

uvicorn app.main:app --log-config conf/log-config.json   (real, runs/shutdown-graceful-drain.txt)
1  uvicorn.error  Started server process [80609]
2  uvicorn.error  Waiting for application startup.
3  app.lifespan   startup complete  env=dev threadpool_tokens=40 worker_pid=80609
4  uvicorn.error  Application startup complete.
5  uvicorn.error  Uvicorn running on http://127.0.0.1:18751
   ... requests ...
6  uvicorn.error  Shutting down
7  uvicorn.error  Waiting for connections to close. (CTRL+C to force quit)
8  uvicorn.error  Waiting for application shutdown.
9  app.lifespan   shutdown: closing http client, process pool and db pool
10 app.lifespan   shutdown complete
11 uvicorn.error  Application shutdown complete.
12 uvicorn.error  Finished server process [80609]

Real scenario: an engine created at import time is shared by a forked Gunicorn worker with --preload and two processes write on the same socket (create it in the lifespan, or engine.dispose(close=False) after fork); an httpx.AsyncClient() per request leaks file descriptors under load (one client per worker, closed in the lifespan); a lifespan that runs migrations makes ten replicas race for the schema lock (Alembic runs them as a separate job); a model loaded in the lifespan makes startup take 40 s, so the readiness probe needs a startupProbe or a long initialDelaySeconds.

ResourceCreated inClosed inPerWhy not per request
SQLAlchemy Engine + QueuePoollifespanengine.dispose()workerConnections are expensive; the pool reuses them
httpx.AsyncClientlifespanawait client.aclose()workerKeep-alive and connection limits only work on a shared client
ProcessPoolExecutorlifespanshutdown(wait=True, cancel_futures=True)workerSpawning processes costs tens of ms
Thread-pool sizelifespan (total_tokens)nothingevent loopIt is a property of the loop's limiter
Settingsget_settings() (cached)nothingprocessValidated once, read everywhere
Session / transactiondependency with yieldafter the responserequestIt must not outlive the request (Depends)

Connection pool sizing: pool size vs workers vs the database Must-know ​

In plain words: every worker has its own pool. The number of connections the database sees is workers × (pool size + overflow) × replicas, and it has to stay below the database's limit with room for migrations, admins and other services.

Common misunderstanding: "Bigger pools are faster." A pool larger than the number of requests that hold a connection at once only adds idle connections; a pool larger than the thread pool cannot even be used by sync endpoints (40 threads, at most 40 checked-out connections per worker); and many short-lived connections cost the database memory per backend process (PostgreSQL forks one process per connection).

Definition: SQLAlchemy's QueuePool keeps up to pool_size connections open and allows max_overflow extra ones under load; a checkout waits up to pool_timeout seconds and then raises sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 5 reached, connection timed out, timeout 0.50 (real, runs/pool-timeout.txt, eleventh checkout with pool_timeout=0.5). pool_pre_ping=True issues a cheap ping on checkout (the real echo below shows Pool pre-ping on connection on the second checkout). engine.pool.status() returns the counters the snippet's /readyz reports: Pool size: 5 Connections in pool: 1 Current Overflow: -4 Current Checked out connections: 0 (real).

connection budget, PostgreSQL max_connections = 100 (default), reserve 10 for admin/migrations
1  per worker      pool_size 5 + max_overflow 5                  = 10
2  per container   --workers 4                                    = 40
3  per service     2 replicas                                     = 80
4  rolling deploy  maxSurge 1: a 3rd container exists for a while = 120  > 90 available: errors
5  fix: pool 4+2 per worker (24 per container, 72 at surge), or PgBouncer in transaction mode

The readiness check, and the queries an operator runs to see the budget on PostgreSQL (the first block is the real SQLAlchemy echo from runs/readiness-sql-echo.txt, against SQLite; the PostgreSQL queries are expected, not run):

sql
-- what /readyz sends through the pool (real echo, SQLAlchemy 2.0.58)
BEGIN (implicit);
SELECT 1;
ROLLBACK;

-- PostgreSQL: the ceiling and who holds connections right now (expected, not run)
SHOW max_connections;
SELECT application_name, state, count(*) AS connections
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY application_name, state
ORDER BY connections DESC;

Real scenario: a team scales from 2 to 8 replicas for a sale and the database starts refusing connections with FATAL: sorry, too many clients already; a sync endpoint holds a connection while it calls a slow upstream, so the pool of 5 is exhausted at 5 concurrent requests and the sixth waits pool_timeout; PgBouncer in transaction mode lets 200 app connections share 20 server connections (and breaks session-level features such as prepared statements and SET).

KnobWhereDefaultRule of thumb
pool_sizeSQLAlchemy create_engine5 (installed 2.0.58 pool/impl.py)Peak concurrent checkouts per worker, measured
max_overflowSQLAlchemy10Small burst room; 0 makes the limit hard
pool_timeoutSQLAlchemy30 sBelow the request timeout, so callers fail fast
pool_pre_pingSQLAlchemyFalseTrue behind proxies and failovers that drop idle connections
pool_recycleSQLAlchemy-1Below the server's or proxy's idle timeout
max_connectionsPostgreSQL"typically 100" (PostgreSQL docs)Sum over all workers, replicas and surge must fit
--workers × replicasserver, orchestrator1 × 1Multiply before you deploy

Settings with pydantic-settings: BaseSettings, .env, SecretStr, the settings dependency Must-know ​

In plain words: one class lists every configuration value with its type and default. pydantic-settings fills it from environment variables, a .env file and a secrets directory, converts the strings to real types, and refuses to start if something is wrong.

Common misunderstanding: ".env overrides the environment." The opposite: pydantic-settings' order is, "in descending order of priority": CLI arguments (if enabled), "Arguments passed to the Settings class initialiser", "Environment variables", "Variables loaded from a dotenv (.env) file", "Variables loaded from the secrets directory", "The default field values". The tests assert each step (test_real_environment_beats_dotenv, test_init_kwargs_beat_everything, test_secrets_dir_is_the_lowest_source). Field syntax, env_nested_delimiter and validators are in Typing & Pydantic v2; SettingsConfigDict and the sources in detail are in APIRouter & Project Structure.

Definition: class Settings(BaseSettings) with model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env", secrets_dir=..., extra="ignore"). env_prefix is prepended to every field name (APP_DB_POOL_SIZE fills db_pool_size; an unprefixed SERVICE_NAME is ignored, test test_unprefixed_variable_is_ignored). Complex types are parsed from JSON (APP_ALLOWED_HOSTS='["api.example.com","*.internal"]'). SecretStr prints as ********** in str(), repr() and model_dump_json() and gives the value only through .get_secret_value(). The settings dependency is the FastAPI docs' pattern: @lru_cache def get_settings(): return Settings(), injected with Depends(get_settings); the cache means one validation per process and that changing the environment later has no effect until get_settings.cache_clear() (test test_get_settings_is_cached_until_cache_clear). In tests, either build Settings(...) explicitly (_env_file=None keeps a developer's .env out) or override get_settings with app.dependency_overrides.

which value wins for db_pool_size (tests/test_settings.py, real)
1  default in the class                       5
2  .env:            APP_DB_POOL_SIZE=7        7      (string "7" validated to int)
3  environment:     APP_SERVICE_NAME=...      beats .env
4  Settings(service_name="from-kwargs")       beats environment
5  APP_DB_POOL_SIZE=many                      ValidationError, loc ('db_pool_size',): process does not start

Real scenario: APP_DB_POOL_SIZE=many from a typo in a Helm value stops the pod at startup instead of failing the first request; a Kubernetes Secret mounted as files under /run/secrets fills secret_key through secrets_dir without the value ever being an environment variable (visible in /proc/<pid>/environ and in crash dumps); print(settings) in a debugging session shows secret_key=SecretStr('**********'); a staging .env baked into an image by accident is ignored because the real environment wins, and found by the .dockerignore test.

SourceExamplePriorityGood for
Init kwargsSettings(env="prod")1 (highest, after CLI)Tests, factories
Environment variableAPP_ENV=prod2Containers, 12-factor
.env fileAPP_ENV=dev in ./.env3Local development only
Secrets directory/run/secrets/app_secret_key4Docker/Kubernetes secrets as files
Field defaultenv: Literal[...] = "dev"5 (lowest)Safe local defaults

Environments dev/staging/prod and fail-fast configuration Important ​

In plain words: the same image runs in every environment; only the environment variables differ. The settings class knows which environment it is in and refuses dangerous combinations (prod with the development secret, prod with allowed_hosts=["*"]).

Common misunderstanding: "Use a different settings class per environment, selected by if ENV == ...." That puts environment knowledge in code and lets prod run with staging defaults. One class, an env: Literal["dev", "staging", "prod"] field (so production is rejected), derived properties (show_docs), and a model_validator for the cross-field rules is enough.

Definition: the snippet's prod_needs_real_secrets validator raises ValueError("APP_SECRET_KEY must be set in prod"). Because app = create_app() runs at import, the worker fails before it binds. Real runs: a single uvicorn process exits with code 1 and the ValidationError (Value error, APP_SECRET_KEY must be set in prod); Gunicorn's master prints Reason: Worker failed to boot. and exits with 3; uvicorn --workers 2 kept respawning failing children (10 failed starts in 8 s) and stayed up until SIGTERM, so in that mode the orchestrator learns about the problem only through a failing readiness probe.

Settingdevstagingprod
APP_ENVdevstagingprod
/docs, /openapi.jsononon (behind auth or VPN)off (404, real) unless APP_DOCS_ENABLED=true
Log format / levelplain text, DEBUGJSON, INFOJSON, INFO (WARNING for chatty libraries)
HSTS headernoyes if HTTPS end to endyes (real: max-age=31536000; includeSubDomains)
Secret source.envSecret managerSecret manager / mounted files
allowed_hostslocalhoststaging host namesreal host names; * rejected
Workers1 with reloadas prodfrom CPU limit

Logging: uvicorn.error, uvicorn.access, --log-config, dictConfig, log level Must-know ​

In plain words: Uvicorn logs through the standard logging module under two names: uvicorn.error (the server's own messages, not only errors) and uvicorn.access (one line per request). Give the server one dictConfig dictionary and route those loggers and your own to the same handler and format.

Common misunderstanding: "uvicorn.error contains errors." It contains Started server process, Application startup complete., Shutting down; tracebacks from the app are logged there too. And "--log-level warning changes the app's log level": it sets Uvicorn's loggers; the app's loggers follow the config you pass.

Definition: Uvicorn's settings page: "--log-config <path> - Logging configuration file. Options: dictConfig() formats: .json, .yaml. Any other format will be processed with fileConfig()." --log-level (critical … trace, default info) sets Uvicorn's loggers; "--no-access-log - Disable access log only, without changing log level." Gunicorn takes the same dictionary as logconfig_dict. The snippet's dictionary routes uvicorn.error, gunicorn.error and app.* to one stdout handler with the JSON formatter and the request-ID filter, sets uvicorn.access and gunicorn.access to WARNING (dropped), and writes its own app.access line with method, path, status, duration and client. disable_existing_loggers: False keeps loggers that libraries created at import.

default uvicorn logging (real, no --log-config)
1  INFO:     Started server process [99973]
2  INFO:     Application startup complete.
3  INFO:     127.0.0.1:49675 - "GET /healthz HTTP/1.1" 200 OK          <- uvicorn.access
same server with --log-config conf/log-config.json --no-access-log (real)
4  {"ts": "2026-11-29T13:59:25.623Z", "level": "INFO", "logger": "uvicorn.error", "msg": "Started server process [99817]", "request_id": "-", "pid": 99817, ...}
5  {"ts": "2026-11-29T13:59:25.787Z", "level": "INFO", "logger": "app.access", "msg": "request", "request_id": "edge-7f3a9c01", "pid": 99817, "method": "GET", "path": "/info", "status": 200, "duration_ms": 0.94, "client": "127.0.0.1"}

Real scenario: a log pipeline (Loki, Elasticsearch, CloudWatch) cannot parse coloured multi-line text and splits every traceback into twenty events; the access log is doubled because Uvicorn's and the app's are both on; PYTHONUNBUFFERED is missing and logs appear in bursts minutes late; a chatty library at DEBUG fills the disk because the root logger was set to DEBUG instead of the app logger.

LoggerWho writes itWhat it containsSnippet's level
uvicorn.errorUvicornStartup, shutdown, warnings ("Exceeded concurrency limit."), app tracebacksINFO
uvicorn.accessUvicornclient - "METHOD path HTTP/1.1" statusWARNING (off)
gunicorn.errorGunicornMaster and worker lifecycleINFO
gunicorn.accessGunicornAccess lines (unused with UvicornWorker + accesslog=None)WARNING
app.accessRequestIDMiddlewareJSON access line with duration and request IDINFO
app.*Application codeBusiness eventsfrom APP_LOG_LEVEL
rootEverything elseLibrary logsWARNING

Structured JSON logs and structlog Important ​

In plain words: one log event is one JSON object on one line: timestamp, level, logger, message, request ID, and fields such as status and duration_ms as real values instead of words in a sentence.

Common misunderstanding: "JSON logs need structlog." A twenty-line logging.Formatter subclass is enough (the snippet's JsonFormatter, tested); structlog adds processors, bound loggers and its own contextvars helpers, and python-json-logger is another drop-in formatter. What matters is one line per event, a stable field set, and exceptions inside the JSON ("exc": "Traceback ...", test test_exceptions_are_inside_the_json_line).

Definition: the snippet formatter copies every non-standard attribute of the LogRecord into the JSON, so logger.info("request", extra={"status": 200}) produces "status": 200. structlog's documented pattern for request context is structlog.contextvars.merge_contextvars() as the first processor, clear_contextvars() at the start of a request and bind_contextvars(...) to add fields; its standard-library integration lets uvicorn.* records go through the same renderer.

python
# The structlog equivalent of the snippet's filter + formatter (shape from structlog's docs; not run here)
import structlog

structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,  # request_id bound in the middleware
        structlog.processors.add_log_level,
        structlog.processors.TimeStamper(fmt="iso", utc=True),
        structlog.processors.format_exc_info,
        structlog.processors.JSONRenderer(),
    ]
)
# in the middleware: structlog.contextvars.clear_contextvars(); structlog.contextvars.bind_contextvars(request_id=rid)
log = structlog.get_logger("app")
log.info("order placed", order_id=42, total_cents=1999)
FieldExampleWhy
ts2026-11-29T13:59:25.787ZUTC, millisecond, sortable
levelINFOFiltering and alerting
loggerapp.accessWho wrote it
msgrequestShort, constant event name
request_idedge-7f3a9c01Join every line of one request, across services
pid99817Which worker (recycling, uneven load)
status, duration_ms, path200, 0.94, /infoMetrics from logs, slow-request search
excTraceback ...One event per error, not twenty lines

Request ID and correlation ID middleware with contextvars Must-know ​

In plain words: every request gets an ID (taken from X-Request-ID if a trusted caller sent a sane one, generated otherwise). The ID goes back in the response header, into a ContextVar, and from there into every log line written while that request runs, in coroutines and in thread-pool threads alike.

Common misunderstanding: "Use BaseHTTPMiddleware and request.state.request_id." Then the ID is not visible to a plain logging call deep in a library, and Starlette's docs list as a known limitation that "Using BaseHTTPMiddleware will prevent changes to contextvars.ContextVars from propagating upwards", recommending pure ASGI middleware instead. A pure ASGI middleware that sets a ContextVar before calling the app reaches everything below it: the snippet's tests check an async def route, a def route in the thread pool (test_sync_endpoint_in_threadpool_sees_the_same_id), 50 concurrent requests that do not mix IDs, and the reset after the request.

Definition: request_id_var: ContextVar[str] (default "-"); the middleware validates the incoming header against ^[A-Za-z0-9._-]{8,128}$ (anything else could be log injection) or uses uuid4().hex, sets the variable, wraps send to append X-Request-ID to http.response.start, and resets the token in finally. Starlette's run_in_threadpool copies the current context into the worker thread, so the thread sees the value; asyncio.create_task copies it too (contextvars across tasks and threads). A correlation ID is the same idea across services: pass it on outgoing calls (httpx default headers per request, or W3C traceparent with OpenTelemetry) so one user action can be followed through several services. Because Starlette's ServerErrorMiddleware sits outside every user middleware, an unhandled exception would produce a plain 500 without the header; the snippet's middleware catches the exception and sends its own JSON 500 with the ID (real, below).

curl -i http://127.0.0.1:18746/work/boom   (real)
1  HTTP/1.1 500 Internal Server Error
2  x-request-id: 38b854bb04bb4bac9f7bcb1b90f91381
3  x-content-type-options: nosniff
4  {"detail": "Internal Server Error", "request_id": "38b854bb04bb4bac9f7bcb1b90f91381"}
log line for the same request:
5  {"level": "INFO", "logger": "app.access", "request_id": "38b854bb04bb4bac9f7bcb1b90f91381", "path": "/work/boom", "status": 500, "duration_ms": 6.13}

Real scenario: support gets a screenshot with request_id and finds the five log lines and the traceback in one search; an API gateway (Nginx $request_id, AWS ALB X-Amzn-Trace-Id) sets the ID and the app reuses it; a client sends X-Request-ID: "\n{"level":"ERROR"... and the regex replaces it; a background task started with asyncio.create_task inside the request keeps logging with the right ID because the context was copied.

ApproachID in every log lineWorks in def endpointsWorks with streamingCost
Pure ASGI middleware + ContextVar (snippet)yes (filter)yes (context copied)yes~25 lines
BaseHTTPMiddleware + request.stateonly where you pass requestyeswraps the response bodysimpler, less reach
asgi-correlation-id packageyesyesyesone dependency
structlog bind_contextvarsyesyesyesstructlog setup
OpenTelemetry trace IDyes, with the logging instrumentationyesyesthe OTel SDK

Health endpoints: liveness vs readiness (and startup) Must-know ​

In plain words: liveness answers "is this process stuck, should you restart it?"; readiness answers "should you send it traffic right now?". They need different checks, because restarting a healthy process does not fix a database outage.

Common misunderstanding: "One /health that checks the database is safest." If the liveness probe checks the database, a database blip makes Kubernetes restart every pod at once, which turns a short outage into a long one (and the restarted pods all reconnect at the same moment). The snippet's test asserts the split: with an unreachable database /readyz is 503 {"status":"unavailable","db":"OperationalError"} while /healthz stays 200.

Definition: /healthz is async def and touches nothing but the event loop: if it answers, the loop is not blocked. /readyz is def (it runs in the thread pool, so it also notices thread-pool exhaustion) and checks SELECT 1 through the pool plus the pool counters. Kubernetes: a failed liveness probe restarts the container; a failed readiness probe removes the pod from Service endpoints; a startup probe holds both back until a slow start finishes. Docker's HEALTHCHECK sets a container's health status ("initially starting"), which Compose can use for depends_on: condition: service_healthy; Kubernetes ignores it. One trap with TrustedHostMiddleware: the Pod API reference says an httpGet probe's host "defaults to the pod IP. You probably want to set "Host" in httpHeaders instead.", and a request with Host: 10.1.2.3:8000 gets 400 from TrustedHost (test test_probe_with_pod_ip_host_is_rejected_unless_host_header_set), so a pod whose probes do not set Host never becomes ready. Set httpHeaders: [{name: Host, value: localhost}] on the probes (as in the pod spec) and keep localhost and 127.0.0.1 in allowed_hosts (TrustedHost ignores the port).

probe timeline during a 20 s database outage (expected, not run; values from the probe settings)
1  t=0     database stops answering
2  t=5     readinessProbe /readyz fails (periodSeconds 5)      livenessProbe /healthz ok
3  t=15    failureThreshold 3 reached: pod removed from endpoints, no new traffic to it
4  t=20    database back; /readyz ok after the next period
5  t=25    pod back in endpoints. No restart happened: pools, caches and warm workers kept
   with a DB check in liveness instead: t=15 every pod restarts at once, then all reconnect together

Real scenario: a pod that is warming a cache reports not-ready until it is done; a pod whose thread pool is saturated by slow sync calls fails /readyz (the check waits for a thread) and sheds traffic; a load balancer outside Kubernetes (AWS ALB target group, Nginx max_fails) uses /readyz the same way; /metrics and the probes are excluded from the access metrics so they do not dominate request counts.

ProbeEndpoint in the snippetChecksOn failureTypical settings
Liveness/healthzThe loop answersContainer restartedperiodSeconds: 10, failureThreshold: 3
Readiness/readyzDB round trip, pool, thread poolRemoved from endpointsperiodSeconds: 5, failureThreshold: 3
Startup/healthzStartup finishedLiveness/readiness waitfailureThreshold: 30, periodSeconds: 2
Docker HEALTHCHECK/healthzThe loop answersStatus unhealthy (Compose, Swarm)--interval=30s --timeout=3s

Graceful shutdown: SIGTERM, drain, --timeout-graceful-shutdown Must-know ​

SIGTERM to exit: stop accepting, drain, lifespan shutdownKubernetesUvicornRequestsLifespantimeTerminating: endpoints removedpreStop: sleep 5terminationGracePeriodSeconds (default 30) counts from the start of preStopstill running at the end: SIGKILL, no lifespan shutdownSIGTERM to PID 1 (tini) to uvicorn"Shutting down"close listener"Waiting for connectionsto close" (drain)timeout passed:cancel tasksin-flight GET /work/slow (3 s), started before SIGTERMfinishes: 200longer request (5 s) with --timeout-graceful-shutdown 2cancelled: 500new connection after SIGTERM: refused (ConnectError)resources open since startup (pool, httpx, process pool)after yield: close,dispose; exit 143measured (1 worker): SIGTERM 1.664 s | refused 1.968 s | 200 at 3.669 s | exit 3.709 s

In plain words: on SIGTERM Uvicorn closes the listening socket (new connections are refused), closes idle keep-alive connections, lets in-flight requests finish, runs the lifespan shutdown and exits. --timeout-graceful-shutdown caps the waiting; requests still running after it are cancelled.

Common misunderstanding: "Graceful shutdown waits as long as requests need." Without --timeout-graceful-shutdown Uvicorn waits indefinitely, and the orchestrator will SIGKILL it at the end of its grace period anyway, skipping the lifespan shutdown. With the timeout, the cancelled request does not get a clean answer: in the real run the client received 500 Internal Server Error and the log had Cancel 1 running task(s), timeout graceful shutdown exceeded followed by a CancelledError traceback.

Definition: Uvicorn's Server.shutdown() (0.39.0 source): log "Shutting down", close the servers and sockets ("Stop accepting new connections"), call shutdown() on every connection (idle ones close; busy ones get keep_alive = False so they close after the current response), wait for connections and tasks up to timeout_graceful_shutdown, cancel what is left, then send the lifespan shutdown event. Uvicorn captures SIGINT and SIGTERM and re-raises the captured signal after a clean shutdown, so a single-process Uvicorn exits with status 143 (128 + 15; Python's Popen reports -15) even when the shutdown was graceful; the multi-worker supervisor and Gunicorn's master exited with 0 in the real runs.

tools/shutdown_probe.py --slow 3 --term-after 1 -- uvicorn ... --timeout-graceful-shutdown 10   (real)
1  [client t= 0.665s] GET /work/slow?seconds=3.0 sent
2  [client t= 1.664s] SIGTERM sent to pid 80609
3  uvicorn.error  Shutting down
4  uvicorn.error  Waiting for connections to close. (CTRL+C to force quit)
5  [client t= 1.968s] new request after SIGTERM: ConnectError         <- listener closed
6  app.access     path=/work/slow status=200 duration_ms=3002.33
7  [client t= 3.669s] slow request finished: 200
8  app.lifespan   shutdown: closing http client, process pool and db pool
9  [client t= 3.709s] server exited with code -15
same with --slow 5 and --timeout-graceful-shutdown 2   (real)
10 [client t= 1.566s] SIGTERM sent
11 uvicorn.error  Cancel 1 running task(s), timeout graceful shutdown exceeded     (2.0 s later)
12 uvicorn.error  Exception in ASGI application ... CancelledError
13 [client t= 3.696s] slow request finished: 500 Internal Server Error
14 app.lifespan   shutdown complete

Real scenario: a payment callback in flight during a deploy completes because the drain waited for it; a WebSocket or SSE stream never "finishes", so the server needs the timeout and the client needs to reconnect (the Twelve-Factor text: "the client should seamlessly attempt to reconnect when the connection is lost"); a container whose CMD is shell form never sees SIGTERM, waits the full 10 s docker stop timeout and is killed; one important run detail: the probe's httpx client first went through the Mac's system proxy (httpx reads OS proxy settings) and received a 503 from the proxy after SIGTERM, which looked like a server answer until trust_env=False was set.

StepUvicorn single process (real)uvicorn --workers 2 (real)Gunicorn + UvicornWorker (real)
Signal receivedShutting down immediatelysupervisor Received SIGTERM, exiting. about 0.4 s laterHandling signal: term
New connection right after SIGTERMrefused (ConnectError)one request got 200 before the supervisor reactedrefused
In-flight requestsfinished (200)finished in both workers (200)finished (200)
Lifespan shutdownyesyes, in each workeryes, in each worker
Exit status143 (signal re-raised)00
Wait cap--timeout-graceful-shutdownsame, per workergraceful_timeout (30)

Rolling deploys, preStop and the grace period Important ​

In plain words: during a rolling deploy, an old pod is told to stop while traffic may still be routed to it for a moment. A short preStop sleep keeps it serving until load balancers have noticed, then SIGTERM starts the drain.

Common misunderstanding: "Readiness failing on shutdown is enough." Endpoint removal and SIGTERM happen in parallel; kube-proxy, ingress controllers and cloud load balancers update a little later, and Uvicorn closes its listener immediately on SIGTERM, so connections that arrive in that window are refused. The preStop sleep closes the window from the outside; a draining flag inside the app cannot, because the listener is already closed.

Definition: Kubernetes container hooks: "PreStop hooks are not executed asynchronously from the signal to stop the Container; the hook must complete its execution before the TERM signal can be sent", and the grace period "applies to the total time it takes for both the PreStop hook to execute and for the Container to stop normally" ("defaults to 30 seconds"). The sleep action runs in the kubelet, so the image needs no sleep binary. Budget: preStop + --timeout-graceful-shutdown + lifespan shutdown < terminationGracePeriodSeconds. Deployment strategy details (maxSurge, maxUnavailable, canaries) are in Deployment Strategies.

yaml
# Pod spec fragment for the image on this page (expected, not run: no cluster on the build machine)
spec:
  terminationGracePeriodSeconds: 30
  containers:
    - name: api
      image: registry.example.com/orders-api:1.4.2
      args: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000",
             "--timeout-graceful-shutdown", "20", "--proxy-headers", "--forwarded-allow-ips", "10.0.0.0/8"]
      lifecycle:
        preStop:
          sleep:
            seconds: 5            # 5 s preStop + 20 s drain + lifespan < 30 s
      env:
        - name: APP_ALLOWED_HOSTS
          value: '["api.example.com","localhost","127.0.0.1"]'
      readinessProbe:
        httpGet:
          path: /readyz
          port: 8000
          httpHeaders: [{name: Host, value: localhost}]   # default Host is the pod IP: TrustedHost would answer 400
        periodSeconds: 5
      livenessProbe:
        httpGet:
          path: /healthz
          port: 8000
          httpHeaders: [{name: Host, value: localhost}]
        periodSeconds: 10
      resources:
        requests: {cpu: "1", memory: 512Mi}
        limits: {memory: 512Mi}
Budget itemValueRule
preStop sleep5 sLonger than endpoint propagation
--timeout-graceful-shutdown / Gunicorn graceful_timeout20 s / 25 sLonger than the slowest normal request
Lifespan shutdown< 1 s (real: 2 ms)Close, do not flush big queues
terminationGracePeriodSeconds30 sGreater than the sum above
docker stop -t"10 seconds for Linux containers" (Docker CLI reference)Same budget for plain Docker

The production Docker image: multi-stage with uv, --no-dev, non-root, tini, exec form Must-know ​

In plain words: build in one stage (uv, caches, compilers), copy only the finished virtual environment and the code into a slim runtime stage, run as an unprivileged user, and start Uvicorn in exec form behind a tiny init so signals arrive and zombies are reaped.

Common misunderstanding: "CMD uvicorn app.main:app is the same as the JSON form." The shell form runs /bin/sh -c "uvicorn ..."; the Dockerfile reference says such a process "will not be the container's PID 1, and will not receive Unix signals. In this case, your executable doesn't receive a SIGTERM from docker stop". FastAPI's Docker page: "Make sure to always use the exec form to ensure that FastAPI can shutdown gracefully and lifespan events are triggered." Layers, caching and multi-arch builds are in Images & Dockerfiles; rootless and capabilities in Container Security.

Definition: the snippet's Dockerfile (read by tests/test_deploy_files.py; build expected, not run): builder python:3.12-slim with uv copied from ghcr.io/astral-sh/uv:0.13.10, UV_COMPILE_BYTECODE=1 (uv's Docker guide: compile to bytecode at install for faster startup), UV_LINK_MODE=copy, a cache mount, and uv sync --locked --no-install-project --no-dev with pyproject.toml and uv.lock bind-mounted, so the dependency layer is rebuilt only when the lock changes. The runtime stage installs tini, creates user app (uid 10001), sets PYTHONUNBUFFERED=1 (log lines reach stdout immediately) and PYTHONDONTWRITEBYTECODE=1 (no .pyc writes at runtime; UV_COMPILE_BYTECODE=1 compiled the installed packages in .venv at build time, while the copied app/ sources are compiled in memory at each start, which costs milliseconds for a small app), copies /app/.venv, app/ and conf/ with --chown, switches USER app, declares a HEALTHCHECK in exec form with the stdlib (no curl in the image), and uses ENTRYPOINT ["tini", "--"] with an exec-form CMD. Tini's README: "By default, Tini needs to run as PID 1 so that it can reap zombies"; docker run --init gives the same without installing it. Nothing secret is in an ENV or ARG (test test_no_secrets_baked_into_the_image).

docker build -t orders-api . && docker run --rm -p 8000:8000 -e APP_SECRET_KEY=... orders-api   (expected, not run)
1  [builder 3/4] RUN uv sync --locked --no-install-project --no-dev     <- cached until uv.lock changes
2  [runtime 4/6] COPY --from=builder --chown=app:app /app/.venv /app/.venv
3  docker exec <id> ps -o pid,user,args
4      1 app   tini -- uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 2 ...
5      7 app   uvicorn ... (supervisor)         8, 9 app   spawned workers
6  docker stop <id>   -> tini forwards SIGTERM -> "Shutting down" ... "Finished server process"
7  docker inspect --format '{{.State.Health.Status}}' <id>   -> healthy

Real scenario: an image built with pip install -r requirements.txt and COPY . . contains .git, .env and the test suite (the .dockerignore excludes .env, tests, *.db); a CMD in shell form makes every deploy take the full grace period and kill requests; running as root lets an RCE in a dependency write anywhere in the container; a missing PYTHONUNBUFFERED hides the last log lines before a crash.

LineWhyFailure without it
Multi-stage (AS builder, AS runtime)Build tools stay out of the final imageLarger image, more CVEs
uv sync --locked --no-devExactly the lock, no test toolsSurprise versions, pytest in prod
--no-install-project firstDependency layer cached separatelyEvery code change reinstalls everything
UV_COMPILE_BYTECODE=1.pyc built once at build timeSlower cold start in every worker
PYTHONUNBUFFERED=1Logs flushed immediatelyLost or delayed log lines
PYTHONDONTWRITEBYTECODE=1No .pyc writes into the container at runtime__pycache__ files written into the image's directories (CPython silently skips them when the filesystem is read-only)
USER app (non-root user)Least privilegeRoot inside the container
HEALTHCHECKDocker/Compose know the healthdepends_on cannot wait for "healthy"
ENTRYPOINT ["tini", "--"]Signal forwarding, zombie reaping as PID 1Zombies from ProcessPoolExecutor children
Exec-form CMD [...]Uvicorn receives SIGTERMNo graceful shutdown, no lifespan shutdown
.dockerignore with .envSecrets stay out of the build contextSecrets in images anti-pattern

Behind a reverse proxy: --proxy-headers, --forwarded-allow-ips, X-Forwarded-For, --root-path Must-know ​

In plain words: behind Nginx, Traefik or a cloud load balancer, the TCP peer is the proxy. The real client address and scheme arrive in X-Forwarded-For and X-Forwarded-Proto, and Uvicorn should believe those headers only when they come from the proxy's address.

Common misunderstanding: "--forwarded-allow-ips '*' is the easy fix." It lets any client that can reach the container set its own IP and scheme: rate limits by IP, audit logs and "only from the office" rules are then forgeable. Trust exactly the proxy's address or network.

Definition: Uvicorn: "--proxy-headers / --no-proxy-headers - Enable/Disable X-Forwarded-Proto, X-Forwarded-For to populate remote address info. Defaults to enabled, but is restricted to only trusting connecting IPs in the forwarded-allow-ips configuration", and --forwarded-allow-ips takes "IP Addresses, IP Networks, or literals" and defaults to $FORWARDED_ALLOW_IPS or 127.0.0.1 and ::1. --root-path /api sets the ASGI root_path when the proxy strips a prefix: FastAPI then advertises servers: [{"url": "/api"}] in OpenAPI and the docs page loads /api/openapi.json (real). The full proxy recipes (Traefik, root_path in FastAPI()) are in FastAPI's "Behind a Proxy" guide.

curl -H "X-Forwarded-For: 203.0.113.7" -H "X-Forwarded-Proto: https" http://127.0.0.1:PORT/info   (real)
1  default (--proxy-headers, trusts 127.0.0.1)   -> "client":"203.0.113.7","scheme":"https"
2  --forwarded-allow-ips 10.0.0.1                -> "client":"127.0.0.1","scheme":"http"   (headers ignored)
3  --root-path /api                              -> "root_path":"/api"; openapi servers [{'url': '/api'}]
4                                                   /docs loads url: '/api/openapi.json'

Real scenario: a rate limiter keyed on request.client.host sees one IP (the ingress) for all users until proxy headers are trusted; HTTPSRedirectMiddleware loops forever behind a TLS-terminating proxy because the scheme looks like http (fix: trust the proxy so X-Forwarded-Proto sets the scheme); the API is mounted at /api by the ingress and the docs page asks for /openapi.json at the root until --root-path /api is set.

SettingUvicornGunicornEffect
Honour forwarded headers--proxy-headers (default on)Uvicorn inside UvicornWorker does itclient, scheme from the headers
Who is trusted--forwarded-allow-ips / FORWARDED_ALLOW_IPSforwarded_allow_ips (passed to Uvicorn by uvicorn-worker 0.4.0)Default loopback only
Prefix stripped by proxy--root-path /apiSCRIPT_NAME envOpenAPI servers, docs URL, url_for
Server header--no-server-headern/aHide server: uvicorn
Max header size--h11-max-incomplete-event-sizelimit_request_field_sizeOversized headers rejected

Security middlewares: CORSMiddleware, TrustedHostMiddleware, HTTPSRedirectMiddleware, security headers, docs Important ​

In plain words: a few middlewares turn a working API into one that rejects forged host names, answers browsers' CORS checks only for your front-ends, redirects plain HTTP, sends the standard defensive headers and does not publish its full schema to the internet.

Common misunderstanding: "CORS protects the API." CORS only tells browsers which origins may read responses; curl and server-to-server callers ignore it. Authentication is still required. And "disabling /docs hides the API": it hides the interactive page and /openapi.json, not the endpoints.

Definition: TrustedHostMiddleware(allowed_hosts=[...]) answers 400 Invalid host header for other Host values (real; it defends against host-header attacks on password-reset links and cache poisoning); HTTPSRedirectMiddleware answers 307 to https:// (real test: location: https://testserver/healthz); CORSMiddleware(allow_origins=[...], allow_methods=..., allow_headers=..., expose_headers=["X-Request-ID"]) answers preflights (real: allowed origin 200 with access-control-allow-origin, other origin 400); GZipMiddleware(minimum_size=1000). The snippet's SecurityHeadersMiddleware is outermost, so even TrustedHost's 400 and the 500 carry X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer, a Content-Security-Policy for an API (default-src 'none'; frame-ancestors 'none', skipped on /docs and /redoc, whose Swagger UI page loads cdn.jsdelivr.net/npm/swagger-ui-dist@5 and runs an inline script that the strict policy would block; test test_strict_csp_everywhere_except_the_docs_pages), Cross-Origin-Opener-Policy, and Strict-Transport-Security in prod. The OWASP HTTP Headers Cheat Sheet recommends X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and Strict-Transport-Security: max-age=63072000; includeSubDomains; preload; an API that is never a referrer source can use the stricter no-referrer, and the snippet's one-year HSTS without preload is the cautious start before submitting a domain to the preload list. Docs: FastAPI(docs_url=None, redoc_url=None, openapi_url=None) in prod, that is docs_url None, redoc_url None and openapi_url None (real: 404 for all three); to protect /docs instead of removing it, serve the docs routes behind an auth dependency or only on an internal port.

Middleware / headerProtects againstSnippetReal result
TrustedHostMiddlewareHost-header injection, DNS rebindingallowed_hosts from settings400 Invalid host header
HTTPSRedirectMiddlewarePlain-HTTP accessAPP_HTTPS_REDIRECT=true307 to https://
CORSMiddlewareCross-origin reads in browsersAPP_CORS_ORIGINSpreflight 200 / 400
X-Content-Type-Options: nosniffMIME sniffingalwayspresent on 200, 400, 500
X-Frame-Options: DENY, frame-ancestors 'none'Clickjackingalwayspresent
Strict-Transport-SecurityDowngrade to HTTPprod onlymax-age=31536000; includeSubDomains
docs_url=None, openapi_url=NoneSchema disclosureprod404
X-Request-ID exposed via CORSFront-end can report the IDexpose_headersreadable by JS

Sync vs async endpoints, the threadpool and the AnyIO capacity limiter Must-know ​

One request: proxy, server, middleware stack, then loop, threads or processesReverse proxy / load balancerTLS, X-Forwarded-For, -ProtoUvicorn worker: accept (backlog), httptools on uvloop--limit-concurrency: 503 | --forwarded-allow-ips: trust headers | --timeout-keep-alive 5ASGI middleware stack (outermost first; last add_middleware is outermost)ServerErrorMiddleware (Starlette, always outermost): plain 500 if nothing else answeredSecurityHeadersMiddleware: nosniff, DENY, CSP, HSTS in prod (also on 400 and 500)RequestIDMiddleware: X-Request-ID, contextvar, JSON access line, own 500 with the IDTrustedHostMiddleware: 400 "Invalid host header" | HTTPSRedirect 307 | CORSMiddlewareGZipMiddleware(minimum_size=1000): 90,160 bytes became 15,513Prometheus instrumentator: http_requests_total, http_request_duration_secondsExceptionMiddleware: HTTPException and 422 handlersRouter: match path, solve dependencies, validate, call endpoint, serialise (ORJSONResponse)async def: event loopawait I/O, thousands in flight842 req/s at 100 users, 100 msdef: AnyIO thread poolrun_in_threadpool, 40 tokens355 req/s (cap 40 / 0.1 s = 400)CPU-bound: processesProcessPoolExecutor or workersblocking in async def: 9.6 req/s

In plain words: an async def endpoint runs on the event loop and must only await; a def endpoint runs in a thread from a pool of 40, so blocking calls are fine there but at most 40 run at once per worker; a blocking call inside async def freezes every request of that worker.

Common misunderstanding: "def endpoints are slow." They are bounded, not slow: with 100 users and 100 ms of blocking work, 40 tokens gave 355.3 req/s (the ceiling is 40 / 0.1 s = 400) and raising the limiter to 100 tokens gave 811.0 req/s, close to the async def version's 842.0. The real disaster is the third row below: time.sleep inside async def served 9.6 req/s with only 10 users.

Definition: FastAPI calls def endpoints and def dependencies through Starlette's run_in_threadpool, which is anyio.to_thread.run_sync. AnyIO: "The default AnyIO worker thread limiter has a value of 40, meaning that any calls to to_thread.run_sync() without an explicit limiter argument will cause a maximum of 40 threads to be spawned." Starlette's thread-pool page adds that the limit "is shared with other libraries: for example FastAPI also uses anyio to run sync dependencies", and shows limiter.total_tokens = 100, warning that more threads "may have a performance and memory impact". The limiter is per event loop, so it is set inside the lifespan (the snippet's APP_THREADPOOL_TOKENS), and each worker has its own. A CapacityLimiter(n) can also be passed to to_thread.run_sync(fn, limiter=...) to give one kind of call its own budget. The event-loop side (await, asyncio.to_thread, why blocking hurts) is in Async Python.

one worker, 100 concurrent users, 100 ms per request (runs/sync-vs-async.txt, real)
1  /work/async?ms=100     async def + await asyncio.sleep   842.0 req/s   p50 112.9  p99 165.3 ms
2  /work/sync?ms=100      def + time.sleep, 40 tokens       355.3 req/s   p50 246.4  p99 481.7 ms
3  /work/sync?ms=100      def + time.sleep, 100 tokens      811.0 req/s   p50 110.2  p99 179.8 ms
4  /work/blocking?ms=100  async def + time.sleep (10 users)   9.6 req/s   p50 942.2  p99 1888.6 ms
One worker, 100 ms of waiting per request: requests per second (p50 / p99)async def + await (100 users)842 (113 / 165 ms)def, 40 thread tokens (100 users)355 (246 / 482 ms), ceiling 40 / 0.1 s = 400def, 100 thread tokens (100 users)811 (110 / 180 ms)time.sleep in async def (10 users)9.6 (942 / 1889 ms): the loop is blockedscale: 100 px = 200 req/s | runs/sync-vs-async.txt, uvicorn 0.39.0, CPython 3.9.6, 12-core arm64

Real scenario: a def endpoint calls a payment API that takes 2 s at peak; 40 of them occupy every thread and /readyz (also def) starts timing out, which is the right signal; an async def endpoint uses the sync boto3 client and the whole worker stalls (use run_in_threadpool/asyncio.to_thread, or the async client); a team raises tokens to 1,000 and memory doubles while the database pool (5 + 5) is now the queue.

Endpoint styleRuns onConcurrency per workerBlocking call insideUse for
async def + awaitevent loopthousandsfreezes the workerasync drivers (httpx.AsyncClient, asyncpg, AsyncSession)
defAnyIO thread pooltotal_tokens (40)fine, holds a threadsync drivers, sync SDKs, SQLAlchemy Session
async def + await run_in_threadpool(fn)thread pool from async codesame 40 tokensfineone sync call inside an async route
async def + run_in_executor(process_pool, fn)other processespool sizen/aCPU-bound work
def dependencythread poolsame tokensfinecounts against the same 40

Server knobs: uvloop, httptools, keep-alive, --limit-concurrency, --backlog, timeouts Important ​

In plain words: Uvicorn has a handful of settings that decide how connections are handled before your code runs: which event loop and parser, how long idle connections stay open, how many connections or tasks it accepts before answering 503, and how many unaccepted connections the kernel may queue.

Common misunderstanding: "--limit-concurrency is a request queue." It is not: "excess requests receive an immediate 503, they are not queued", and it counts connections as well as tasks. In the real run with --limit-concurrency 10 and 40 keep-alive users, 387 of 400 answers were 503 (Exceeded concurrency limit. in uvicorn.error), because 40 open connections were already over the limit.

Definition: --loop auto|asyncio|uvloop (uvloop's README: "uvloop is a fast, drop-in replacement of the built-in asyncio event loop" and "uvloop makes asyncio 2-4x faster"; not on Windows or PyPy); --http auto|h11|httptools (httptools wraps the C llhttp parser; the real 500 response above shows transfer-encoding: chunked chosen by Uvicorn because the app sent no Content-Length); --timeout-keep-alive (default 5 s: "Close Keep-Alive connections if no new data is received within this timeout"; behind a load balancer that pools connections, set it longer than the balancer's idle timeout so the balancer, not the server, closes idle connections and never reuses one the server just closed); --limit-concurrency; --backlog (default 2048: "Maximum number of connections to hold in the TCP accept queue, passed to the socket's listen() call"); --timeout-graceful-shutdown; --limit-max-requests; --h11-max-incomplete-event-size. Current Uvicorn adds --http2 with the experimental zttp parser and zuvloop for 3.14+; neither is in 0.39.0.

--limit-concurrency 10, 40 users, GET /work/async?ms=200 (runs/limit-concurrency.txt, real)
1  {"statuses": {"503": 387, "200": 13}, "p50_ms": 20.4, "p99_ms": 217.2}
2  uvicorn.error  WARNING  Exceeded concurrency limit.     (one line per rejected request)

Real scenario: a pod with a 512 MiB limit uses --limit-concurrency 200 so a traffic spike becomes fast 503s (the load balancer retries elsewhere) instead of an OOM kill; an AWS ALB with a 60 s idle timeout in front of Uvicorn's 5 s keep-alive produces sporadic 502s when Uvicorn closes a connection the ALB just reused (raise --timeout-keep-alive to 65); a SYN flood fills the backlog and new clients time out at the TCP level, before any app code runs.

KnobDefault (0.39)Raise whenLower when
--loopauto (uvloop if installed)n/aasyncio to debug loop issues
--httpauto (httptools if installed)n/ah11 on PyPy
--timeout-keep-alive5 sLB idle timeout is longer and reuses connectionsmany idle clients hold memory
--limit-concurrencynonen/aprotect memory; fail fast with 503
--backlog2048bursts of new connectionsrarely
--timeout-graceful-shutdownnone (wait forever)long requeststo fit the grace period
--limit-max-requestsnoneslow memory growthn/a
--workers$WEB_CONCURRENCY or 1CPU-bound load, cores availablememory or DB connections are short

Response cost: GZipMiddleware, ORJSONResponse, validation cost, StreamingResponse Important ​

In plain words: for large responses, the time goes into turning Python objects into bytes (validation, encoding, compression), not into the route. Know which of those you pay for and pick the cheap path deliberately.

Common misunderstanding: "ORJSONResponse is always the fastest." On FastAPI 0.130.0+ a declared return type or response_model is serialised by Pydantic in Rust directly, and ORJSONResponse is deprecated since 0.131.0. On the pinned 0.128.8, orjson on plain dicts was fastest in the real measurement, but that skips validation entirely.

Definition: the real numbers for 2,000 small objects (tools/serialization_cost.py, best of 5 × 50 runs): stdlib json.dumps(jsonable_encoder(items)) 8.18 ms, orjson.dumps(items) 0.09 ms, Pydantic TypeAdapter(List[Item]).validate_python + dump_json 0.93 ms. A cProfile of 20 requests to /work/big through the whole app (same thread via httpx.ASGITransport) put zlib.Compress.compress first (23 ms of 64 ms total; httpx asks for gzip by default), then Pydantic's SchemaSerializer.to_python (14 ms), the route's list comprehension (7 ms) and orjson.dumps (4 ms). GZipMiddleware(minimum_size=1000) shrank that body from 90,160 to 15,513 bytes (real curl) at that CPU price; small responses are not compressed (minimum_size, default 500 in Starlette). StreamingResponse sends chunks as they are produced (chunked transfer encoding, constant memory); the snippet's NDJSON stream is tested, and the full treatment is in Exceptions & Responses.

python tools/serialization_cost.py --profile   (real, top of "tottime")
1  ncalls  tottime  function
2      20    0.023  {method 'compress' of 'zlib.Compress' objects}          <- GZipMiddleware
3      20    0.014  {method 'to_python' of 'pydantic_core...SchemaSerializer'}
4      20    0.007  app/work.py:82(<listcomp>)                              <- building the data
5      20    0.004  {orjson.dumps}

Real scenario: a list endpoint returning 10,000 rows spends more CPU in gzip than in the database (compress at the proxy, or lower compresslevel, or paginate); a response_model with nested models doubles latency on 0.128 and costs little on 0.130+; an export endpoint builds a 200 MB list in memory and the pod is OOM-killed (stream it); a team adds ORJSONResponse everywhere on 0.165 and gets deprecation warnings for no gain.

ChoiceCost (real, 2,000 objects)Validates outputStatus on current FastAPI
JSONResponse after jsonable_encoder8.18 msnodefault without a return type
ORJSONResponse0.09 msnodeprecated since 0.131.0
response_model / return type0.93 ms (Pydantic validate + dump)yesserialised by Pydantic in Rust since 0.130.0
GZipMiddleware~1.15 ms per 90 KB body (profile)n/astable; consider the proxy instead
StreamingResponseper chunknostable; constant memory

CPU-bound work and processes: ProcessPoolExecutor Important ​

In plain words: threads do not make Python code run on more cores; processes do. Either more workers (each request on its own core) or a process pool inside the worker for the heavy part.

Common misunderstanding: "A def endpoint runs CPU work in parallel because it uses threads." The real run: /work/cpu (21 ms of pure Python) in one worker served 49.3 req/s with 16 users whether it ran in the thread pool or not; moving the same function to a 2-process ProcessPoolExecutor from an async def endpoint doubled it to 104.7 req/s with a flat p99 (158.4 ms vs 448.2 ms).

Definition: loop.run_in_executor(app.state.process_pool, burn, n); the function and its arguments are pickled and sent to a child process (spawn on macOS and Windows; on Linux the default start method depends on the Python version), so they must be top-level and picklable, and the result is pickled back. The pool is created in the lifespan and shut down there. For heavy or long jobs, a task queue (Celery, arq, RQ, Dramatiq) with separate worker containers is usually better than a pool inside the web worker. The general treatment is in Async Python.

Approach (one web worker, 16 users, real)req/sp50p99
def endpoint, CPU in the thread pool49.3331.7 ms448.2 ms
async def + ProcessPoolExecutor(max_workers=2)104.7152.3 ms158.4 ms
4 web workers, CPU in each (from Worker processes)184.152.2 ms248.9 ms

Measuring: load testing, p50/p99, throughput, py-spy, cProfile Must-know ​

In plain words: run a load generator with a fixed number of concurrent users against a real server, read throughput and the latency percentiles, change one thing, run again. Then profile to see where the time goes.

Common misunderstanding: "My load tool measures the server." It measures the server and itself. The first version of the snippet's tool shared one httpx.AsyncClient between all users; against the same server and endpoint it reported 222.5 req/s with p99 1,047.5 ms, while ab -k reported 1,343.1 req/s with p99 33 ms. With one client (one keep-alive connection) per virtual user it reported 1,340.4 req/s, p99 32.9 ms, matching ab. At 100 users the Python tool topped out at 1,968.6 req/s while ab reached 3,675.2: above roughly 2,000 req/s the Python client is the bottleneck on this machine, so the comparisons on this page stay below that.

Definition: a closed-loop tool (loadtool/load.py) keeps -c users busy, each sending its next request when the previous one returns; throughput = completed requests / elapsed time; p50 and p99 are nearest-rank percentiles of per-request latency (tested). Open-loop tools (k6 with arrival-rate executors, wrk2, Vegeta) send at a fixed rate instead and show queueing honestly when the server falls behind; hey, wrk, ab, Locust and k6 are the common choices. Profilers: cProfile (deterministic, in the standard library, profiles only the thread it runs in; the first profile attempt through TestClient showed nothing because TestClient runs the app in another thread) and py-spy (sampling, attaches to a running process: "without restarting the program or modifying the code in any way", py-spy top --pid, py-spy record -o profile.svg --pid, --subprocesses for workers; in a container it needs SYS_PTRACE). py-spy was not installed on the build machine.

one uvicorn worker, GET /work/async?ms=20 (runs/loadtool-calibration.txt, real)
1  32 users  shared httpx pool      222.5 req/s   p50 46.8 ms  p99 1047.5 ms   <- client bottleneck
2  32 users  one client per user   1340.4 req/s   p50 22.9 ms  p99   32.9 ms
3  32 users  ab -k                 1343.1 req/s   p50 24   ms  p99   33   ms
4  100 users one client per user   1968.6 req/s   p50 48.1 ms  p99   80.1 ms   <- Python client saturates
5  100 users ab -k                 3675.2 req/s   p50 26   ms  p99   39   ms
ToolModelGood forNote
loadtool/load.py (snippet)closed loop, httpxper-PID counts, quick A/Bclient-bound above ~2,000 req/s here
ab -kclosed loop, Csanity check of the toolHTTP/1.0 + keep-alive only
hey, wrkclosed loophigh rates, scripting (wrk Lua)not installed here
k6, wrk2, Vegetaopen loop / arrival raterealistic queueing, SLO teststhe honest p99 under overload
LocustPython usersuser flowsheavier per request
cProfiledeterministic profilerone code path in-processsame thread only
py-spysampling profilerproduction processes--subprocesses, SYS_PTRACE

Metrics and tracing: Prometheus, prometheus-fastapi-instrumentator, OpenTelemetry Important ​

In plain words: expose counters and histograms at /metrics for Prometheus to scrape, and (optionally) emit traces with OpenTelemetry. Both need care with multiple worker processes.

Common misunderstanding: "/metrics shows the whole service." Without multiprocess mode it shows the worker that happened to answer. Real run with 2 workers: the load spread 152 / 48 requests, and all 12 scrapes of /metrics returned http_requests_total{handler="/work/async",...} 153.0 from the same worker; the other worker's 48 requests were invisible. The Prometheus Python client says why: client libraries "presume a threaded model, where metrics are shared across workers. This doesn't work so well for languages such as Python", and its multiprocess mode needs PROMETHEUS_MULTIPROC_DIR set to a directory shared by the workers (prometheus-fastapi-instrumentator 7.1.0's /metrics handler switches to a MultiProcessCollector when the variable is set; read in its installed source).

Definition: Instrumentator(excluded_handlers=[...]).instrument(app).expose(app, endpoint="/metrics", include_in_schema=False) adds a middleware that records http_requests_total (labels handler, method, status as 2xx/4xx/5xx) and http_request_duration_seconds histograms; the handler label is the route template, not the raw path, so cardinality stays bounded. A second gotcha found by the tests: the default registry is process-wide, and a second app instrumented in the same process silently records nothing (the duplicate metrics are swallowed), which is why the test fixture passes metrics_registry=CollectorRegistry(). Keep /metrics off the public ingress. OpenTelemetry: FastAPIInstrumentor.instrument_app(app) from opentelemetry-instrumentation-fastapi, or zero-code opentelemetry-instrument uvicorn app.main:app after opentelemetry-bootstrap; with workers, initialise the SDK per worker (in the lifespan or a post-fork hook), not in the master. Concepts (RED metrics, sampling, exemplars) are in Observability.

ConcernSingle process--workers N / Gunicorn
Counter valuescorrectper worker, scrape sees one (real)
Fixnone neededPROMETHEUS_MULTIPROC_DIR, or one worker per pod and scrape every pod
Gauges in multiprocess moden/aneed a multiprocess_mode (livesum, max, ...)
Recycled workern/aits files stay in the directory; clean on startup
OpenTelemetry SDKinit in lifespaninit per worker, after fork

Configuration anti-patterns: os.environ everywhere, secrets in images Must-know ​

In plain words: two habits cause most configuration incidents: reading os.environ all over the code, and putting secrets where they outlive their purpose (images, Git, logs).

Common misunderstanding: "Secrets in a private image are safe." Every layer is stored and pulled in full; an ENV SECRET=... or a copied .env is readable by anyone who can pull the image, forever, even if a later layer deletes it. The Twelve-Factor litmus test: could the codebase "be made open source at any moment, without compromising any credentials"?

Definition: the Before app shows the first habit: strings read at import, bool("false") is True, defaults that hide a missing secret. The second: COPY . . with a .env, ARG/ENV with credentials, secrets printed in a startup log, secrets passed as command-line arguments (visible in ps). The fix is one Settings class, SecretStr, runtime injection (environment from a secret store, or files under secrets_dir), .dockerignore, and a startup validator that rejects development values in prod.

Anti-patternSymptomFix on this page
os.environ.get in many modulesTypos, strings, untestableOne Settings, get_settings()
Config read at import timeTests need importlib.reload (see test_before.py)create_app(settings) factory
bool(os.environ["DEBUG"])"false" is trueTyped bool field
Silent default for a secretProd runs with changememodel_validator fails fast
.env or ENV SECRET in the imageSecret in every pull.dockerignore, runtime env or files
Secret in logs or responsesLeak to log storeSecretStr, never get_secret_value() in logs
One settings class per environmentProd runs with staging defaultsOne class, env field, overrides by env vars

Mechanics ​

What happens from uvicorn --workers 2 to the first response Important ​

From the Uvicorn 0.39.0 source (server.py, supervisors/multiprocess.py, protocols/http/httptools_impl.py, saved) and the real logs:

1  supervisor: parse CLI, bind 127.0.0.1:PORT once (shared socket), log "Uvicorn running on ..."
2  supervisor: "Started parent process [1172]", spawn 2 children with the socket
3  each child: import app.main (create_app() runs: settings validated, middleware stack built)
4  each child: new event loop (uvloop), lifespan.startup -> our lifespan before yield
5  each child: "Application startup complete."; start serving on the inherited socket
6  kernel: hands a new connection to whichever child accepts first
7  child: httptools parses the request; limit-concurrency check (503 if exceeded)
8  child: proxy headers applied if the peer is in forwarded-allow-ips; scope built (root_path, client, scheme)
9  child: create a task, call app(scope, receive, send): middleware stack -> router -> endpoint
10 child: send() writes headers and body; keep-alive timer starts; access log (uvicorn.access) if on

What SIGTERM does in each process manager Must-know ​

uvicorn (single)   handle_exit -> should_exit -> shutdown(): close listeners, connection.shutdown() each,
                   sleep 0.1, wait for connections/tasks (<= timeout_graceful_shutdown), cancel the rest,
                   lifespan.shutdown, then signal.raise_signal(SIGTERM) -> exit status 143
uvicorn --workers  supervisor: "Received SIGTERM, exiting." -> "Terminated child process [..]" (SIGTERM to each)
                   -> each child runs the single-process sequence -> "Stopping parent process" -> exit 0
gunicorn           master "Handling signal: term" -> SIGTERM to workers -> each UvicornWorker drains
                   (graceful_timeout) -> master reaps ("Worker (pid:..) was sent SIGTERM!") -> "Shutting down: Master"

Exact messages and what they mean Must-know ​

Every line below was printed by the runs on this page.

MessageLogger / sourceMeaningAction
Waiting for connections to close. (CTRL+C to force quit)uvicorn.errorDraining in-flight requests after SIGTERMNormal
Cancel 1 running task(s), timeout graceful shutdown exceededuvicorn.error--timeout-graceful-shutdown passed; clients get 500Raise the timeout or shorten requests
Exceeded concurrency limit.uvicorn.error WARNING--limit-concurrency reached; 503 sentExpected under overload
Maximum request limit of 50 exceeded. Terminating process.uvicorn.error WARNINGRecycling via max_requests / --limit-max-requestsAdd jitter
Worker (pid:1164) was sent SIGTERM!gunicorn.error ERRORNormal stop in Gunicorn 23, logged at ERRORDo not alert on it
Reason: Worker failed to boot.gunicorn.errorImport or startup failed in every worker; master exits 3Read the traceback above it
Child process [2793] dieduvicorn.errorSupervisor respawning a crashed workerCrash loop if repeated
Invalid host header (400)TrustedHostMiddlewareHost not in allowed_hostsAdd the host or block the client
QueuePool limit of size 5 overflow 5 reached, connection timed out, timeout 0.50SQLAlchemyPool exhausted for pool_timeoutFewer concurrent checkouts or a bigger pool within the budget
Value error, APP_SECRET_KEY must be set in prodpydantic ValidationErrorFail-fast validatorSet the secret
"workers" flag is ignored when reloading is enabled.Uvicorn (under fastapi dev)Reload on and workers > 1 (here from WEB_CONCURRENCY=2)Use fastapi run or unset WEB_CONCURRENCY

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Requests fail during deploysGraceful shutdownexec-form CMD, tini, --timeout-graceful-shutdown, preStop sleepNo dropped requestsLonger pod termination
One slow endpoint stalls everythingFix blocking in async defdef or run_in_threadpool or async clientLoop stays freeThread-pool budget
Too many DB connectionsPool budgetworkers × (size + overflow) × replicas × surge < max_connectionsPredictableMay need PgBouncer
Logs cannot be searched per requestRequest ID + JSONpure ASGI middleware, ContextVar, filterOne query per incidentSmall code
Bad config found in production trafficFail fasttyped Settings, validators, import-time create_app()Pod never becomes readyStrictness needs tests
Pods restarted during DB outageSplit probes/healthz vs /readyzNo restart stormsTwo endpoints
Slow memory growthRecyclingmax_requests + jitterBounded RSSCold workers, connection resets
Wrong client IP / schemeTrust the proxy--forwarded-allow-ips <proxy CIDR>Correct IPs, redirectsMust know the proxy network
Metrics undercountMultiprocess mode or 1 worker/podPROMETHEUS_MULTIPROC_DIRCorrect totalsDirectory management

Deploys without failed requests ​

Exec-form CMD behind tini so SIGTERM reaches Uvicorn; --timeout-graceful-shutdown shorter than the grace period; a preStop sleep so load balancers stop routing first; readiness that reflects dependencies; at least two replicas and maxUnavailable: 0. The shutdown probe on this page is the test: an in-flight request must end with 200 and new connections must be refused only after the drain began.

Throughput you can explain ​

Start from the process model: CPU-bound → more processes (workers or a process pool); I/O-bound → async def with async drivers, or def with enough thread tokens; then measure with a tool that is not the bottleneck (calibrate it against ab or wrk once), watch p99 not only the mean, and profile the slow path (py-spy on the live worker, cProfile in-process).

Configuration that cannot be wrong at runtime ​

One Settings class, env_prefix, SecretStr, a Literal environment field, cross-field validators, @lru_cache accessor, a factory that takes settings for tests, secrets injected at runtime, .env only for laptops and excluded from images.

Choosing ​

SituationRecommendationExtra techniqueReason
Kubernetes, HPA on CPUuvicorn with 1 worker per container (FastAPI docs: "a single (Uvicorn) process per container")Scale replicas; requests.cpu: 1The orchestrator already replicates, restarts and load-balances
One VM or a container with several coresuvicorn --workers N or fastapi run --workers NN = usable cores; budget the poolUses all cores, simple
Need hooks, heartbeat timeout, recycling, loud boot failuresGunicorn + uvicorn_worker.UvicornWorkermax_requests + jitter, graceful_timeoutMature process management
Want no Uvicorn dependency, Gunicorn 24+Gunicorn --worker-class asgiTest it: beta in 24.0.0One server for WSGI and ASGI apps
CPU-heavy endpointsMore workers, or ProcessPoolExecutor, or a task queueMeasure p99One GIL per process
Many slow upstream callsasync def + httpx.AsyncClient from the lifespanTimeouts, limitsThousands of waits per worker
Sync-only SDKdef endpointRaise total_tokens with careThreads are cheaper than rewriting
Spiky traffic, tight memory--limit-concurrency + several replicasLoad balancer retries on 503Fast rejection beats OOM
Long requests, streams--timeout-graceful-shutdown + reconnecting clientsStreamingResponse, SSE retryShutdown cannot wait forever

How many workers ​

EnvironmentFormulaExample
Kubernetes pod with limits.cpu: 21–2 workers, or 1 worker and 2 replicas1 worker, scale out
VM with 8 cores, I/O-bound API2–4 workers (more only if CPU is high)--workers 4
VM with 8 cores, CPU-bound APIabout one per core--workers 8
Gunicorn sync (WSGI) workersGunicorn's guide: (2 × CPU cores) + 117 for 8 cores; not for async workers
Memory-bound (big models in RAM)RAM / RSS per worker4 GiB / 900 MiB → 4

Python has no GOMAXPROCS: os.cpu_count() returns the host's cores, not the container's CPU limit, so derive the worker count from the limit you set (WEB_CONCURRENCY in the manifest) rather than from the machine. A leaked WEB_CONCURRENCY also changes plain uvicorn (it is Uvicorn's default for --workers): during this chapter's runs a variable exported for a Gunicorn test turned a later single-process uvicorn into a 2-worker supervisor.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app, one PostgreSQL. In a container on a VM: uvicorn --workers 4, pool 5 + 5 per worker (40 connections), JSON logs to stdout collected by the Docker log driver, /healthz for Docker's HEALTHCHECK, Nginx in front with --forwarded-allow-ips set to Nginx's address. Deploys: docker compose up -d replaces the container; with a single instance there is a gap, so either accept it, run two containers behind Nginx and restart them one at a time, or use Gunicorn's HUP/Uvicorn's SIGHUP worker restart for code-only changes.

Modular monolith and multiple databases ​

Several modules in one app, perhaps an orders database and a reporting database. Each engine is created in the lifespan with its own pool and its own budget; /readyz checks only what the app cannot serve without (the orders database), while the reporting database's failure degrades one router. Settings grow nested sections (APP_ORDERS_DB__URL with env_nested_delimiter="__"). One image, one process model; the modules share the thread pool and the worker count, so a CPU-heavy reporting module can starve the orders module, which is the first argument for splitting it out.

Microservices ​

Each service is its own image with the same production skeleton (settings, logging, request IDs, probes, metrics). What must survive service boundaries: the correlation ID (forward X-Request-ID or W3C traceparent on every outgoing httpx call), timeouts (each hop's timeout shorter than its caller's), and graceful shutdown (a caller retrying an idempotent request on ConnectError during the callee's deploy). Example flow: gateway sets X-Request-ID: 7f3a… → orders service logs it and calls payments with the same header → payments logs it; one search shows the whole path. Each service runs one Uvicorn worker per pod and scales on its own CPU metric.

Distributed data: replicas, caches, multi-region ​

Read replicas get their own engine and pool (budget them too); readiness should not fail because a replica lags, only because the primary is unreachable. A Redis cache client lives in the lifespan like the engine (Background Tasks, Caching & External APIs). Connection poolers (PgBouncer, RDS Proxy) between many workers and the database change the budget arithmetic and the failure modes (transaction pooling and session state). Multi-region: settings per region from the environment, one image; health checks per region feed the global load balancer, and the shutdown/drain rules apply to regional failovers as much as to deploys.

Scaling path: 1×, 10×, 100× ​

  • 1×: one container, --workers 2, SQLite or one PostgreSQL, logs to stdout. Measure once with the load tool so you know the ceiling.
  • 10×: Kubernetes, one worker per pod, HPA on CPU, pool budget computed with surge, preStop + graceful timeout, Prometheus scraping every pod, JSON logs with request IDs into a log store, PgBouncer when replicas × pool approaches max_connections.
  • 100×: the database and upstreams are the limit, not Uvicorn: caching, read replicas, async drivers end to end, CPU-heavy work moved to task queues, open-loop load tests against SLOs (p99), profiling with py-spy in production, and capacity planning per worker from measured req/s and RSS.

Lab ​

All steps ran on the build machine (CPython 3.9.6, the venv outside docs/); the Docker step is expected, not run. Use free ports; kill every server you start by its PID.

1. Install and run the tests (real) ​

bash
cd docs/snippets/python/fastapi-production-uvicorn
export UV_PROJECT_ENVIRONMENT=/tmp/orders-api-venv     # keep the venv out of the repository
uv sync --locked
uv run pytest
# ............................................................             [100%]
# 62 passed in 2.01s

2. One worker vs four on CPU-bound work (real) ​

bash
uvicorn app.main:app --port 18741 --workers 1 --no-access-log --log-config conf/log-config.json & PID=$!
python -m loadtool.load "http://127.0.0.1:18741/work/cpu?n=600000" -c 16 -n 600
# {"rps": 47.9, "p50_ms": 333.1, "p99_ms": 493.5, "pids": {"82875": 600}}
kill -TERM $PID
uvicorn app.main:app --port 18742 --workers 4 --no-access-log --log-config conf/log-config.json & PID=$!
python -m loadtool.load "http://127.0.0.1:18742/work/cpu?n=600000" -c 16 -n 600
# {"rps": 184.1, "p50_ms": 52.2, "p99_ms": 248.9, "pids": {"85589": 150, "85590": 150, "85592": 149, "85591": 151}}
kill -TERM $PID

3. Sync vs async vs blocking (real) ​

bash
uvicorn app.main:app --port 18744 --no-access-log --log-config conf/log-config.json & PID=$!
python -m loadtool.load "http://127.0.0.1:18744/work/async?ms=100" -c 100 -n 2000    # rps 842.0, p99 165.3
python -m loadtool.load "http://127.0.0.1:18744/work/sync?ms=100" -c 100 -n 1000     # rps 355.3, p99 481.7
python -m loadtool.load "http://127.0.0.1:18744/work/blocking?ms=100" -c 10 -n 50    # rps 9.6,   p99 1888.6
kill -TERM $PID
APP_THREADPOOL_TOKENS=100 uvicorn app.main:app --port 18745 --no-access-log --log-config conf/log-config.json & PID=$!
python -m loadtool.load "http://127.0.0.1:18745/work/sync?ms=100" -c 100 -n 1000     # rps 811.0, p99 179.8
kill -TERM $PID

4. Graceful shutdown with a request in flight (real) ​

bash
python tools/shutdown_probe.py --port 18751 --slow 3 --term-after 1 -- \
  uvicorn app.main:app --port 18751 --log-config conf/log-config.json --no-access-log --timeout-graceful-shutdown 10
# [client t= 1.664s] SIGTERM sent to pid 80609
# [client t= 1.968s] new request after SIGTERM: ConnectError
# [client t= 3.669s] slow request finished: 200 {"kind":"slow","seconds":3.0,"pid":80609}
# [client t= 3.709s] server exited with code -15
python tools/shutdown_probe.py --port 18752 --slow 5 --term-after 1 -- \
  uvicorn app.main:app --port 18752 --log-config conf/log-config.json --no-access-log --timeout-graceful-shutdown 2
# {"level": "ERROR", "logger": "uvicorn.error", "msg": "Cancel 1 running task(s), timeout graceful shutdown exceeded"}
# [client t= 3.696s] slow request finished: 500 Internal Server Error

5. Gunicorn: recycling and SIGTERM (real) ​

bash
GUNICORN_BIND=127.0.0.1:18754 GUNICORN_MAX_REQUESTS=50 GUNICORN_MAX_REQUESTS_JITTER=0 WEB_CONCURRENCY=2 \
  gunicorn -c conf/gunicorn.conf.py app.main:app & PID=$!
python -m loadtool.load "http://127.0.0.1:18754/work/async?ms=5" -c 4 -n 300 --warmup 0
# {"requests": 295, "p99_ms": 577.3, "errors": {"ReadError": 5}, "pids": {"1064": 84, "1068": 69, "1108": 62, "1113": 78, "1134": 2}}
kill -TERM $PID
# (unset GUNICORN_* and WEB_CONCURRENCY afterwards: uvicorn reads WEB_CONCURRENCY too)

6. Configuration fails fast (real) ​

bash
APP_ENV=prod uvicorn app.main:app --port 18760; echo "exit $?"
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
#   Value error, APP_SECRET_KEY must be set in prod [type=value_error, ...]
# exit 1
APP_ENV=prod APP_SECRET_KEY=prod-secret-from-vault uvicorn app.main:app --port 18762 --log-level warning & PID=$!
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:18762/docs        # 404
curl -si http://127.0.0.1:18762/info | grep -i strict                        # strict-transport-security: max-age=31536000; includeSubDomains
kill -TERM $PID

7. Build and run the image (expected, not run) ​

bash
docker build -t orders-api:dev .
docker run --rm -p 8000:8000 -e APP_SECRET_KEY=dev-secret -e APP_ALLOWED_HOSTS='["localhost","127.0.0.1"]' orders-api:dev
# (127.0.0.1 must stay allowed: the HEALTHCHECK calls http://127.0.0.1:8000/healthz)
# {"logger": "uvicorn.error", "msg": "Started parent process [7]", ...}
docker exec <container> ps -o pid,user,args        # PID 1 is tini, user app
time docker stop <container>                      # well under the 10 s default: SIGTERM reached uvicorn

For PHP/Laravel developers ​

Classic PHP-FPM is a pre-fork process manager like Gunicorn, sized by PHP-FPM pm.max_children: a master and a pool of children, each serving one request at a time and forgetting everything afterwards. The PHP manual: with pm = static "the number of child processes is fixed (pm.max_children)", and pm.max_requests recycles children like max_requests. Laravel Octane is the closer analogue of Uvicorn workers: "Octane boots your application once, keeps it in memory, and then feeds it requests", on FrankenPHP (a Go-based server), Swoole/Open Swoole or RoadRunner, with php artisan octane:start --workers=4 and recycling: "Octane gracefully restarts any worker once it has handled 500 requests" (--max-requests). The same consequences follow as in Python: state lives per worker, singletons leak across requests if you are careless, and the worker count multiplies database connections. Configuration: Laravel reads .env and APP_ENV; in production you run php artisan config:cache, after which, the deployment docs warn, "the .env file will not be loaded and all calls to the env function for .env variables will return null" (the equivalent of reading settings once through get_settings()). php artisan down (maintenance mode) answers 503 for everything, which is a blunt version of a failing readiness probe. Horizon supervises queue workers, the job the task-queue row of Choosing gives to Celery or arq.

php
<?php
// config/octane.php excerpt + deploy steps, side by side with the Python setup (illustrative)
return [
    // Octane's documented default: requests are cut after 30 s (compare --timeout-graceful-shutdown)
    'max_execution_time' => 30,
];
// Deploy (Dockerfile RUN / entrypoint):
//   composer install --no-dev                            ~ uv sync --locked --no-dev
//   php artisan config:cache && php artisan route:cache  ~ Settings validated once, cached
//   php artisan octane:start --server=frankenphp --workers=4 --max-requests=500
//                                                         ~ gunicorn -w 4 --max-requests 500
ConcernLaravelFastAPI on this page
Process managerPHP-FPM (pm.max_children) or OctaneUvicorn supervisor or Gunicorn
App kept in memoryOctane onlyalways (each worker)
Worker recyclingpm.max_requests, Octane --max-requests (500 default)max_requests + jitter, --limit-max-requests
Config cachingconfig:cache (then env() returns null outside config)@lru_cache get_settings()
Environment nameAPP_ENVAPP_ENV (Literal["dev","staging","prod"])
Maintenancephp artisan downreadiness 503, or drain via preStop
Queue workersHorizonCelery / arq / RQ workers (separate containers)

The Go angle ​

Go needs no external server or process manager: one net/http process uses every core through goroutines, so the "workers" question becomes GOMAXPROCS, and since Go 1.25 the runtime reads the container's CPU limit: "If a Go process is running inside a container with a CPU limit, GOMAXPROCS will default to the CPU limit if it is less than the core count", and it re-checks periodically. Timeouts live on http.Server (ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, the last being keep-alive); an http.Server ReadTimeout bounds reading the whole request, headers and body. Graceful shutdown is explicit: Shutdown(ctx) "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error", the same sequence Uvicorn runs, with the context deadline in place of --timeout-graceful-shutdown. The Go side of configuration and logging (flag, env, log/slog JSON handler) is in CLI Flags, Env & Logging; the server in HTTP Server & Client.

go
// Go equivalent of the shutdown path on this page (illustrative; see /go/http-server-client)
srv := &http.Server{
	Addr:              ":8000",
	Handler:           mux,
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       15 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       5 * time.Second, // ~ --timeout-keep-alive
}
go func() { _ = srv.ListenAndServe() }() // returns http.ErrServerClosed after Shutdown
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
<-ctx.Done()
stop()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second) // ~ --timeout-graceful-shutdown 20
defer cancel()
_ = srv.Shutdown(shutdownCtx) // close listeners, close idle conns, wait for active ones
db.Close()                     // ~ lifespan after yield
ConcernGo net/httpFastAPI + Uvicorn
Parallelismgoroutines on GOMAXPROCS threads (container-aware since 1.25)worker processes (you pick N)
Keep-alive timeoutIdleTimeout--timeout-keep-alive
Slow-client protectionReadHeaderTimeout, ReadTimeout--h11-max-incomplete-event-size, proxy timeouts
Graceful shutdownShutdown(ctx)SIGTERM handling + --timeout-graceful-shutdown
Connection poolone *sql.DB per process (SetMaxOpenConns)one engine per worker (pool_size × workers)
Structured logslog/slog JSON handlerdictConfig + JSON formatter
Imagestatic binary on distroless/scratchmulti-stage uv venv on python:3.12-slim

Common misconceptions ​

BeliefReality
More workers always mean more throughputOnly for CPU-bound work: 47.9 → 184.1 req/s CPU-bound, about 1,350 req/s either way for async def I/O (real)
Gunicorn is required in productionFastAPI's docs recommend --workers; Gunicorn is for its extra management features
The lifespan runs once per deploymentOnce per worker process and again after every recycle
.env overrides environment variablesEnvironment variables win over .env (tested)
def endpoints block the serverThey run in a 40-token thread pool; time.sleep in async def is what blocks (9.6 req/s)
--limit-concurrency queues excess requestsIt answers 503 immediately and counts connections too (387 of 400 were 503)
SIGTERM always triggers a graceful shutdownOnly if PID 1 forwards it: exec form and an init like tini
Graceful shutdown waits as long as needed--timeout-graceful-shutdown cancels the rest (client got 500); SIGKILL ends it at the grace period
One /health endpoint is enoughLiveness and readiness answer different questions; a DB check in liveness causes restart storms
--forwarded-allow-ips '*' is harmlessAny client can then forge its IP and scheme
/metrics shows the whole serviceWithout multiprocess mode it shows one worker (real: 153 of 201 requests)
CORS protects the APIIt only controls what browsers may read; auth is still needed
ORJSONResponse is the fastest choiceOn FastAPI 0.130+ a response model is serialised by Pydantic in Rust; ORJSON is deprecated
A bigger thread pool is freeMemory per thread, more DB checkouts, and the pool may just move the queue to the database
os.cpu_count() gives the container's CPUsIt returns the host's cores; derive WEB_CONCURRENCY from the CPU limit
My load tool measures the serverA shared httpx pool showed 222.5 req/s where ab showed 1,343.1 (real)

Cheat sheet ​

TopicRemember
Start in productionuvicorn app.main:app --host 0.0.0.0 --port 8000 (1 worker per pod) or --workers N
fastapi run / fastapi devProduction defaults on 0.0.0.0 / reload on 127.0.0.1, workers ignored with reload
Gunicorngunicorn -k uvicorn_worker.UvicornWorker -w N; uvicorn.workers is deprecated
Recyclingmax_requests + max_requests_jitter; Uvicorn --limit-max-requests
LifespanPools, clients, process pools, thread tokens; per worker
Pool budgetworkers × (pool_size + max_overflow) × replicas × surge < max_connections
SettingsBaseSettings, env_prefix, SecretStr, @lru_cache get_settings(), validators
Priorityinit kwargs > env vars > .env > secrets dir > defaults
Logging--log-config dictConfig; uvicorn.error/uvicorn.access; JSON to stdout
Request IDPure ASGI middleware + ContextVar + logging filter; return it on 500 too
Probes/healthz (process) for liveness, /readyz (dependencies) for readiness
Shutdownexec form + tini; --timeout-graceful-shutdown < grace period − preStop
Imagemulti-stage uv, --locked --no-dev, UV_COMPILE_BYTECODE=1, PYTHONUNBUFFERED=1, non-root
Proxy--proxy-headers, --forwarded-allow-ips <proxy>, --root-path for prefixes
SecurityTrustedHost, CORS allow-list, HTTPS redirect, security headers, docs_url=None in prod
def vs async def40 thread tokens per worker; never block inside async def
Server knobs--timeout-keep-alive > LB idle, --limit-concurrency → 503, --backlog 2048
MeasureCalibrated load tool, p50 and p99, then py-spy / cProfile
Metricsprometheus-fastapi-instrumentator; PROMETHEUS_MULTIPROC_DIR with workers

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Your async API runs with one Uvicorn worker on a 4-core VM. Will --workers 4 make it four times faster? Must-know ​

Answer

Answer: Only if the bottleneck is CPU in Python code. One worker has one event loop and one GIL; I/O-bound async def endpoints already overlap their waits, so in the real run a 20 ms await endpoint served about 1,350 req/s with 1 or 4 workers, while a CPU-bound endpoint went from 47.9 to 184.1 req/s. More workers also multiply memory, lifespan resources and database connections. See Worker processes.

2 — What exactly happens between SIGTERM and process exit in Uvicorn, and what does --timeout-graceful-shutdown change? Must-know ​

Answer

Answer: Uvicorn logs "Shutting down", closes the listening socket (new connections are refused), closes idle keep-alive connections, waits for in-flight requests, runs the lifespan shutdown (code after yield) and exits. Without the timeout it waits indefinitely; with it, tasks still running are cancelled ("Cancel 1 running task(s), timeout graceful shutdown exceeded") and their clients get a 500, then the lifespan shutdown still runs. All of it must fit in the orchestrator's grace period. See Graceful shutdown.

3 — Why must the Dockerfile use exec-form CMD, and what does tini add? Must-know ​

Answer

Answer: Shell form runs /bin/sh -c "...", so the shell is PID 1 and, per the Dockerfile reference, the server "will not receive Unix signals": docker stop and Kubernetes' SIGTERM never reach Uvicorn, there is no drain, and the process is killed at the timeout. Exec form makes the listed program the process that receives signals. tini as PID 1 forwards signals and reaps zombie processes (for example children of a ProcessPoolExecutor), which a Python process as PID 1 does not do. See The production Docker image.

4 — What is the difference between a liveness and a readiness probe, and what should each check? Must-know ​

Answer

Answer: A failing liveness probe makes Kubernetes restart the container; a failing readiness probe only removes the pod from Service endpoints. Liveness should check that the process can answer (/healthz without dependencies); readiness should check what serving needs (/readyz with a DB round trip). Putting the database into liveness turns a database blip into a restart of every pod. See Health endpoints.

5 — In what order does pydantic-settings resolve a value, and why is get_settings() wrapped in @lru_cache? Must-know ​

Answer

Answer: Init kwargs, then environment variables, then the .env file, then the secrets directory, then field defaults (CLI arguments first if enabled); the snippet's tests assert each step. @lru_cache makes the settings a per-process singleton: parsed and validated once, the same object for every request. The consequence is that later environment changes are invisible until get_settings.cache_clear(), and tests should build Settings(...) explicitly or use dependency_overrides. See Settings.

6 — Four workers, pool_size=5, max_overflow=5, three replicas, rolling deploy with maxSurge: 1. How many PostgreSQL connections can the service open? Important ​

Answer

Answer: Each worker has its own pool: 4 × (5 + 5) = 40 per container; three replicas give 120, and during the surge a fourth container adds 40, so up to 160. With PostgreSQL's default max_connections = 100 that fails; reduce per-worker pools, use fewer workers per pod, or put PgBouncer in front. See Connection pool sizing.

7 — A def endpoint and an async def endpoint both wait 100 ms. Why did the def one top out at about 355 req/s with 100 users, and what fixed it? Important ​

Answer

Answer: def endpoints run through run_in_threadpool on AnyIO's default limiter of 40 tokens, so at most 40 run at once per worker: 40 / 0.1 s = 400 req/s is the ceiling. Raising anyio.to_thread.current_default_thread_limiter().total_tokens to 100 in the lifespan gave 811 req/s. The async def version (842 req/s) needs no threads. A time.sleep inside async def gave 9.6 req/s because it blocks the loop. See Sync vs async.

8 — How do you make every log line of a request carry the same request ID, including lines from def endpoints and libraries? Important ​

Answer

Answer: A pure ASGI middleware reads or generates the ID, stores it in a contextvars.ContextVar before calling the app, adds it to the response headers and resets it afterwards; a logging.Filter copies the value onto every record, and a JSON formatter writes it. run_in_threadpool and asyncio.create_task copy the context, so threads and tasks see it. Catch unhandled exceptions in that middleware so the 500 carries the ID too. See Request ID middleware.

9 — Behind Nginx, request.client.host is always 10.0.3.17. What do you change, and what must you not do? Important ​

Answer

Answer: Keep --proxy-headers on and set --forwarded-allow-ips (or FORWARDED_ALLOW_IPS) to the proxy's address or network, so Uvicorn takes the client and scheme from X-Forwarded-For and X-Forwarded-Proto only when the peer is the proxy. Do not set it to * when clients can reach the app directly: anyone could forge their IP and scheme. If the proxy strips a path prefix, add --root-path. See Behind a reverse proxy.

10 — Gunicorn with UvicornWorker or uvicorn --workers: what does each give you, and what did the boot-failure run show? Important ​

Answer

Answer: Both restart dead workers. Gunicorn adds a pre-fork master with hooks, a heartbeat timeout, max_requests + jitter recycling, --preload and binary upgrades; Uvicorn's supervisor is simpler, spawns workers, supports --limit-concurrency and SIGHUP/SIGTTIN/SIGTTOU. With a configuration error in every worker, Gunicorn's master stopped with "Worker failed to boot" and exit code 3, while uvicorn --workers 2 kept respawning workers and stayed up, so only a readiness probe would reveal the problem. See Gunicorn.

11 — How does Laravel Octane relate to Uvicorn workers, and what is the Laravel equivalent of @lru_cache get_settings()? Good to know ​

Answer

Answer: Octane (on FrankenPHP, Swoole or RoadRunner) boots the app once per worker and keeps it in memory, like a Uvicorn worker, with --workers and --max-requests (500 by default) for recycling; PHP-FPM is the per-request pre-fork model with pm.max_children and pm.max_requests. php artisan config:cache freezes configuration once, after which env() outside config files returns null, the counterpart of validating settings once and caching them. See For PHP/Laravel developers.

12 — What does Go do instead of worker processes, and how does Shutdown(ctx) compare with Uvicorn's shutdown? Good to know ​

Answer

Answer: One Go process runs goroutines on GOMAXPROCS OS threads, and since Go 1.25 GOMAXPROCS defaults to the container's CPU limit when it is lower than the core count; Python needs an explicit worker count. http.Server.Shutdown(ctx) closes listeners, closes idle connections and waits for active ones until the context expires, the same sequence as Uvicorn's, with the context deadline playing the role of --timeout-graceful-shutdown. See The Go angle.

Glossary ​

TermMeaning
ASGI serverProgram that implements HTTP and calls an ASGI app (await app(scope, receive, send)); Uvicorn, Hypercorn, Granian, Gunicorn's asgi worker
UvicornThe ASGI server used here; uvloop + httptools by default
fastapi run / fastapi devFastAPI CLI wrappers around Uvicorn: production defaults / auto-reload
--workersNumber of worker processes ($WEB_CONCURRENCY or 1)
Worker processOne OS process with its own event loop, GIL, thread pool and lifespan
Process managerStarts, watches, restarts and stops workers (Uvicorn supervisor, Gunicorn, systemd, Kubernetes)
Master process (arbiter)Gunicorn's managing process; never touches client sockets
Pre-forkModel where a master forks workers that inherit the listening socket
SpawnStart method where a fresh interpreter imports the app (Uvicorn's supervisor)
GunicornPre-fork WSGI/ASGI server and process manager
UvicornWorkerGunicorn worker class from uvicorn-worker (uvicorn_worker.UvicornWorker)
Worker recyclingRestarting a worker after N requests (max_requests, --limit-max-requests)
max_requests_jitterRandom extra requests so workers do not restart together
LifespanASGI startup/shutdown protocol; FastAPI's lifespan context manager
Connection pool in lifespanEngine and pool created at startup, disposed at shutdown, one per worker
Pool size vs workersTotal connections = workers × (pool_size + max_overflow) × replicas
pydantic-settingsPydantic package that fills BaseSettings from env, .env, secrets
BaseSettingsPydantic model class whose fields come from configuration sources
env_file / .envDotenv file read by pydantic-settings, below real environment variables
env_prefixPrefix added to every environment variable name (APP_)
secrets_dirDirectory of one-file-per-secret values (Docker/Kubernetes secrets)
SecretStrPydantic type that masks its value as **********
Settings dependencyDepends(get_settings) with @lru_cache
lru_cachefunctools decorator; here a per-process singleton
12-factor configConfiguration in environment variables, separate from code
uvicorn.errorUvicorn's general logger (startup, shutdown, warnings, tracebacks)
uvicorn.accessUvicorn's per-request access logger
--log-configUvicorn flag: logging config file applied with dictConfig / fileConfig
dictConfiglogging.config.dictConfig, logging setup from a dictionary
JSON logsOne JSON object per line per event
structlogStructured logging library with processors and contextvars helpers
Request ID / correlation IDIdentifier of one request / one user action across services
contextvarsStandard-library context-local variables, copied into tasks and thread-pool calls
Access logOne line per request: method, path, status, duration
PYTHONUNBUFFEREDEnv var: unbuffered stdout/stderr
PYTHONDONTWRITEBYTECODEEnv var: do not write .pyc files
Compile bytecodeUV_COMPILE_BYTECODE=1: .pyc created at image build time
Multi-stage buildDockerfile with a builder stage and a slim runtime stage
--no-devuv flag: exclude the dev dependency group
Non-root userContainer process running as an unprivileged UID
Exec formCMD ["prog", "arg"] JSON form, no shell in between
PID 1First process in a container; receives signals, must reap zombies
tiniMinimal init for containers: signal forwarding and zombie reaping
HEALTHCHECKDockerfile instruction defining a container health command
SIGTERMPolite termination signal sent by docker stop and the kubelet
Graceful shutdownStop accepting, drain in-flight requests, release resources, exit
DrainWaiting for in-flight requests and connections to finish
--timeout-graceful-shutdownUvicorn's cap on the drain; then tasks are cancelled
Liveness / readiness / startup probeRestart check / traffic check / slow-start gate in Kubernetes
preStopKubernetes hook that runs before SIGTERM; counts against the grace period
terminationGracePeriodSecondsTime from deletion to SIGKILL (default 30 s)
Rolling deployReplacing pods gradually (maxSurge, maxUnavailable)
Reverse proxyNginx, Traefik, a cloud LB in front of the app
X-Forwarded-For / X-Forwarded-ProtoHeaders carrying the original client IP / scheme
--proxy-headers / --forwarded-allow-ipsUvicorn: honour forwarded headers / only from these peers
--root-pathASGI root_path for apps served under a stripped prefix
Thread pool / threadpoolAnyIO worker threads running def endpoints and dependencies
AnyIO capacity limiterToken counter limiting concurrent to_thread.run_sync calls (default 40)
run_in_threadpoolStarlette helper that runs a sync function in the thread pool
uvlooplibuv-based drop-in asyncio event loop
httptoolsPython binding to the llhttp C parser
Keep-alive / --timeout-keep-aliveReusing a connection for several requests / idle limit (5 s)
--limit-concurrencyMax connections or tasks before immediate 503
--backlogTCP accept queue length passed to listen() (2048)
--limit-max-requestsUvicorn worker exits after N requests
StreamingResponseResponse sent chunk by chunk from an iterator
GZipMiddlewareCompresses responses above minimum_size
ORJSONResponseJSON response rendered with orjson; deprecated since FastAPI 0.131.0
Validation costCPU spent validating/serialising responses through Pydantic
CPU-boundWork limited by CPU, not by waiting
ProcessPoolExecutorPool of worker processes for CPU-bound functions
Load testingGenerating controlled traffic to measure throughput and latency
p50 / p99Median / 99th-percentile latency
ThroughputCompleted requests per second
py-spySampling profiler that attaches to running Python processes
cProfileStandard-library deterministic profiler
CORSMiddlewareAnswers CORS preflights for allowed origins
TrustedHostMiddlewareRejects requests whose Host is not allowed (400)
HTTPSRedirectMiddlewareRedirects http to https (307)
Security headersnosniff, X-Frame-Options, CSP, HSTS, Referrer-Policy
docs_url=NoneFastAPI argument that removes /docs (also redoc_url, openapi_url)
Protect /docsServe docs only behind auth or on an internal network
PrometheusPull-based metrics system scraping /metrics
prometheus-fastapi-instrumentatorMiddleware + /metrics endpoint for FastAPI
PROMETHEUS_MULTIPROC_DIRDirectory that makes the Prometheus client aggregate across processes
OpenTelemetryVendor-neutral tracing/metrics/logs SDK; FastAPIInstrumentor, opentelemetry-instrument
Secrets in images anti-patternCredentials in layers, ENV, ARG or a copied .env
OctaneLaravel's long-running application server layer (FrankenPHP, Swoole, RoadRunner)
FrankenPHPPHP application server written in Go
SwoolePHP extension providing an async server
PHP-FPM pm.max_childrenMaximum number of PHP-FPM child processes
config:cacheLaravel command caching configuration into one file
APP_ENVEnvironment name in Laravel and in this snippet
http.Server ReadTimeoutGo server timeout for reading the whole request
GOMAXPROCSNumber of OS threads running Go code; container-aware since Go 1.25
Shutdown(ctx)Go's graceful shutdown of an http.Server
WEB_CONCURRENCYEnv var read by Uvicorn and Gunicorn as the default worker count

References ​

Every URL below (90) returned HTTP 200 on 2026-11-29 (pipeline/sources/fastapi-production-uvicorn/ref-status.tsv); the text of each is saved next to it. Version facts about current releases also come from the PyPI JSON API (pypi-latest.txt).

Built by Morteza Negahi