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.

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
| # | Factor | In a Python/FastAPI service |
|---|---|---|
| I | Codebase | One Git repo per service, many deploys |
| II | Dependencies | pyproject.toml + a lock file, installed in an isolated env/container |
| III | Config | Environment variables, read with pydantic-settings |
| IV | Backing services | Database/queue/cache URLs come from config |
| V | Build, release, run | Immutable Docker image + runtime config = release |
| VI | Processes | Stateless app; sessions per request via dependency injection |
| VII | Port binding | Uvicorn listens on a port itself |
| VIII | Concurrency | Scale out with more processes or pods |
| IX | Disposability | Fast startup, graceful shutdown with lifespan |
| X | Dev/prod parity | Same image and backing services in dev and prod |
| XI | Logs | Write to stdout; the platform aggregates |
| XII | Admin processes | Migrations 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.exampleThe 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:
poetry lockCommit 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_URLandDEBUGmap to the fields automatically; matching is case-insensitive by default.- Real environment variables take priority over values in
.env. - If
.envdoesnβ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/appDEBUG=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 poetryCOPY 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 devskips dev tools in the image.--no-rootinstalls 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 sessionThen 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:
uvicorn app.main:app --host 0.0.0.0 --port 8000A 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 4Or 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 loggingfrom contextlib import asynccontextmanager
from fastapi import FastAPI
from app.db import engine
logger = logging.getLogger(__name__)
@asynccontextmanagerasync 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
.envlocally and ConfigMaps/Secrets in production, with the same app code and the sameSettingsclass. - 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 loggingimport 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.pyRun a task locally:
python scripts/migrate.pyInside the dev stack, run it in the app container so it gets the same environment:
docker compose run --rm app python scripts/migrate.pyIn production, run the same image as a Kubernetes Job. If you use Alembic for migrations, the Job simply runs alembic upgrade head.
Cheatsheet
| Factor | Applies to | Description |
|---|---|---|
| Codebase | All apps | One codebase per app, tracked in version control, with many deploys. |
| Dependencies | Language/runtime | Explicitly declare and isolate dependencies via a manifest and lock file (e.g., pyproject.toml + poetry.lock). |
| Config | Environment management | Store config in environment variables, never in code. |
| Backing Services | Databases, queues, caches | Treat services as attached resources; swap them via config, not code changes. |
| Build, Release, Run | CI/CD pipelines | Separate build, release and run stages. Never change code or config inside a release. |
| Processes | Application execution | Run as stateless, share-nothing processes; persist state in backing services. |
| Port Binding | Web services | Export services via port binding; donβt depend on an external web server at runtime. |
| Concurrency | Scalability | Scale out via the process model: more processes or pods. |
| Disposability | Lifecycle management | Fast startup and graceful shutdown improve robustness and scalability. |
| Dev/Prod Parity | Dev environments | Keep development, staging and production as similar as possible. |
| Logs | Observability | Treat logs as event streams; write to stdout and let the platform aggregate. |
| Admin Processes | One-off tasks | Run 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!