Skip to content

Practical software architecture · Part 10 of 10

Configuration and environments: the twelve-factor way

Keep code identical across environments and put everything that differs in configuration. Environment variables, secrets and parity explained.

· 2 min read

architecturedevops

The same build should run on a laptop, in staging and in production. What changes between them is configuration: database addresses, API keys, feature switches. The twelve-factor app methodology gives clear rules for this.

Config is not code

Configuration is anything likely to differ between deploys. Do not hard-code it, and do not keep production values in the repository. A good test: could you open-source the codebase right now without leaking a credential?

Use environment variables

Environment variables are language-neutral, easy to change per deployment and hard to commit by accident.

shell
export DATABASE_URL="postgres://app:[email protected]:5432/app"
export LOG_LEVEL="info"
./bin/start-server
Python
import os

DATABASE_URL = os.environ["DATABASE_URL"]          # fail fast if missing
LOG_LEVEL = os.environ.get("LOG_LEVEL", "info")    # optional with a default

Fail fast. Read required settings at startup and stop with a clear message when one is missing or invalid. A service that boots with a half-broken configuration fails later, in a confusing way.

Secrets deserve more care

Environment variables are convenient but visible to anything that can read the process or its container definition. Keep secrets in a secret manager or encrypted store, inject them at deploy time, rotate them, and never print them in logs. Keep a record of who changed what and when.

Dev and production parity

Differences between environments cause bugs that only appear in production. Reduce the gaps:

  1. Use the same type of database and the same major version everywhere.
  2. Deploy the same artifact, for example one container image, to every environment.
  3. Keep the time between writing code and deploying it short.

Pitfalls

  • Config files per environment that slowly drift apart.
  • Code that checks if production? all over the place. Prefer an explicit setting for each behaviour.
  • Defaults that are unsafe, such as debug mode on.

Takeaway

One build, many configurations. Keep secrets out of the repository, validate settings at startup and keep environments as alike as you can.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.