Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 15 min · revision 3

Configuration That Fails Fast

Validate configuration at start-up with a typed settings class, exit at once when a variable is missing or malformed, and supply secrets at run time instead of baking them into images.

Contentsand lesson path

What you will learn

  • Validate configuration at startup so the process fails fast on missing or malformed settings, with secrets supplied by the runtime environment rather than code or images.

Prerequisites: Database Schema Migrations

01. Why it matters

A common pattern is reading configuration lazily all over the codebase, with bare lookups like os.environ.get("STRIPE_SECRET_KEY") inside specific route functions. Suppose an engineer forgets to set STRIPE_SECRET_KEY in the production manifest:

  • Everything looks healthy: the container starts cleanly, the lightweight /livez probe returns 200 OK, and the pipeline marks the rollout successful and replaces every old Pod.
  • The failure comes later: six hours later, the first customer tries to check out. The route handler reads the missing setting as None and fails with a TypeError, or the payment gateway rejects the call. Customers see failed payments that a check at deployment time would have caught.

The fail-fast principle says that a system should report a condition that prevents normal operation as soon as it can, instead of carrying on in a broken or undefined state. For configuration, failing fast means validating every required environment variable and secret when the container starts, before the application opens its port or accepts its first request.

02. Failing at start-up, and build, release, run

The fail-fast alternative. When configuration is validated during bootstrap, missing or malformed settings cause the container process to exit immediately with a non-zero exit code (such as sys.exit(1)) and an explicit error message naming the exact missing variable. A Kubernetes Deployment does not halt or roll back by itself: the new pods crash-loop and never become ready, so the rollout stalls instead of replacing the remaining healthy pods, and after progressDeadlineSeconds the Deployment reports Progressing=False. How many users notice depends on the rollout settings. With the default maxUnavailable: 25%, up to a quarter of the old pods may already have been removed, so capacity drops; with maxUnavailable: 0 and enough headroom, the old pods keep serving at full capacity. Alert on a stalled rollout (kubectl rollout status deployment/<name> --timeout=5m fails), read the error in the pod logs, and roll back with kubectl rollout undo.

Build, release, run. The Twelve-Factor App separates three stages of delivery:

  • Build: turns source code into an immutable container image: application code, installed dependencies, static assets. The build knows nothing about where it will run, so the same image runs in staging and production without rebuilding.
  • Release: combines that image with one environment's configuration and secrets. Each release gets its own identifier (e.g. release-v142) and is never changed afterwards: changing an environment variable creates a new release.
  • Run: starts the release's processes. Checking every required setting at the start of the run stage stops a broken release before it becomes ready, so with a safe rollout configuration it never takes over production traffic.

03. Typed validation with pydantic-settings, and secrets at run time

A typed settings class turns the raw strings of the environment into checked values in one place.

Schema enforcement with pydantic-settings. With BaseSettings, configuration is a typed class with explicit constraints:

  • Type coercion: environment variables arrive as strings. Pydantic parses string representations into native types (PORT="8080" becomes int(8080), ENABLE_METRICS="true" becomes bool(True)). However, if an engineer mistakenly configures MAX_WORKERS="four", Pydantic v2 rejects the value with an explicit ValidationError: Input should be a valid integer, unable to parse string as an integer.
  • Connection-string checks: types such as PostgresDsn and RedisDsn check the shape of a connection string, such as an allowed scheme and a host, before any connection is attempted. They do not check that the credentials work: only a real connection (for example in the readiness check) shows that.
  • Masking secrets with SecretStr: wrap passwords, API keys and JWT secrets in SecretStr. Printing or logging the settings object then shows ********** instead of the value. The mask has limits. A password inside a PostgresDsn URL is printed in full, so keep it in its own SecretStr field. And a ValidationError message quotes the raw input values, so a missing database_url can print the value of jwt_secret in its input_value. Pydantic shortens an input_value only when it is longer than 50 characters, and then keeps only about its first 25 and last 24 characters. So a short secret (30 characters, say) is shown whole and most of a long one is still visible: 31 characters of a 40- or 64-character key. Log only each error's field and message, as the code below does.

Secrets at run time, not at build time. Factor III of the Twelve-Factor App (Config) keeps configuration out of the code. Four common mistakes break that rule:

  • Baking .env files into images: never run COPY .env . in a Dockerfile. Images are copied to registries, caches and laptops, so anyone who can pull the image can read the secrets.
  • Committing secrets to Git: never hardcode default passwords or API tokens in source code repositories, even in private repositories.
  • Docker build arguments (ARG): passing credentials with docker build --build-arg DB_PASS=... can leave the plain-text value in the image history, which docker history shows; use a build secret (RUN --mount=type=secret) when a build step really needs one.
  • Silent SQLite fallbacks: never write fallback code like db_url = os.getenv("DATABASE_URL") or "sqlite:///local.db". If the environment variable fails to inject in production, the application silently writes to a SQLite file inside the container, and those customer records are lost when the container is replaced.

In production, the platform supplies secrets at run time, as environment variables or mounted files, from a store such as Kubernetes Secrets, AWS Secrets Manager or HashiCorp Vault.

Python · Pydantic BaseSettings bootstrap with SecretStr and fail-fast validation
import sys
from pydantic import Field, PostgresDsn, SecretStr, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict

class AppConfig(BaseSettings):
    # Required settings (no defaults): deployment fails if missing
    database_url: PostgresDsn
    jwt_secret: SecretStr

    # Optional settings with safe operational defaults
    app_env: str = Field("production", pattern="^(development|staging|production)$")
    server_port: int = Field(8000, ge=1024, le=65535)
    max_connections: int = Field(20, ge=1, le=200)

    model_config = SettingsConfigDict(env_prefix="SERVICE_", case_sensitive=False)

def load_and_validate_config() -> AppConfig:
    try:
        config = AppConfig()
        # Log configuration safely (SecretStr hides credentials)
        print(f"Loaded config: env={config.app_env}, port={config.server_port}")
        print(f"JWT Secret masked: {config.jwt_secret}")  # Prints: **********
        return config
    except ValidationError as err:
        # Field and message only: str(err) would quote the raw input values
        sys.stderr.write("=" * 60 + "\n")
        sys.stderr.write("FATAL CONFIGURATION ERROR: Failed to boot service\n")
        for error in err.errors():
            field = ".".join(str(loc) for loc in error["loc"])
            msg = error["msg"]
            sys.stderr.write(f"  - Invalid field '{field}': {msg}\n")
        sys.stderr.write("=" * 60 + "\n")
        sys.exit(1)

04. Check your understanding

Practice check · 3 questions

SecretStr, validation errors and crashing pods

Three questions on configuration behaviour at startup.

Q1. Why declare the JWT signing secret as `SecretStr` in the Pydantic settings model?
Q2. A settings class has `database_url: PostgresDsn` and `jwt_secret: SecretStr`. A release sets only `SERVICE_JWT_SECRET` (a 30-character key), and the start-up code logs `str(err)` for the `ValidationError`. What does the log show of the secret?
Q3. New pods crash at startup because of a configuration error, and the Deployment uses the default `maxUnavailable: 25%`. What happens?
Practice only: not graded, not saved, not evidence.

05. Apply it

Apply these to the service in your skill project:

  • Use pydantic-settings for all configuration: Declare one Settings class that inherits from BaseSettings, with a type, a range or a pattern for every environment variable.
  • Create the settings at start-up: Call settings = Settings() at import time or in your FastAPI lifespan handler, and do not read os.environ inside route functions.
  • Wrap passwords and API keys in SecretStr: This keeps them out of printed settings and most logs; also keep passwords out of DSN fields, and log validation errors by field and message only.
  • Supply secrets at run time: Use Kubernetes Secrets, AWS Secrets Manager or HashiCorp Vault to provide credentials as environment variables or mounted files. Never commit credentials to Git or pass them as Docker build arguments.

In the next lesson, you rehearse a release with a database migration, a smoke test and a code rollback, and measure the errors during the switch.

06. Review prompt

Without looking back, define the fail-fast principle and explain why late-binding configuration lookups cause delayed production incidents. Describe how Pydantic BaseSettings parses and validates environment variables, and explain what happens when an invalid type is provided. Name three ways secrets leak at build time, two limits of SecretStr, and how a container platform supplies secrets at run time.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check