Production DeploymentVol. 16 · Part XVI
0 / 0

Shelves / Production Deployment

DP·190

Environment Strategy

Why systems run in several environments and how to design them: the purpose, users, data and fidelity of local, dev, test, staging and production (plus ephemeral preview environments); the twelve-factor separation of build and config; configuration layering and validation at startup in Spring Boot, Go, Rust and TypeScript; secret isolation with separate cloud accounts, workload identity and External Secrets; data isolation — why production data doesn't belong in lower environments, synthetic data, and deterministic masking; promotion with approvals and protection rules; production parity and its three gaps; Terraform and Kustomize layouts per environment; a parity checker that diffs environments; and TiffinBox's environment map.

20 topics · ~22 min read · 31-question quiz
Updated Suggest a correction

Start here: dev, staging and production

An environment is a complete, separate copy of the system where code runs: your laptop (dev), shared test environments (staging, QA, previews) and production, where real users and real money are. Separate environments let you try changes without risking customers, but only if they're set up so that what passed in staging is exactly what reaches production.

Three rules that do most of the work

  1. Build once, promote the same artefact. Build the container image or package once, then deploy that exact file to staging and production, identified by its hash. Rebuilding per environment risks shipping something you never tested. The lab built the same Python package twice from identical code and got two different hashes (timestamps inside the archive); pinning the build timestamp made the hashes identical.
  2. Same code, different configuration. Everything that differs between environments (database addresses, feature flags, timeouts) is configuration, layered (defaults → environment file → environment variables) and validated at start-up. In the lab, production refused to start because a payment key was missing and debug mode was on: far better than starting and failing on the first customer's payment.
  3. Secrets never live in code or images. They come from a secrets manager at run time, scoped per environment. The lab's secret scanner found 1 secret in the current files and 3 in the git history, including two that had been "removed" in a later commit; deleting a file doesn't delete it from history, so leaked keys must be revoked.

How deep to go in environment strategy

Volume 17 defines six mastery levels; for environment strategy they look like this:

Level You can…
L1 explain dev/staging/prod, build-once promotion and config vs code
L2 set up layered, validated configuration and secrets injection for a service
L3 design promotion pipelines with approvals, reproducible builds and data isolation
L4 find environment drift and config/secret mistakes behind failed releases
L5 design an organisation's environment map, preview environments and access controls
L6 run environment platforms at scale with cost controls and compliance

Why more than one environment

Production is where users are and where mistakes cost money and trust. Every other environment exists to find problems earlier and more cheaply, with a trade-off: the closer an environment is to production (same scale, same data shape, same infrastructure), the more problems it catches, and the more it costs and the slower it is to change. An environment strategy picks a small set of environments, each with a clear purpose, and moves one immutable artefact through them.

Environment Purpose Who uses it Data Fidelity to prod Lifetime
Local Fast inner loop: write, run, debug One developer Seeded fixtures Low–medium (containers for deps) Always
Preview (ephemeral) Review a pull request running Author, reviewers, PM/design Seeded fixtures Medium Per PR, minutes–days
Dev / integration Integrate main branch continuously Team Synthetic Medium Long-lived
Test / QA Automated suites (E2E, contract, performance smoke) CI, QA Synthetic, reset per run Medium Long-lived or per run
Staging / pre-prod Final rehearsal: same infra code, same deploy process CI/CD, on-call, release manager Synthetic or masked, production-sized High Long-lived
Production Users Everyone Real — Always

Small teams often collapse dev and test into one, and use previews instead of a shared dev. The minimum viable set for TiffinBox: local, preview, staging, production.

CI build oncesha256:ab12… preview (PR) staging production testschecks + approval values-preview values-staging values-prod secrets: dev acct secrets: stg acct secrets: prod acct same digest everywhere; only config and secrets differ
One artefact promoted through environments. CI builds and signs an image once; the same digest is deployed to preview, staging and production, while each environment supplies its own configuration and secrets from its own isolated store. Gates between environments are automated checks plus, for production, an approval.

Build versus config: the twelve-factor rule

The Twelve-Factor App (Heroku, 2011) states the principle: config is everything that varies between deploys (resource handles, credentials, per-deploy values like hostnames and feature flags), and it's strictly separated from code. A build is environment-agnostic; a release is build + config; you can deploy the same build anywhere by changing config. The test: could you open-source the code right now without leaking credentials? Corollaries:

  • No environment names in code paths: if (env == "prod") branches mean staging doesn't test production's code path. Express differences as config values (payments.baseUrl, features.bulkSkip=true), not environment checks.
  • No per-environment builds: rebuilding for production means production runs something staging never ran.
  • Config is validated at startup (fail fast): a missing or malformed value stops the pod from becoming ready, so a bad config never serves traffic and the rollout halts.

Configuration layering

Config comes from layers, later ones overriding earlier: defaults in code → base config file → environment overlay → environment variables / mounted files → (rarely) command-line flags. Keep the set of per-environment values small and visible.

# Spring Boot: application.yaml (defaults) + application-staging.yaml / -prod.yaml overlays via SPRING_PROFILES_ACTIVE
# application.yaml
tiffinbox:
  cutoff-local-time: "07:00"
  cutoff-zone: Asia/Kolkata
  payments:
    base-url: https://sandbox.payments.example
    timeout: 2s
  features:
    bulk-skip: false
spring:
  datasource:
    url: ${DB_URL}                 # injected per environment
    username: ${DB_USER}
    password: ${DB_PASSWORD}       # from a mounted secret, never in the file
    hikari: { maximum-pool-size: 10, connection-timeout: 1000 }
---
# application-prod.yaml
tiffinbox:
  payments:
    base-url: https://api.payments.example
  features:
    bulk-skip: true

Runtime config versus build-time config for SPAs. Baking API_BASE_URL into the JS bundle at build time violates "build once": you'd need one bundle per environment. Instead, serve a small config.json (or inject a window.__CONFIG__ script) per environment from the CDN, fetched at startup; the bundle is identical everywhere.

Feature flags are runtime config with targeting (per user, office, percentage), managed in a flag service (LaunchDarkly, Unleash, Flagsmith, flagd/OpenFeature) rather than redeploys. Treat flag changes as production changes: audited, reversible, and announced; remove stale flags (each is a branch in your code; chapter 192).

Secret isolation

Each environment's secrets are separate values in separate stores with separate access. A staging credential must not work in production, and a developer with staging access must not be able to read production secrets.

  • Separate cloud accounts/projects per environment (AWS Organizations with accounts tiffinbox-dev, -staging, -prod, plus -security and -backup; GCP projects; Azure subscriptions). Account boundaries are the strongest isolation clouds offer: IAM, networking, quotas and billing are separate, and a compromised dev credential can't touch production.
  • Workload identity: pods get cloud credentials by their Kubernetes service account (EKS Pod Identity / IRSA, GKE Workload Identity, Azure Workload Identity), short-lived and scoped, with no static keys in secrets at all where possible (e.g. RDS IAM authentication, S3 access by role).
  • Secret delivery: the External Secrets Operator syncs from AWS Secrets Manager / Vault / GCP Secret Manager into Kubernetes Secrets; or the Secrets Store CSI driver mounts them as files; Sealed Secrets or SOPS encrypt them in Git for GitOps.
  • CI credentials: OIDC federation from GitHub Actions to each cloud account, with trust policies restricted by repository, branch and GitHub environment (only the production environment's jobs can assume the production deploy role).
  • Rotation: automated where possible (Secrets Manager rotation for database passwords); apps re-read secrets or are restarted on change.
  • Encrypt Kubernetes Secrets at rest with a KMS key (they're base64, not encrypted, by default in etcd).
YAML
# External Secrets Operator: pull the DB password for this environment's cluster from its own account's store
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: { name: api-db, namespace: tiffinbox }
spec:
  refreshInterval: 1h
  secretStoreRef: { kind: ClusterSecretStore, name: aws-secrets-manager }   # IAM role scoped to this account
  target: { name: api-db, creationPolicy: Owner }
  data:
    - secretKey: DB_PASSWORD
      remoteRef: { key: tiffinbox/api/db, property: password }
JSON
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {
        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
        "token.actions.githubusercontent.com:sub": "repo:acme/tiffinbox:environment:production"
      }
    }
  }]
}

The trust policy above lets only jobs running in the production GitHub environment of acme/tiffinbox assume the production deploy role; a workflow on a fork, a feature branch or the staging environment gets a different sub claim and is refused.

Data isolation

Production data stays in production. Copying it into lower environments spreads personal data to places with weaker access controls, more people, and less monitoring; it is a common cause of breaches, and under data-protection law (India's DPDP Act 2023, GDPR) using personal data for testing usually lacks a lawful purpose. Lower environments use:

  • Synthetic data: generated to match production's shapes and distributions (row counts, skew: a few offices with hundreds of subscribers; edge cases deliberately included). Generators: Faker-based scripts, SQL generate_series, tools like Synthea (healthcare) or Tonic/Gretel (commercial).
  • Masked/pseudonymised copies, when production shapes matter (performance tests of real query plans): copy in a secured pipeline that transforms PII before data leaves production's account, deterministically (the same input maps to the same output, so joins still work), irreversibly (keyed HMAC, not plain hashing: phone numbers have so little entropy that unsalted hashes are reversible by enumerating every number).
Python
# Deterministic, irreversible masking with a keyed HMAC; keeps joins and formats, removes identity
import hmac, hashlib

KEY = b"rotate-me-kept-in-prod-secret-store"         # lives only in the masking job's secret store

def pseudo(value: str, domain: str) -> bytes:
    return hmac.new(KEY, f"{domain}:{value}".encode(), hashlib.sha256).digest()

def mask_phone(e164: str) -> str:
    d = int.from_bytes(pseudo(e164, "phone")[:8], "big") % 10**9
    return f"+919{d:09d}"                                   # keeps the +91 9XXXXXXXXX shape

FIRST = ["Asha", "Ravi", "Meera", "Arjun", "Farah", "Kiran", "Vikram", "Lakshmi", "Imran", "Divya"]
def mask_name(name: str) -> str:
    return FIRST[pseudo(name, "name")[0] % len(FIRST)] + " " + pseudo(name, "surname").hex()[:4].upper()

rows = [("+919812345678", "Harsha Reddy"), ("+919812345678", "Harsha Reddy"), ("+919900011122", "Farah Khan")]
for phone, name in rows:
    print(mask_phone(phone), "|", mask_name(name))
# Why not plain SHA-256? Indian mobile numbers are ~10^10 candidates: enumerable in hours on a GPU. Without KEY, HMAC isn't.
Text
+919209027485 | Arjun 2ACE
+919209027485 | Arjun 2ACE
+919395173657 | Ravi F784

(Your masked values differ unless you use the same key; the point is that the same input always produces the same output, and nobody without the key can go back.) Also mask free text (delivery notes often contain names and phone numbers), drop columns you don't need, and remember quasi-identifiers: an office + floor + plan can identify a person even with names masked.

Deployment approvals and promotion

Promotion moves a verified release to the next environment. Patterns:

  • Automatic to staging on merge to main (after CI).
  • Gated to production: automated checks (staging smoke tests, synthetic checks, no active incidents, outside freeze windows) and, where required, a human approval. GitHub environments with protection rules (required reviewers, wait timers, branch restrictions, custom deployment protection rules calling an external check), GitLab protected environments, Argo CD sync windows, or a release-manager role in Spinnaker/Harness.
  • Separation of duties for regulated contexts (payments: PCI DSS; SOC 2 change management): the person who wrote a change isn't the only one approving its production deploy, and the approval is recorded.
  • Continuous deployment (every green main goes to production automatically) is the goal for mature teams: approvals are replaced by strong automated checks and progressive delivery, which is safer than a human glancing at a diff at 5 p.m.
YAML
# .github/workflows/promote-prod.yml — promote the SAME digest that passed staging; requires approval
name: promote-prod
on:
  workflow_dispatch:
    inputs: { digest: { description: "image digest verified in staging", required: true } }
jobs:
  promote:
    runs-on: ubuntu-latest
    environment: production            # protection rules: 1 required reviewer, main only, freeze-window check
    permissions: { contents: write, id-token: write }
    steps:
      - uses: actions/checkout@v4
      - name: Verify the digest ran in staging and is signed
        run: |
          grep -q "${{ inputs.digest }}" deploy/envs/staging/values.yaml
          cosign verify ghcr.io/acme/api@${{ inputs.digest }} \
            --certificate-identity-regexp 'https://github.com/acme/tiffinbox/.github/workflows/ci-cd.yml@refs/heads/main' \
            --certificate-oidc-issuer https://token.actions.githubusercontent.com
      - name: Bump production (Argo CD syncs, Argo Rollouts canaries)
        run: |
          yq -i '.image.digest = "${{ inputs.digest }}"' deploy/envs/prod/values.yaml
          git commit -am "prod → ${{ inputs.digest }}" && git push

Production parity

Twelve-factor's dev/prod parity names three gaps to keep small:

  1. Time gap: code written today reaches production weeks later. Close it with continuous delivery: small changes shipped daily.
  2. Personnel gap: developers write, ops deploy. Close it with "you build it, you run it": the team deploys and is on call.
  3. Tools gap: SQLite locally, PostgreSQL in production; an in-memory queue locally, SQS in production. Close it with the same backing services everywhere, run locally in containers (Docker Compose, Testcontainers, LocalStack for AWS APIs). Differences in version matter too: Postgres 16 in production means 16 locally.

Staging specifically should share production's infrastructure code (the same Terraform modules with different variables), the same deploy mechanism (the same Argo CD + Rollouts definitions), the same topology (multi-AZ, the gateway, the CDN), and production-like data volume, scaled down only where cost forces it, and with differences documented. Things that legitimately differ: scale (replica counts, instance sizes), third-party endpoints (sandbox payment provider), data (synthetic), and access (broader for engineers in staging).

YAML
# docker-compose.yaml — local environment with the same backing services and versions as production
services:
  postgres:
    image: postgres:16.10
    environment: { POSTGRES_PASSWORD: local, POSTGRES_DB: tiffinbox }
    ports: ["5432:5432"]
    healthcheck: { test: ["CMD", "pg_isready", "-U", "postgres"], interval: 2s, retries: 30 }
  redis:
    image: valkey/valkey:8
    ports: ["6379:6379"]
  localstack:                          # SQS + S3 emulation
    image: localstack/localstack:4
    environment: { SERVICES: "sqs,s3" }
    ports: ["4566:4566"]
  api:
    build: ./api
    environment:
      SPRING_PROFILES_ACTIVE: local
      DB_URL: jdbc:postgresql://postgres:5432/tiffinbox
      DB_USER: postgres
      DB_PASSWORD: local
    depends_on: { postgres: { condition: service_healthy } }
    ports: ["8080:8080"]

A parity checker

Make drift visible: render each environment's effective configuration (Helm template or Kustomize build output) and diff the keys that should match.

Python
# parity.py — compare environments' effective settings; flag unexpected differences
staging = {"postgres_version": "16.10", "replicas_min": 2, "zones": 3, "pdb": True, "hpa": True,
           "gateway": "envoy-gateway 1.5", "otel_sampling": 0.2, "payments": "sandbox", "instance": "m7g.large",
           "network_policies": True, "rollout": "canary"}
prod    = {"postgres_version": "16.11", "replicas_min": 3, "zones": 3, "pdb": True, "hpa": True,
           "gateway": "envoy-gateway 1.5", "otel_sampling": 0.05, "payments": "live", "instance": "m7g.xlarge",
           "network_policies": True, "rollout": "canary"}
EXPECTED_TO_DIFFER = {"replicas_min", "payments", "instance", "otel_sampling"}   # documented, legitimate

drift = {k: (staging.get(k), prod.get(k)) for k in staging.keys() | prod.keys()
         if staging.get(k) != prod.get(k) and k not in EXPECTED_TO_DIFFER}
for k, (s, p) in sorted(drift.items()):
    print(f"DRIFT {k}: staging={s} prod={p}")
print("documented differences:", sorted(EXPECTED_TO_DIFFER))
# DRIFT postgres_version: staging=16.10 prod=16.11
# documented differences: ['instance', 'otel_sampling', 'payments', 'replicas_min']

The drift (production got a minor-version upgrade staging didn't) is exactly what parity checks exist for: upgrades must go through staging first.

Infrastructure layout per environment

Terraform: reusable modules (network, cluster, database) instantiated by per-environment root modules (separate state files and backends, in separate accounts). Avoid one state for all environments (a mistake in a plan could touch production) and be careful with workspaces for environments (same code, but easy to apply to the wrong one; separate directories are more explicit).

Text
infra/terraform/
├── modules/
│   ├── network/        VPC, subnets in 3 AZs, NAT, endpoints
│   ├── eks/            cluster, node groups, pod identity, add-ons
│   ├── postgres/       RDS PostgreSQL Multi-AZ, parameter group, backups, PITR
│   └── edge/           CloudFront, WAF, certificates, Route 53 records
└── envs/
    ├── staging/        main.tf (module calls with staging sizes), backend.tf (state in staging account)
    └── prod/           main.tf (module calls with prod sizes),    backend.tf (state in prod account)
HCL
# infra/terraform/envs/prod/main.tf — same modules as staging; only inputs differ
module "postgres" {
  source                  = "../../modules/postgres"
  name                    = "tiffinbox-prod"
  engine_version          = "16.11"
  instance_class          = "db.r7g.large"
  multi_az                = true
  backup_retention_days   = 35
  deletion_protection     = true
  performance_insights    = true
}

Kubernetes manifests: a Helm chart with per-environment values files (chapter 187's deploy/envs/), or Kustomize base + overlays:

YAML
# deploy/kustomize/overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: [../../base]
namespace: tiffinbox
images:
  - name: ghcr.io/acme/api
    digest: sha256:ab12cd34ef56...     # bumped by the promotion workflow
patches:
  - target: { kind: HorizontalPodAutoscaler, name: api }
    patch: |
      - { op: replace, path: /spec/minReplicas, value: 3 }
      - { op: replace, path: /spec/maxReplicas, value: 12 }
configMapGenerator:
  - name: api-config
    behavior: merge
    literals: [SPRING_PROFILES_ACTIVE=prod, FEATURE_BULK_SKIP=true]

Preview environments

An ephemeral environment per pull request (a namespace with the PR's images, seeded data, a URL like pr-412.preview.tiffinbox.in) lets reviewers, designers and PMs try changes before merge, and runs E2E tests against a real deployment. Argo CD's ApplicationSet pull-request generator, Vercel/Netlify for front ends, or tools like Okteto and Signadot create and destroy them. Keep them cheap: shared cluster, small resources, shared (or per-PR schema in a) database, TTL-based cleanup. They complement staging rather than replace it: staging tests the integrated main branch at production-like fidelity.

TiffinBox's environment map

Local Preview Staging Production
Account Laptop tiffinbox-dev tiffinbox-staging tiffinbox-prod
Cluster Docker Compose shared EKS, ns per PR EKS 3 AZs EKS 3 AZs
Postgres 16 container shared RDS, schema per PR RDS Multi-AZ, 16.x (same minor as prod first) RDS Multi-AZ 16.x
Data fixtures fixtures synthetic, production-sized (60k subscribers) real
Payments stub sandbox sandbox live
Deploy docker compose up ApplicationSet on PR open auto on main approved promotion of staging's digest; canary
Access developer team team (read), CI (write) CI only (write); break-glass for humans, audited
Cost / month (est.) 0 low (scale-to-zero) about a third of prod —

Lab: artefacts, configuration and secrets across environments

Setup. On the lab machine: pip/setuptools wheel builds, GNU tar, Pydantic 2.13 for configuration validation, git, and gitleaks 8.21.2 (downloaded from its GitHub release). The "secrets" planted in the test repository are fake values with realistic formats.

Experiment 1: build once, or build again?

Build SHA-256 (first 16 hex) of build 1 of build 2
wheel from identical source, 2 s apart c7e5a499b47b1a67 1b2bc8d576d10450
same, with SOURCE_DATE_EPOCH=1700000000 66d06f88cb1ff7d6 66d06f88cb1ff7d6
tar of identical files after a touch cdd15bd2d0b54f2e 306f2f5dfca499ab
tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner 19b39f219ec53add 19b39f219ec53add

Unpinned builds differed although the code didn't; normalised builds matched bit for bit. Two consequences: if you rebuild per environment, you can't prove production runs what staging tested (and with unpinned dependencies, it may not); and reproducible builds let anyone verify an artefact came from the claimed source (Volume 10). Promote by digest (image@sha256:…), never by a mutable tag.

Experiment 2: layered configuration that refuses bad values

Layers: defaults → per-environment file → APP_* environment variables (later wins). A Pydantic Settings model validates the result at start-up: environment name, required database_url, a payment_api_key of at least 20 characters, a timeout between 0 and 30 s, and "debug must be off in prod".

Run dev staging prod
files only starts (debug on) refuses: payment_api_key: Field required refuses: payment_api_key: Field required; debug: debug must be off in prod
+ secret from the secrets manager as APP_PAYMENT_API_KEY, APP_DEBUG=false starts starts starts

The production file had debug: true left in by accident; validation caught it before any traffic. Validation at start-up turns configuration errors into failed deploys (visible, automatically rolled back by readiness checks) instead of incidents.

Experiment 3: secrets in a repository

A test repository: commit 1 adds deploy.ini with AWS-style credentials; commit 2 deletes it; commit 3 adds pay.js with a Stripe-style live key; commit 4 adds notes.txt with password = "hunter2".

Scan Findings
gitleaks dir . (current files) 1: stripe-access-token in pay.js
gitleaks git . (all history) 3: the Stripe key, plus aws-access-token and generic-api-key in the deleted deploy.ini
  • Deleting a file in a later commit left both AWS credentials in history, available to anyone with a clone. Scan history, not just the tree; on a finding, revoke and rotate first, then clean history.
  • password = "hunter2" wasn't reported: short, low-entropy secrets slip past pattern and entropy rules. Scanners are a net, not a guarantee; the real control is that secrets never enter repositories (secrets manager, pre-commit hooks, push protection).

Try it yourself

  1. Build a container image twice with your usual Dockerfile and compare digests; then make it reproducible.
  2. Add a staging vs prod diff check to CI that lists configuration keys present in one environment but not the other.
  3. Install gitleaks as a pre-commit hook and try to commit the Stripe key.
  4. Inject a secret from a local Vault or SOPS-encrypted file instead of an environment variable and compare the operational trade-offs.

Revision sheet: environment strategy

Key ideas

  • Environments isolate risk: dev, CI, preview, staging/pre-prod, production (plus sandbox, perf, DR as needed).
  • Twelve-factor: one codebase, build once, configuration in the environment; promote immutable artefacts by digest.
  • Configuration layering with a typed schema validated at start-up; no environment-specific code branches.
  • Secrets: a secrets manager per environment, short-lived credentials, least privilege, rotation, scanning and push protection.
  • Data isolation: synthetic or masked data outside production; tightly controlled exceptions.
  • Promotion and approvals: automated gates, manual approval for production where needed, audit trail.
  • Parity: same versions, same topology shape, infrastructure as code per environment.
  • Preview environments per pull request, with automatic teardown and cost limits.

Numbers to remember

  • Lab: identical source → different wheel hashes until SOURCE_DATE_EPOCH was pinned.
  • Lab: validation stopped prod with a missing key and debug on.
  • Lab: gitleaks found 1 secret in the tree, 3 in history; missed a low-entropy password.

Pitfalls

  • Rebuilding per environment; deploying mutable tags like latest.
  • if env == "prod" branches in code.
  • Secrets in images, repos, CI logs or chat.
  • Production data copied to staging casually.
  • Staging that has drifted from production.

Glossary

  • Artefact promotion: moving one built artefact through environments.
  • Image digest: content hash identifying an exact image.
  • Reproducible build: identical inputs produce bit-identical outputs.
  • Configuration drift: unintended differences between environments.
  • Push protection: blocking pushes that contain detected secrets.