Shipping safely
Most migration outages are not caused by the change itself. They are caused by what the change waits for, and everything that then waits behind it. This page starts there, and then sets out what to check, when.
The queue behind a lock
Picture a reporting query that holds a transaction open on billing.invoice for a few seconds. A migration starts: alter table billing.invoice add column note text. It needs an ACCESS EXCLUSIVE lock, which conflicts with the report's, so it waits. That part is fine.
Then a customer checks out, and the checkout reads the invoice table. Its lock does not conflict with the report's at all. But PostgreSQL grants locks in order, and the alter is ahead in the queue. So the checkout waits too. So does every query on that table after it, for as long as the report runs.
Here it is on the example database, three sessions, captured from pg_stat_activity:
session | waiting_on | query
-----------+------------+---------------------------------------------------
report | Timeout | begin; select count(*) from billing.invoice; selec
migration | Lock | alter table billing.invoice add column note text
checkout | Lock | select count(*) from billing.invoice
The alter itself would take a millisecond. The outage is the wait. On a busy table, a few seconds of it means a pile of connections, timeouts in the application, and a pager going off.
The fix is to make the migration give up quickly:
$ psql -c "set lock_timeout to '50ms'" -c "alter table billing.invoice add column note2 text"
SET
ERROR: canceling statement due to lock timeout
After 50 ms in the queue the alter leaves it, and the checkout behind it goes through. Every create-migration template starts with that setting, and sqiff's migrations do too when they use the templates.
lock_timeout limits how long a statement waits for a lock. Once it has the lock, it holds it until the transaction ends. A table rewrite that gets its lock in 10 ms still blocks the table for as long as the rewrite takes. That is why sqiff prints hazards and sqint reports rewrites: the timeout cannot help with those.
Deploying with psql-retry
A migration that gives up has not failed; it has found a bad moment. The right response is to wait a little and try again, from outside the database. Retrying inside PL/pgSQL with an exception block opens a subtransaction per attempt, which brings its own problems on a busy server.
psql-retry runs psql, and when the output says canceling statement due to lock timeout, runs it again, with jittered backoff starting at 10 ms and capped at a minute, up to 500 times. Any other error stops it at once. Here is the same report holding its lock for three seconds, and the migration run through psql-retry:
$ PSQL_ARGS="-v ON_ERROR_STOP=1 -f add_note.sql" psql-retry SET psql:add_note.sql:2: ERROR: canceling statement due to lock timeout Retrying [2 / 500] SET psql:add_note.sql:2: ERROR: canceling statement due to lock timeout Retrying [3 / 500] … Retrying [9 / 500] SET ALTER TABLE
Each attempt waited at most 50 ms, so the checkout queries never queued for longer than that. When the report finished, the next attempt got its lock, and psql-retry exited 0. sqitch uses it through a small wrapper:
database/psql-retry.sh
#!/usr/bin/env bash
# sqitch calls this the way it calls psql. psql-retry reruns the script
# while it fails with "canceling statement due to lock timeout".
declare -a processed_args=()
for arg in "$@"; do
processed_args+=("$(printf "%q" "$arg")")
done
export PSQL_ARGS="${processed_args[*]}"
exec psql-retry
sqitch deploy --client database/psql-retry.sh "$PRODUCTION_TARGET"
Each retry runs the whole script again from the top, so every script must be safe to run again after it gave up part-way. The templates are written for that: a transaction around everything that can be in one, and if not exists, if exists and guards for what cannot, such as the concurrent index build, which refuses to continue if an earlier attempt left an invalid index.
Locally you can use plain psql. Use the wrapper whenever you want to exercise the production path.
Before a commit
Checks that need no database and take a second.
- sqint's static pass on staged deploy scripts.
- The plan only grows. No line of
sqitch.planthat exists onmasteris changed or removed. - Snapshots are not edited. A new
@tagfile is expected; a modified or deleted one is a mistake. - pgfmt on the SQL files you stage, except rework snapshots, so every file has one format.
- hasql-th-format --check, if you use hasql-th, so the SQL in quotes has one format.
.pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: sqint
name: sqint
entry: sqint
language: system
files: ^database/deploy/.*\.sql$
- id: pgfmt
name: pgfmt
entry: pgfmt
language: system
files: ^database/.*\.sql$
exclude: '@' # rework snapshots keep the text that was deployed
- id: plan-only-grows
name: sqitch.plan only grows
language: system
pass_filenames: false
files: ^database/sqitch.*\.plan$
entry: >-
sh -c '! git diff --cached -U0 master -- "database/sqitch*.plan"
| grep -E "^-[^-]"'
- id: snapshots-are-not-edited
name: rework snapshots are not edited
language: system
pass_filenames: false
files: '@'
entry: >-
sh -c 'files=$(git diff --cached --name-only --diff-filter=MD -- "database/*@*.sql");
[ -z "$files" ] || { echo "edited snapshots: $files"; exit 1; }'
On a pull request
These need a PostgreSQL. The order matters: build the schema master has, then apply the branch on top, the way production will.
- Deploy
master's plan into a scratch database. - Run sqint's dynamic pass. It deploys each new change in plan order, runs its statements in a rolled-back transaction while a second connection watches
pg_locks, asks the planner whether a cast defeats an index, and checks every SQL function after each change. It reports the locks a change really took, which the static pass can only infer. - Revert and deploy again.
sqitch rebase --ontothe base's last change runs every new revert script, then every deploy script a second time. - Check the queries of the branch against the result, with hasql-check if you use hasql-th.
- Run your tests, pgTAP or otherwise.
.github/workflows/database.yml (the database part; add your own build and tests)
name: database
on: pull_request
jobs:
migrations:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:18
env:
POSTGRES_PASSWORD: postgres
ports: ["5432:5432"]
env:
PGHOST: localhost
PGUSER: postgres
PGPASSWORD: postgres
PGDATABASE: postgres
TARGET: db:pg://postgres@localhost/postgres
SQITCH_TARGET: db:pg://postgres@localhost/postgres # sqint deploys to sqitch's default target
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: cachix/install-nix-action@v31
- run: nix profile install nixpkgs#sqitchPg github:kronor-io/sqint github:kronor-io/pgfmt
- name: Check the format
run: |
git diff --name-only --diff-filter=AM "origin/$GITHUB_BASE_REF" -- database \
| grep '\.sql$' | grep -v @ | xargs -r pgfmt --check
- name: Deploy the base branch
run: |
git worktree add ../base "origin/$GITHUB_BASE_REF"
(cd ../base && sqitch deploy "$TARGET")
baseline=$(awk '!/^[%#@]/ && NF { change = $1 } END { print change }' ../base/database/sqitch.plan)
echo "BASELINE=$baseline" >> "$GITHUB_ENV"
- name: Lint against the database
run: |
sqint --with-postgres "postgres://postgres:postgres@localhost/postgres" \
--baseline-change "$BASELINE" \
$(git diff --name-only --diff-filter=AM "origin/$GITHUB_BASE_REF" -- database/deploy)
- name: Revert and deploy again
run: |
sqitch deploy "$TARGET"
sqitch rebase -y --onto "$BASELINE" "$TARGET"
Reworks need sqint 0.1.1.0. Earlier releases find changes by name, which a rework makes ambiguous. If the branch reworks the same change master's plan ends with, they check nothing, without saying so; if a change is reworked more than once after the baseline, they stop with sqitch's "is ambiguous" error. 0.1.1.0 places the baseline using the sqitch registry and deploys earlier occurrences as change@tag.
sqint deploys the changes for real, so give it a throwaway database, and point both its PG* variables and SQITCH_TARGET at the same database as --with-postgres: sqint runs sqitch deploy against sqitch's default target, and a database named in sqitch.conf's target wins over PGDATABASE. Concurrent index builds cannot run in its rolled-back transaction; it reports them at INFO and leaves them to the static pass.
Before a deploy
The database migrates first, then the new code rolls out, so for a while the old code runs against the new schema. Check that it can:
# the commit running in production now git worktree add ../running "$DEPLOYED_SHA" # a scratch database with the new schema sqitch deploy "$TARGET" # the running code's queries, against it (cd ../running && find src -name '*.hs' -print0 | hasql-check --files0-from -)
A statement that fails to prepare here would fail in production during the rollout. Split the change: add the new thing now, remove the old one in a later release, once no running code uses it.
hasql-check covers Haskell services that use hasql-th. Other consumers, such as a GraphQL layer or a reporting tool, need their own version of this check.
The deploy
- Deploy the database with psql-retry as the client,
--mode changeso a failing change is reverted on its own and the ones before it stay. - Roll out the application.
- Remove what the old code needed in a later release.
Drift
Someone ran an alter by hand during an incident. To find out, compare production with what the deployed revision's plan builds:
sqiff diff --from "rev:$DEPLOYED_SHA" --to "host=replica.internal dbname=shop"
sqiff checks out that revision, deploys its plan into a scratch database started from your compose file and cached between runs, and compares the catalogs. Comparing with master instead would also report changes that are merged but not yet deployed. diff exits with 1 when there is a difference, so it can run on a schedule.
What the checks do not prove
| Check | Tells you | Does not tell you |
|---|---|---|
| sqint, static | Statements that take heavy locks, rewrite, or defeat indexes, by their shape | How big the table is, or whether a type change is free |
| sqint, dynamic | The locks a change really took, broken functions, confirmed index misses | How long anything takes on production data |
| Revert and redeploy | Reverts work, and deploys run twice cleanly | That a script resumes correctly after giving up half-way |
| hasql-check | Every hasql-th statement prepares against the schema | Anything about code that does not use hasql-th |
| sqiff hazards | What each step costs in locks, rewrites and lost data | Whether that cost is acceptable. That is your call |