All guides

Database migrations in a pipeline: expand, then contract

Expand and contract breaks a breaking schema change into three phases: add the new structure, move the application over, remove the old structure. The database change is then decoupled from the application deployment.

A wall covered in coloured sticky notes

The three phases

GitLab's developer documentation defines the expand and contract pattern. Every breaking change is broken down into three phases:

  • Expand. A breaking change is introduced keeping the software backward-compatible.
  • Migrate. Every consumer is switched over to the new implementation.
  • Contract. Backward compatibility is removed.

The same page shows why: during a deployment there is a long transition period with the old and the new application version on one schema. Its database example replaces a query that an index supports. Expand adds the new index, which the application ignores for now. Migrate deploys the new code, and only the new query runs. Contract removes the old index, which nothing uses anymore.

A column change, step by step

DORA's database change management page describes the parallel change pattern for a column. In this pattern you never mutate existing database objects. You add new structures alongside the old ones. Its example changes an address column into address_1 and address_2:

  1. Add the new columns and keep the old one. This can happen before the application deployment.
  2. Deploy an application version that reads the new columns if they are present and not null, and reads the old column otherwise.
  3. Have the application write to both the old and the new columns, which migrates the data lazily.

DORA names two results. The application can be rolled back with no database rollback, and the application deployment is decoupled from the database change. Database triggers are DORA's alternative for keeping the old and new columns synchronized.

Migrations as their own pipeline step

Three documented mechanisms run a migration command in a Kubernetes cluster.

  • A Job. A Job represents a one-off task that runs to completion and then stops. .spec.backoffLimit sets the number of retries before the Job is considered failed, and defaults to 6. Kubernetes also notes that the same program is sometimes started twice, even with parallelism 1, completions 1 and restartPolicy set to Never. Write the migration so that a second start does no harm.
  • A Helm hook. On an upgrade request, a pre-upgrade hook runs once the templates are rendered and before Helm updates any resource. A pre-install hook executes before any resources are created. When the hook is a Job, Helm waits until it runs to completion, and if the hook fails, the release fails. Hook resources are not managed with the release, so helm uninstall does not remove them.
  • An init container. Init containers are specified in the Pod specification and run to completion before the app containers start. A Pod cannot be Ready until all its init containers have succeeded. If one fails, the kubelet restarts it until it succeeds, unless the Pod's restartPolicy is Never. Kubernetes says init container code should be idempotent, because init containers can be restarted, retried or re-executed.

This is the hook example from the Helm documentation:

Text

apiVersion: batch/v1
kind: Job
metadata:
  name: "{{ .Release.Name }}"
  labels:
    app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
    app.kubernetes.io/instance: {{ .Release.Name | quote }}
    app.kubernetes.io/version: {{ .Chart.AppVersion }}
    helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
  annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-install
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded
spec:
  template:
    metadata:
      name: "{{ .Release.Name }}"
      labels:
        app.kubernetes.io/managed-by: {{ .Release.Service | quote }}
        app.kubernetes.io/instance: {{ .Release.Name | quote }}
        helm.sh/chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    spec:
      restartPolicy: Never
      containers:
      - name: post-install-job
        image: "alpine:3.3"
        command: ["/bin/sleep","{{ default "10" .Values.sleepyTime }}"]

For a migration, replace the image and the command with those of your migration tool, and set the hook to pre-install,pre-upgrade. One resource can implement several hooks, separated by commas. hook-succeeded deletes the Job after the hook has executed successfully.

Long locks on large PostgreSQL tables

ALTER TABLE acquires an ACCESS EXCLUSIVE lock unless its documentation explicitly notes another level for a subform. A standard CREATE INDEX locks out writes on the table until it is done. This script uses one setting and three statement forms from the PostgreSQL documentation:

SQL

SET lock_timeout = '5s';

ALTER TABLE customers ADD COLUMN address_1 text, ADD COLUMN address_2 text;

CREATE INDEX CONCURRENTLY customers_address_1_idx ON customers (address_1);

ALTER TABLE customers
  ADD CONSTRAINT customers_address_1_present CHECK (address_1 IS NOT NULL) NOT VALID;

ALTER TABLE customers VALIDATE CONSTRAINT customers_address_1_present;

The table, the names and the 5s are choices made for this example. Use your own.

  • lock_timeout aborts any statement that waits longer than the given time to acquire a lock. Zero, the default, disables the timeout. PostgreSQL does not recommend setting it in postgresql.conf, because it would affect all sessions. Set it in the migration's session.
  • CREATE INDEX CONCURRENTLY builds the index without taking locks that prevent concurrent inserts, updates or deletes. It scans the table twice, takes significantly longer, and cannot run inside a transaction block. If the build fails, it leaves behind an index marked INVALID. The recommended recovery is to drop the index and try again.
  • NOT VALID skips the scan of existing rows when a constraint is added. The constraint is still applied to subsequent inserts and updates. VALIDATE CONSTRAINT checks the existing rows later and acquires only a SHARE UPDATE EXCLUSIVE lock. It fails until every existing row satisfies the constraint.
  • Adding a column with no default, or with a non-volatile default, requires no rewrite of the table. Changing the type of a column rewrites the entire table and its indexes, apart from the exceptions the ALTER TABLE page lists.

Checks before a migration merges

  • Test every schema change against a production-like data set, as DORA advises.
  • Keep all schema changes in version control with the application code, and use a tool that records which changes have run against which environments. DORA's list of migration tools includes Flyway, Liquibase and Alembic.
  • Set lock_timeout in the session of every migration that takes a lock on a live table.
  • Build indexes on live tables with CONCURRENTLY, outside a transaction block.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides