Workflow: Expand, Contract, Roll Forward

Three Rules

The platform’s migrations follow three rules. Everything else in this chapter is how they are kept.

  1. Only forward. A migration is never undone by a reverse script. A mistake is fixed by the next migration - roll forward. The backend has no .down.sql files, on purpose: a down script can rename a column back, but it cannot bring back the data a DROP removed, and it is the least tested code a team owns.
  2. Expand, then contract. A migration only adds - a table, a nullable column, an index - or relaxes. Removing or renaming something comes later, as its own release, once no release you might roll back to still uses it.
  3. The previous release runs on the new schema. That is what the first two buy: a rollback is only an image change, and every row written since stays.

Expand and Contract, Step by Step

The story’s rename, done so that every step can be rolled back - four releases instead of one:

ReleaseMigrationCodeRollback to the previous release
1 - expandADD COLUMN login (nullable)writes username and login, reads usernamesafe: the old code ignores login
2 - backfillcopies username into login where it is emptyreads login, still writes bothsafe: release 1 reads username, which is still written
3 - stop usingusername may be empty (DROP NOT NULL)writes and reads only loginsafe: release 2 still finds both columns
4 - contractDROP COLUMN usernameunchangedsafe: release 3 no longer uses username

Each release is small, and each leaves a schema the one before it runs on. The contract step waits until you will not roll back past release 3 - days or weeks, not minutes. It is the only step that loses anything, and by then nothing reads what it removes.

A new feature is the simple case of the same rule: expand, write, then read. In the backend, migration 0002 added display_name - nullable, so the previous release, which never sets it, keeps inserting rows. The code writes it on every registration from the first day; returning it in responses is a separate switch, FEATURE_DISPLAY_NAME.

Expand works only if the previous code does not notice what was added - so queries name their columns. A SELECT * returns the new column too, and Go code that scans a fixed list of fields into a row with one more column fails. The backend’s queries list every column they read; INSERTs name theirs for the same reason.

Where Migrations Run

The migrations are SQL files built into the backend’s image (pkg/migrations/sql/0001_….up.sql, 0002_…), applied by the image itself: backend migrate. In Kubernetes it runs as an initContainer of every backend pod - the same image reference as the app, so migrations and the code that needs them always come from one build:

The backend Deployment - the migrate initContainer

Show deployment.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: backend
  labels:
    app: backend
    app.kubernetes.io/name: backend
    app.kubernetes.io/component: api
spec:
  # No spec.replicas: the HorizontalPodAutoscaler owns the replica count (hpa.yaml per environment,
  # minReplicas is the floor). A replicas value in Git makes Flux reset what the HPA scaled on every
  # reconcile. Existing clusters: run scripts/hpa-replicas-handover.sh once before this change.
  revisionHistoryLimit: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  selector:
    matchLabels:
      app: backend
  template:
    metadata:
      labels:
        app: backend
        app.kubernetes.io/name: backend
        app.kubernetes.io/component: api
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8080"
        prometheus.io/path: "/metrics"
    spec:
      # No <SERVICE>_PORT=tcp://... variables for the namespace's Services; KUBERNETES_SERVICE_* stay
      # (scripts/check-app-security.sh says why).
      enableServiceLinks: false
      # The backend never calls the Kubernetes API: no ServiceAccount token in the pod.
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        runAsGroup: 10001
        fsGroup: 10001
        seccompProfile:
          type: RuntimeDefault
      # Schema migrations before the app (Chapter 18): the same image reference as the app (the
      # overlay's images: transformer sets both tags; Kyverno verifies the digest each tag resolves to
      # at admission - a tag is not pinned, see Chapter 17) runs `backend migrate`, applies the migrations
      # embedded in it that the database lacks (golang-migrate, under a Postgres advisory lock) and exits.
      # It runs whenever a backend pod is created - rollout, reschedule, scale-out; with nothing pending
      # it only checks. The recovery point is the continuous WAL archive (Chapter 12), not a backup taken
      # here; a migration's pull request is merged only while that archive is healthy. The app then only
      # checks the schema version and refuses to start on one it cannot use. Migrations only expand:
      # the previous release keeps working on the new schema, so rolling back the image never needs
      # rolling back the data.
      initContainers:
      - name: migrate
        image: backend:latest  # name/tag set by the environment overlay (images: transformer)
        imagePullPolicy: IfNotPresent
        args: ["migrate"]
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 10001
          runAsGroup: 10001
          capabilities:
            drop:
              - ALL
        env:
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: app-postgres-app
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: app-postgres-app
              key: password
        - name: POSTGRES_HOST
          value: app-postgres-rw
        - name: POSTGRES_DB
          value: app
        resources:
          requests:
            cpu: 10m
            memory: 32Mi
          limits:
            cpu: 100m
            memory: 64Mi
      containers:
      - name: backend
        image: backend:latest  # name/tag set by the environment overlay (images: transformer)
        imagePullPolicy: IfNotPresent
        # Stopping, the pod is removed from the Service's endpoints and from Traefik - but not at once,
        # while the container already gets SIGTERM. The sleep keeps it serving until they have caught
        # up; then the app shuts down. Measured on kind (a rollout, ~115 requests/s): without it 14-25
        # failed requests (refused, or 502 from Traefik), with it 0-3 (Chapter 20). The kubelet's own
        # sleep - no shell in the image needed. 5 s + the app's shutdown fit in the 30 s grace period.
        lifecycle:
          preStop:
            sleep:
              seconds: 5
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          runAsNonRoot: true
          runAsUser: 10001
          runAsGroup: 10001
          capabilities:
            drop:
              - ALL
        ports:
        - containerPort: 8080
          name: http
          protocol: TCP
        env:
        - name: PORT
          value: "8080"
        - name: NAMESPACE
          value: "${NAMESPACE}"
        - name: ENVIRONMENT
          value: "${ENVIRONMENT}"
        - name: LOG_LEVEL
          value: "${LOG_LEVEL}"
        - name: SERVICE_NAME
          value: "backend"
        # No SERVICE_VERSION: the backend reports the version baked into the image (the same as
        # /version), so every span says which release produced it.
        - name: DEPLOYMENT_ENVIRONMENT
          value: "${ENVIRONMENT}"
        # Where a span came from: the cluster, the namespace (= the environment) and the pod - set from
        # the downward API, so traces can be filtered per environment and per pod.
        - name: K8S_NAMESPACE_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: K8S_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: OTEL_RESOURCE_ATTRIBUTES
          value: "k8s.cluster.name=${cluster_name},k8s.namespace.name=$(K8S_NAMESPACE_NAME),k8s.pod.name=$(K8S_POD_NAME)"
        - name: UPTRACE_DSN
          valueFrom:
            secretKeyRef:
              name: backend-secrets
              key: uptrace-dsn
        - name: JWT_SECRET
          valueFrom:
            secretKeyRef:
              name: backend-secrets
              key: jwt-secret
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: app-postgres-app
              key: username
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: app-postgres-app
              key: password
        - name: POSTGRES_HOST
          value: app-postgres-rw
        - name: POSTGRES_DB
          value: app
        # Security switches (backend >= the 2026-09-27 hardening). Safe values here; an environment
        # overlay may only turn chaos on (develop, staging). scripts/check-app-security.sh enforces it.
        - name: CHAOS_ENABLED       # /panic + readiness/liveness toggles (still need a token)
          value: "false"
        - name: PPROF_ENABLED       # profiling listener on loopback; never on in Git
          value: "false"
        - name: AUTH_REGISTRATION_ENABLED
          value: "true"
        livenessProbe:
          httpGet:
            path: /livez
            port: http
          initialDelaySeconds: 15
          periodSeconds: 20
          timeoutSeconds: 5
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /readyz
            port: http
          initialDelaySeconds: 5
          periodSeconds: 10
          timeoutSeconds: 3
          failureThreshold: 3
        startupProbe:
          httpGet:
            path: /healthz
            port: http
          initialDelaySeconds: 0
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 30
        # The production values (staging gets the same; develop patches its own). Requests are what
        # the scheduler reserves and the quota counts; limits are the ceiling: memory over the limit
        # is OOMKilled, CPU over it is throttled. requests < limits makes the pod Burstable.
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
            ephemeral-storage: 64Mi
          limits:
            cpu: 250m
            memory: 256Mi
            ephemeral-storage: 128Mi
        volumeMounts:
        - name: tmp
          mountPath: /tmp
        - name: cache
          mountPath: /home/app/.cache
      volumes:
      # Every writable path is an emptyDir with a size limit. It is not a quota that stops the write:
      # the kubelet measures the volume on a schedule and evicts the pod once it is over the limit -
      # a very fast writer can still fill the node's disk before that. It bounds a slow leak and makes
      # the pod's budget explicit. /tmp holds request bodies Go buffers to disk - measured at 0 KB at
      # rest, so 64Mi leaves room for uploads.
      - name: tmp
        emptyDir:
          sizeLimit: 64Mi
      - name: cache
        emptyDir:
          sizeLimit: 10Mi
  • Before the app. The app container starts only after migrate exited successfully. A migration that fails leaves the pod in Init, the rollout stops there, and the previous pods are not replaced (Chapter 09). They are not untouched, though: they use the same database. A KubePodNotReady alert fires when a pod stays in Init for 15 minutes, and KubeDeploymentRolloutStuck when the rollout stops making progress. Both alerts come with the platform’s Prometheus rules. dirty itself is not a metric: the migrate log says it.
  • One file, one transaction. The backend sends each file to Postgres as a single query, and Postgres runs all of its statements as one transaction: a file that fails changes nothing. A statement that cannot run inside a transaction - CREATE INDEX CONCURRENTLY - goes into a file of its own, as its only statement: one statement is not a transaction block, two are, and Postgres refuses CONCURRENTLY inside one.
  • A short wait for table locks. An ALTER TABLE needs an exclusive lock on its table. While it waits for one - behind a long query of the running release - every later query on that table waits behind it: the previous pods stall without failing. So every file starts with SET LOCAL lock_timeout = '5s';, which lasts until the end of that file’s transaction. After 5 seconds the migration gives up and fails loudly; the release is retried when the table is quieter. The CONCURRENTLY file is the exception - the line would make it a transaction. It needs none: its lock does not block reads or writes, so its wait stalls nobody, and the connection’s 5-minute limit bounds it. A backend test checks both kinds of file.
  • Once, under a lock. Replicas that start together race for a Postgres advisory lock; one applies the migrations, the others wait and then find nothing to do. Only migrate containers wait for that lock, so its wait can be long - 5 minutes; a lock that is never released ends in an error, not a hang.
  • On every pod start. With nothing pending, migrate only reads the version and exits: schema already at version 2 (this build needs 2).
  • The rollback case. A schema newer than the image knows - the next release migrated, then this one was rolled back - is accepted when it is clean: schema 2 is newer than this build knows (1) - nothing to apply; this build runs on it (expand-only migrations).
  • A failed migration stops everything. golang-migrate marks the version dirty before it runs a file and clears the flag after; a file that fails leaves it set. migrate then refuses to continue and the app refuses to start. dirty says only that a migration started and did not finish - not what the schema looks like. With one transaction per file, a failed file usually changed nothing; a file that cannot run in a transaction, or a change made by hand, can leave it half-way. So a person compares the schema with the file, and the recorded version must match it - the migration’s own version if it is fully there, the one before it if nothing of it is - before it is marked clean (see the runbook).

At startup the app only checks: the database must be migrated, clean, and at least the version this build needs. Older - it refuses to start, with the reason in its log. Newer - it runs: expand-only migrations promise that it can.

A Kubernetes Job before the deploy is the common alternative (see the chapter’s context). It needs an ordering between the Job and the Deployment - in Flux, a separate Kustomization and dependsOn - and a new Job for every release. The initContainer needs none of that, at a price: it runs on every pod start, and a long migration holds the rollout in Init while it runs.

Feature Flags: Write First, Read Later

A flag separates deploying code from switching it on. The backend writes the display name from the release that added the column; FEATURE_DISPLAY_NAME decides only whether it is returned. Off again, and the feature is hidden - no new image, no schema change, no data lost. It is still a change that rolls the pods, as the next paragraph shows - fast and through Git, but not free.

In develop the flags are a configMapGenerator, not a plain ConfigMap:

configMapGenerator:
  - name: feature-flags
    literals:
      - FEATURE_DISPLAY_NAME=false

Kustomize appends a hash of the values to its name (feature-flags-8tk54httf2) and writes that name into the Deployment. Changing a flag changes the name, so Flux rolls the pods and they read the new value. A plain ConfigMap would change while every running pod kept the old value - until something else restarted it.

The Previous Release, Tested on the New Schema

Rule 3 is not a promise; CI checks it on every backend pull request. The job previous release on this schema (N-1):

  1. builds two binaries - the pull request’s and the base branch’s, the release now running;
  2. lets the previous release migrate an empty Postgres and register a user - data that exists before the migration, as in production;
  3. migrates with the pull request’s binary, starts it, and registers a user with everything the new release stores (a display name);
  4. runs the previous release’s migrate on that schema - it must succeed, or every pod of a rollback would hang in Init;
  5. starts the previous release’s app and logs in both users: the old rows survived the migration, and rows the new release wrote are readable by the old code.

A migration that renames, drops or tightens what the previous release uses fails here, before it merges - the story’s release would not have reached production.

What it does not check: “previous” is the base commit - one release back, what develop runs before the merge. A production that is several releases behind is rolled back further than that, so the rule has to hold for every release in between - one more reason to keep the contract step weeks behind the expand. And it exercises the users’ path, register and login; a release with more features would add a request for each one that reads the changed tables.

How This Platform Got Here - Twice the Hard Way

The release order. The first version of migration 0002 was merged as soon as it worked. Rehearsing the rollback on kind showed the problem: the release before it did not know the newer-schema case yet - its migrate stopped with no migration found for version 2, and every pod of a rollback would have stayed in Init. The new schema was harmless; the previous release’s migrate tool was not. 0002 was taken out again, and the releases were reordered: release A taught migrate to accept a newer clean schema, with no migration in it; release B brought 0002 back. Only from A on is a rollback after B an image change. The N-1 job already ran the previous release’s app on the new schema - and passed; it did not run the previous release’s migrate, which is what failed. Step 3 above was added in the same change, so the next one is caught in CI.

The flag that did nothing. FEATURE_DISPLAY_NAME=true reached the pod - its environment and /env said so - and the responses still had no display name. The configuration code read the variable and then built its final settings from the command-line flags, where the field was missing. Every test of the server built its settings directly, so none could see it. It was found by running this chapter’s lab, and fixed with a test that sets every setting and checks that none is dropped.

The lock that waited five minutes. The 5-minute bound on the advisory lock was set on the migration’s database connection - and so it applied to every lock a migration needed, including the table lock of an ALTER TABLE. A review of this chapter pointed out what that means: a migration queued behind one long query would have held every query of the running release on that table for up to five minutes, while the text said the previous pods “keep serving”. Now each file sets its own 5-second limit, and a backend test holds a table busy and checks that the migration gives up after about 5 seconds and leaves the schema unchanged.

The first two were found by running the change on a cluster, the way a learner would - not by reading the diff; the third by a review that asked what “keep serving” really meant.

Where a Point-in-Time Restore Fits

A migration needs no extra backup taken just before it: a base backup plus the continuous WAL archive after it (Chapter 12) can restore the database to any second since that backup. Both have to be there. A migration’s pull request is merged only when they are: the CloudNativePG cluster reports ContinuousArchiving=True, and none of PostgresWALArchivingFailing, PostgresNeverBackedUp and PostgresBackupTooOld is firing. A quiet archive is not a broken one - on an idle database the last archived segment can be hours old (Chapter 12). If a migration destroys data - a wrong UPDATE, a DROP too early - the restore goes into a separate cluster, to the second before the migration, and the lost rows are copied back from there into the live database. The live database is never replaced to undo a release: everything users wrote since would go with it.

What This Does Not Solve

  • Large tables. An ALTER TABLE that rewrites a table holds its lock for as long as the rewrite takes - the 5-second lock_timeout limits only the wait for it. A backfill of millions of rows is a job of its own, in batches. Online schema change tools exist for exactly this (see the chapter’s context); the backend’s tables are small enough not to need them.
  • Changes between several services that share one schema - each must run on the other’s previous release, which is one more reason for every service to own its data.

Instructions for Your AI Agent

The rules this chapter adds:

  1. Never write a down migration, and never change or delete a migration that was merged: a mistake is fixed by the next migration. The one exception is a migration that no database has recorded as clean - it failed everywhere it ran - see the runbook. Enforced by: the backend builds in only *.up.sql files; a test fails when the newest file and the version the code requires disagree; review.
  2. Every migration file starts with SET LOCAL lock_timeout = '5s'; - except a CONCURRENTLY statement, which is the only statement in its file, without that line. Enforced by: a backend test that checks every file for one of the two shapes.
  3. A migration only adds or relaxes. Removing, renaming or tightening a column, table or constraint is a contract step: its own release, after no release you might roll back to uses it. Enforced by: the CI job previous release on this schema (N-1) - the previous release must migrate, start, and log in its own and the new release’s users on the new schema.
  4. Never run ad hoc DDL by hand on a database that serves users - the one exception is finishing or undoing a migration left dirty, reviewed, as the runbook describes - and never restore over the live database to undo a release. A point-in-time restore goes into a separate cluster. Enforced by: instruction; scripts/postgres-restore-manifest.sh only creates a separate cluster (app-postgres-restore).
  5. Merge a pull request with a migration only while a restore to the second before it is possible: a base backup exists and the WAL archive is healthy. Enforced by: instruction; the cluster’s ContinuousArchiving condition and the alerts PostgresWALArchivingFailing, PostgresNeverBackedUp, PostgresBackupTooOld (Chapter 12).

This builds on: Version Promotion (Chapter 10) - a rollback is one line in Git - and Backup & Restore (Chapter 12): the WAL archive and the side-by-side restore. This enables: Progressive Delivery (Chapter 19) - a canary runs the new and the previous release side by side, on one schema: exactly what this chapter makes safe.