GeekCoding101 make your way to geek

The 12-Factor App with Python & FastAPI

All 12 factors applied to a Python FastAPI service: pydantic-settings config, async SQLAlchemy, Docker, logs and Kubernetes, with code for each.

10 min read
Cover Image of A 12 Factor Crash Course
On this pageWhy bother: apps that don’t suck in production

GeekCoding101 Β· Published May 12, 2025 Β· Topics: 12-factors, best-practices, system-design

The twelve-factor app is a set of 12 principles for building web services that deploy cleanly, scale horizontally and behave the same in every environment. In a Python/FastAPI stack, it comes down to a few habits:

  • One repo per service.
  • Locked dependencies in pyproject.toml.
  • Config read from environment variables with pydantic-settings.
  • Stateless Uvicorn processes that bind to a port.
  • Logs written to stdout.
  • Admin tasks run as one-off processes from the same image.

a 12-factor app crash course
a 12-factor app crash course

Why bother: apps that don’t suck in production

Let’s be honest: plenty of apps β€œwork on my machine” but self-destruct the moment they meet the real world. The usual suspects:

  • Configs hardcoded.
  • Logs missing.
  • Environments confused.
  • Deployments that feel like an escape room puzzle.

If you want your service to thrive in production (and not become an ops horror story), you need a design philosophy that enforces clean separation, modularity and resilience. That’s what the 12-factor methodology gives you.

Below, we take each factor one by one with a FastAPI + Pydantic v2 + SQLAlchemy 2.0 stack. Think of it as a DevOps dojo, with Python as your katana.

The 12 factors at a glance

#FactorIn a Python/FastAPI service
ICodebaseOne Git repo per service, many deploys
IIDependenciespyproject.toml + a lock file, installed in an isolated env/container
IIIConfigEnvironment variables, read with pydantic-settings
IVBacking servicesDatabase/queue/cache URLs come from config
VBuild, release, runImmutable Docker image + runtime config = release
VIProcessesStateless app; sessions per request via dependency injection
VIIPort bindingUvicorn listens on a port itself
VIIIConcurrencyScale out with more processes or pods
IXDisposabilityFast startup, graceful shutdown with lifespan
XDev/prod paritySame image and backing services in dev and prod
XILogsWrite to stdout; the platform aggregates
XIIAdmin processesMigrations and scripts as one-off processes from the same image

🧱 The twelve factors, Python style

I. Codebase: one codebase tracked in revision control, many deploys

The rule: a single source of truth, version-controlled, with no Franken-repos. Every deploy (dev, staging, prod) comes from the same codebase.

πŸ“Œ In Python:

  • Use one Git repo per service.
  • Don’t share code across projects via copy-paste. Publish shared code as an internal package (for example, to a private package index) and declare it as a dependency.

βœ… Recommended layout:

/fastapi-12factor-app
β”œβ”€β”€ app/
β”‚ β”œβ”€β”€ api/
β”‚ β”œβ”€β”€ core/
β”‚ β”‚ └── config.py
β”‚ β”œβ”€β”€ models/
β”‚ β”œβ”€β”€ db.py
β”‚ └── main.py
β”œβ”€β”€ scripts/
β”œβ”€β”€ tests/
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ poetry.lock
β”œβ”€β”€ README.md
└── .env.example

The real .env stays out of Git: add it to .gitignore and commit an .env.example with placeholder values instead.

II. Dependencies: explicitly declare and isolate dependencies

The rule: no implicit magic. Declare every dependency, lock the versions, and never rely on whatever happens to be installed on the host.

πŸ“Œ In Python: use pyproject.toml with a tool that produces a lock file, such as Poetry, pip-tools or uv.

βœ… Example pyproject.toml (Poetry):

[tool.poetry.dependencies]
python = "^3.12"
fastapi = "^0.110.0"
uvicorn = "^0.29.0"
sqlalchemy = "^2.0"
asyncpg = "^0.29"
pydantic = "^2.6"
pydantic-settings = "^2.0"

In Pydantic v2, BaseSettings moved to the separate pydantic-settings package, so it has to be listed explicitly.

πŸ”’ Lock it down:

Terminal window
poetry lock

Commit poetry.lock, and run the app in a container so your coworker’s Python 3.6 setup doesn’t eat your soul.

III. Config: store config in the environment

The rule: config isn’t code. Anything that changes between deploys (database URLs, credentials, feature flags) comes from environment variables.

πŸ“Œ In Python with Pydantic v2 (app/core/config.py):

from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
database_url: str
debug: bool = False
settings = Settings()
  • DATABASE_URL and DEBUG map to the fields automatically; matching is case-insensitive by default.
  • Real environment variables take priority over values in .env.
  • If .env doesn’t exist, which is normal in production, the env vars are used on their own.

βœ… .env for local only:

DATABASE_URL=postgresql+asyncpg://user:pass@db:5432/app
DEBUG=true

πŸš€ In production, let Kubernetes inject the real values from ConfigMaps and Secrets. No secrets in code, please.

IV. Backing services: treat backing services as attached resources

The rule: databases, queues, caches and blob storage are attached resources. You should be able to swap one by changing config, not code.

πŸ“Œ In FastAPI: build the engine from settings.database_url, never from a hardcoded string (app/db.py):

from sqlalchemy.ext.asyncio import create_async_engine
from app.core.config import settings
engine = create_async_engine(settings.database_url, echo=settings.debug)

πŸ§ͺ In tests, point DATABASE_URL at an in-memory SQLite database (sqlite+aiosqlite:///:memory:, which needs the aiosqlite driver). The app code doesn’t change at all. That’s the power of this separation.

V. Build, release, run: strictly separate build and run stages

The rule: there are three stages, and they stay separate:

  • Build turns code into an artifact (here, a Docker image).
  • Release combines that artifact with the config for one environment.
  • Run starts it.

You never change code or config inside a running release; you cut a new one.

πŸ“¦ Dockerfile example:

FROM python:3.12-slim
WORKDIR /app
RUN pip install --no-cache-dir poetry
COPY pyproject.toml poetry.lock ./
RUN poetry config virtualenvs.create false \
&& poetry install --without dev --no-root
COPY . .
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
  • Copying the dependency files first lets Docker cache the install layer.
  • --without dev skips dev tools in the image.
  • --no-root installs only the dependencies, not the project itself.

πŸ‘Š Don’t bake secrets into the image during the build. They arrive as environment variables at run time.

VI. Processes: execute the app as one or more stateless processes

The rule: processes are stateless and share nothing. Anything that must persist lives in a backing service (database, cache), not in process memory or on local disk.

πŸ“Œ In FastAPI:

  • Don’t keep per-user or per-request state on the app object or in module-level globals.
  • Open a database session per request with dependency injection.

Add the session factory to app/db.py:

from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
async_session = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncIterator[AsyncSession]:
async with async_session() as session:
yield session

Then use the dependency in a route:

from fastapi import Depends
@app.get("/items")
async def list_items(session: AsyncSession = Depends(get_session)):
...

Because no request depends on a specific process, Kubernetes can add, kill or move pods freely. Zombie state has nowhere to live.

VII. Port binding: export services via port binding

The rule: the app is self-contained and serves HTTP by listening on a port. It doesn’t need to be injected into an external web server at runtime.

βœ… FastAPI with Uvicorn does this naturally:

Terminal window
uvicorn app.main:app --host 0.0.0.0 --port 8000

A Kubernetes Service routes traffic to that port. You can still put a reverse proxy or ingress in front for TLS and routing, but the app doesn’t depend on Apache/Nginx glue to run.

VIII. Concurrency: scale out via the process model

The rule: scale horizontally by running more processes, not by building one giant multithreaded process.

πŸ“Œ Two common options:

  • Several workers on one machine or VM:

    Terminal window
    uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

    Or use Gunicorn as a process manager with Uvicorn workers.

  • On Kubernetes: run one Uvicorn process per container and scale the number of pods instead, by hand or with a HorizontalPodAutoscaler. This keeps each pod simple and lets the platform do the scaling.

IX. Disposability: fast startup and graceful shutdown

The rule: processes can be started or stopped at any moment. Startup should be quick, and shutdown should finish in-flight work and release resources cleanly.

βœ… In FastAPI, use a lifespan handler. It replaces the older @app.on_event("startup") / "shutdown" hooks:

import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.db import engine
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Ready to go!")
yield
logger.info("Shutting down gracefully...")
await engine.dispose()
app = FastAPI(lifespan=lifespan)

When Kubernetes stops a pod, it sends SIGTERM. Uvicorn catches it, stops accepting new connections, lets in-flight requests finish and then runs the shutdown half of lifespan. Keep that work short so it completes within the pod’s termination grace period.

X. Dev/prod parity: keep development, staging and production as similar as possible

The rule: keep the gaps in time, people and tools between dev and prod small. The same code and the same kinds of backing services should run everywhere.

πŸ“Œ In practice:

  • Use .env locally and ConfigMaps/Secrets in production, with the same app code and the same Settings class.
  • Use Docker in dev, same as prod. Don’t β€œjust run it on the host.”
  • Use the same database engine in dev as in prod (Postgres, not SQLite standing in for it). Keep SQLite for fast unit tests only.

βœ… Use docker-compose in dev, or Tilt/Skaffold, to mirror the production infrastructure.

XI. Logs: treat logs as event streams

The rule: the app doesn’t manage log files. It writes an unbuffered event stream to stdout/stderr, and the platform collects, routes and stores it.

βœ… FastAPI + logging setup:

import logging
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
@app.get("/health")
async def health():
logger.info("Health check called")
return {"status": "ok"}

🎯 Let Kubernetes plus Fluentd, ELK or Grafana Loki deal with aggregation and search.

XII. Admin processes: run admin/one-off tasks as one-off processes

The rule: tasks like database migrations, data fixes or cleanup scripts run as separate one-off processes. They use the same codebase, image and config as the app.

βœ… Put admin tasks in a scripts/ directory:

/scripts/
└── migrate.py

Run a task locally:

Terminal window
python scripts/migrate.py

Inside the dev stack, run it in the app container so it gets the same environment:

Terminal window
docker compose run --rm app python scripts/migrate.py

In production, run the same image as a Kubernetes Job. If you use Alembic for migrations, the Job simply runs alembic upgrade head.

Cheatsheet

FactorApplies toDescription
CodebaseAll appsOne codebase per app, tracked in version control, with many deploys.
DependenciesLanguage/runtimeExplicitly declare and isolate dependencies via a manifest and lock file (e.g., pyproject.toml + poetry.lock).
ConfigEnvironment managementStore config in environment variables, never in code.
Backing ServicesDatabases, queues, cachesTreat services as attached resources; swap them via config, not code changes.
Build, Release, RunCI/CD pipelinesSeparate build, release and run stages. Never change code or config inside a release.
ProcessesApplication executionRun as stateless, share-nothing processes; persist state in backing services.
Port BindingWeb servicesExport services via port binding; don’t depend on an external web server at runtime.
ConcurrencyScalabilityScale out via the process model: more processes or pods.
DisposabilityLifecycle managementFast startup and graceful shutdown improve robustness and scalability.
Dev/Prod ParityDev environmentsKeep development, staging and production as similar as possible.
LogsObservabilityTreat logs as event streams; write to stdout and let the platform aggregate.
Admin ProcessesOne-off tasksRun admin tasks (e.g., migrations) as one-off processes from the same image and config.

FAQ

What is a twelve-factor app? It’s a methodology for building web apps and services as twelve principles. They cover codebase, dependencies, config, backing services, build/release/run, processes, port binding, concurrency, disposability, dev/prod parity, logs and admin processes. The goal is apps that are portable, easy to deploy and easy to scale.

Do I need Kubernetes to follow the 12 factors? No. The factors are platform-neutral: env-var config, stateless processes, stdout logs and port binding work the same on a single VM, in docker-compose or on a PaaS. Kubernetes just makes several of them (scaling, graceful shutdown, one-off Jobs) easy to operate.

Should I use a .env file in production? Usually not. .env is a convenience for local development. In production, inject real environment variables from your platform, such as Kubernetes ConfigMaps and Secrets. pydantic-settings reads both, and real environment variables win.

How do I handle secrets in a 12-factor FastAPI app? Treat them like any other config: environment variables provided at run time. Keep them out of the codebase, out of the Docker image and out of Git.

Uvicorn workers or more pods? On a single machine, uvicorn --workers N (or Gunicorn with Uvicorn workers) uses multiple CPU cores. On Kubernetes, a common pattern is one process per pod, with the pod count scaled by the platform.

πŸ”š Wrapping it all up

The 12-factor methodology isn’t just a checklist. It’s a survivability manual for cloud-native apps. FastAPI, paired with Pydantic v2 and SQLAlchemy 2.0, makes following it refreshingly clean.

A few takeaways:

  • Treat config like royalty: never hardcode it, never commit it.
  • Keep your app stateless and dumb, and let the platform do the smart scaling.
  • Stream your logs, don’t hoard them.
  • Build once, deploy often, break never (hopefully).

ℹ️ If you want more engineering notes and system design, check out the tags on this page. Thanks for reading!

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts