Subscribe

Avoiding goose migration version collisions across parallel branches

Two branches picked the same goose migration version twice in two days. Here is what goose does with duplicate and out-of-order versions, the CI check I use to catch both before merge, and naming habits that stop it happening.

Avoiding goose migration version collisions across parallel branches

Our backend at work uses goose for Postgres migrations, with timestamp versions. Timestamps are supposed to make collisions impossible across branches. They didn't, because we were typing them by hand. In the last week of October two branches picked the same version, and the next day it happened again with a different pair.

In this blog we will look at what goose actually does with a duplicate or out-of-order version (I ran each case), a small CI check that catches both before the merge, and the naming habits that stop it from happening at all.

A folder called migratons

Small aside first. Our migrations folder is called migratons. Yes, missing an "i". It's been that way since the first commit, and by now the Dockerfile copies it, the one-off migration task in every deploy workflow points goose at it, and the code review config mentions it. Renaming it would touch all of that for zero benefit, so it stays, and there is a note in the repo telling people not to "fix" it.

That's why every script in this post takes the directory as an argument. Don't hardcode migrations/, someone's folder is always spelled differently.

What happened

Look at our migration file names and you'll see a pattern: 200 of the 412 versions end in four zeros, like 120000 or 130000. Round times, typed by hand. 20261027120000_something.sql means "27 October, noon", and noon is a popular time.

On 27 October a big feature branch and a hotfix branch each added a migration called 20261027120000_<name>.sql. Both merged towards the same environment branch. The git history doesn't say what caught it first, only that ten minutes after the merge a teammate renamed the second file to 20261027130000 with the commit message "rename ... migration to unique goose version".

The next afternoon a migration landed on our staging branch with version 20261028120000. Another branch had the same version waiting. Two minutes after merging staging into that branch, the same rename: 120000 to 130000, so it would run after the one already on staging.

Both was fixed quickly, nothing lost. But twice in two days is a pattern.

What goose does with a duplicate

I wanted to see the failure for real, so I made a scratch folder with goose v3.30.1 and the sqlite3 driver (built into the goose binary, so no database needed). Two files, same version:

goose -dir migratons sqlite3 ./dev.db up
panic: goose: duplicate version 20261027120000 detected:
    migratons/20261027120000_portfolio.sql
    migratons/20261027120000_documents.sql

goroutine 1 [running]:
github.com/pressly/goose/v3.Migrations.Less(...)

A panic, from inside the sort, with a stack trace. Not pretty, but at least it's loud and nothing runs. If your migrations run as a one-off task before the deploy (I wrote about that setup in running goose migrations as a one-off ECS task), that task fails and the deploy should stop there.

What goose does with an older version

The second case is sneakier. Your branch has 20261028130000, and it already ran on a dev database. Then main brings in 20261028120000, which is older:

goose run: error: found 1 missing migrations before current version 20261028130000:
    version 20261028120000: migratons/20261028120000_plans.sql

goose status shows it as Pending in the middle of applied ones. goose refuses by default itself, which is the right call: the two migrations were written without knowing about each other, and running them in a different order on each database is how schemas drift.

There's a flag to push through anyway:

goose -dir migratons -allow-missing sqlite3 ./dev.db up
OK   20261028120000_plans.sql (403.63µs)
goose: successfully migrated database to version: 20261028120000

It's useful on a dev box only, when you know the two are independent. I wouldn't put it in a deploy pipeline. It turns a loud error into silent ordering differences between environments.

Renaming is only safe before it runs

Both of our fixes were renames, and that was fine because the renamed files hadn't run anywhere that mattered yet. See, after a migration has run, renaming it is a different story. goose tracks versions. It doesn't care about file names. So the database still has the old version recorded, and the new name looks like a fresh pending migration:

goose run: ERROR 20261028140000_bank_hidden.sql: failed to run SQL migration: failed to execute SQL query "ALTER TABLE users ADD COLUMN hidden INTEGER;": SQL logic error: duplicate column name: hidden (1)

That's from renaming an applied file in my scratch folder. On Postgres you'd get "column already exists" instead. So the rule is simple: a migration that is on main is never renamed, edited or deleted. If it's wrong, add a new one.

The CI check

Four checks, in plain bash, comparing the PR against its base branch:

  1. File names match YYYYMMDDHHMMSS_snake_case.sql.
  2. No two files share a version.
  3. No migration that exists on the base branch was renamed, deleted or edited.
  4. Every new migration sorts after the newest one already on the base branch.
#!/usr/bin/env bash
# usage: check-migrations.sh <migrations dir> <base ref>
set -euo pipefail

dir=${1:?migrations dir}
base=${2:?base ref, e.g. origin/main}
fail=0

versions() { # print the version of every migration file name read on stdin
  sed -n -E 's#^(.*/)?([0-9]+)_[^/]*\.(sql|go)$#\2#p'
}

bad=$(find "$dir" -maxdepth 1 -type f -name '*.sql' -exec basename {} \; |
  grep -Ev '^[0-9]{14}_[a-z0-9_]+\.sql$' || true)
if [ -n "$bad" ]; then
  echo "::error::bad migration file names (want YYYYMMDDHHMMSS_name.sql):"
  echo "$bad"
  fail=1
fi

dups=$(find "$dir" -maxdepth 1 -type f -name '*.sql' | versions | sort | uniq -d)
if [ -n "$dups" ]; then
  for v in $dups; do
    echo "::error::duplicate goose version $v:"
    find "$dir" -maxdepth 1 -name "${v}_*"
  done
  fail=1
fi

touched=$(git diff --name-status --diff-filter=DRM "$base"...HEAD -- "$dir/")
if [ -n "$touched" ]; then
  echo "::error::existing migrations changed (add a new migration instead):"
  echo "$touched"
  fail=1
fi

latest=$(git ls-tree --name-only "$base" -- "$dir/" | versions | sort -n | tail -1)
latest=${latest:-0}
for f in $(git diff --name-only --diff-filter=A "$base"...HEAD -- "$dir/"); do
  v=$(echo "$f" | versions)
  [ -z "$v" ] && continue
  if [ "$v" -le "$latest" ]; then
    echo "::error file=$f::version $v is not after $latest, the newest on $base. Rename it with a new timestamp."
    fail=1
  fi
done

[ "$fail" -eq 0 ] && echo "migrations ok (newest on $base: $latest)"
exit "$fail"

Check 4 is the one that actually catches our October case early. It fires even before the branch has main merged in, because it compares against the tip of the base branch, not the merge base. I replayed the story in a scratch git repo. The portfolio branch, before merging main:

::error file=migrations/20261027120000_portfolio.sql::version 20261027120000 is not after 20261027120000, the newest on main. Rename it with a new timestamp.

After merging main, the duplicate check joins in. After the rename to 130000, it prints migrations ok. And when I tried renaming a file that was already on main, check 3 said:

::error::existing migrations changed (add a new migration instead):
R100    migrations/20261027120000_documents.sql migrations/20261027110000_documents.sql

git diff base...HEAD with three dots diffs against the merge base, so a file your branch adds and then renames shows up as a plain add. Only files already on the base branch count as "renamed". That's what lets the fix in our story pass.

The ::error file=...:: lines are GitHub Actions workflow commands, they show up as annotations on the PR.

The workflow

name: migrations

on:
  pull_request:
    paths:
      - 'migrations/**'

permissions:
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18-alpine
        env:
          POSTGRES_PASSWORD: drill
          POSTGRES_DB: drill
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - name: Check names, duplicates and order
        run: ./ci/check-migrations.sh migrations "origin/${GITHUB_BASE_REF}"

      - uses: actions/setup-go@v7
        with:
          go-version: '1.27.x'

      - name: Up and down on an empty database
        env:
          GOOSE_DRIVER: postgres
          GOOSE_DBSTRING: postgres://postgres:drill@localhost:5432/drill?sslmode=disable
          GOOSE_MIGRATION_DIR: migrations
        run: |
          go install github.com/pressly/goose/v3/cmd/goose@v3.30.1
          goose up
          goose down-to 0
          goose up

fetch-depth: 0 is needed, otherwise origin/main isn't in the clone and the git commands fail. The second step is a bonus: up, all the way down, up again, on a throwaway Postgres. I ran the same three commands locally against postgres:18-alpine (18.7) with three sample migrations and it went clean. It catches a broken -- +goose Down long before you need it in a hurry. actionlint was happy with the file.

Make the job a required check, and change migrations to whatever your folder is called. Mine needs migratons.

Naming so it doesn't happen

The check catches it, but better not to need it.

Use goose create and stop typing versions. It uses the current UTC time down to the second:

goose -dir migratons create add_hidden_flag sql
Created new file: migratons/20261119064647_add_hidden_flag.sql

(I ran that at 12:16 IST, hence 06:46 in the name.) Two people would have to run it in the same second to collide. The order problem is still there though, a branch that sits for a week will have an older timestamp than whatever merged meanwhile. Check 4 handles that, the fix is to run goose create again and move your SQL into the new file.

goose also supports sequential versions (00001_, 00002_) with -s, and goose fix converts timestamped files to the next sequential numbers. The idea is timestamps on branches, then goose fix once on main. That's a fine setup for a new repo. On an existing repo full of applied timestamp migrations, don't run goose fix, it renames every one of them, and we just saw what goose does with a renamed applied migration.

So my advice is dull: goose create only, and a check like this one in CI. Same as most migration problems, really. I covered a related angle in database migration and version control for multiple schema multi-tenant systems a while back.