Skip to content

Make concurrent migrations safe on PostgreSQL - #3245

Merged
Huliiiiii merged 8 commits into
SeaQL:masterfrom
patrick-immometrica:migration-concurrent-up
Nov 16, 2026
Merged

Huliiiiii merged 8 commits into
SeaQL:masterfrom
patrick-immometrica:migration-concurrent-up

Conversation

@patrick-immometrica

@patrick-immometrica patrick-immometrica commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Several app instances that each run Migrator::up on start race: they all see the same pending migrations and run them. The losers fail with a duplicate key on pg_type (CREATE TABLE) or on seaql_migrations, and a migration that isn't idempotent can run twice. install() hits the same race on CREATE TABLE IF NOT EXISTS seaql_migrations.

The fix, on Postgres:

  • Each migration's transaction takes pg_advisory_xact_lock and then reads the migrations table again. A migration another process applied (or, for down, already rolled back) is skipped. If a concurrent run in the other direction changed the state underneath (an up whose earlier migration was rolled back, a down whose later migration was applied), it fails instead of continuing. Because the lock is tied to the transaction, it also works over a pool and behind PgBouncer in transaction mode.
  • install() takes the same lock in the statement that creates the table. One simple query runs as one transaction, and nothing fails, so it is also safe inside a caller's transaction.
  • The lock key is the migration table name plus current_schema(), so migrators in different schemas don't wait for each other.

Not covered: migrations that use use_transaction() -> Some(false), and MySQL/SQLite.

Tests (Postgres 18):

  • test_concurrent_up in tests/postgres.rs runs 8 concurrent up, then 8 concurrent down, on a fresh database. Master failed it 3 of 3 times.
  • test_concurrent_up_in_transaction runs 8 concurrent up, each inside its own transaction. With the earlier retry in install() it failed 3 of 3 times (25P02 current transaction is aborted); it passes now.
  • test_lock_per_schema holds the lock in schema a with an open transaction and checks that up in schema b still finishes; with a key without the schema it waits until the timeout.
  • Unit tests on should_apply / should_roll_back cover the skip and the error for a concurrent run in the other direction.

When several instances of an app start at the same time and each runs
Migrator::up on start, they race: all of them read the same pending
list, and each then runs the same migration. The losers fail with a
duplicate key on pg_type (CREATE TABLE) or on seaql_migrations, or,
with a migration that is not idempotent, apply it twice.

Each migration that runs in a transaction now takes a transaction-level
advisory lock first and then checks the migrations table again; one
that another process applied (or rolled back) in the meantime is
skipped. pg_advisory_xact_lock is released on commit or rollback, so it
works over a connection pool and behind PgBouncer in transaction mode.

install() also tolerates the race on CREATE TABLE IF NOT EXISTS for the
migrations table itself, which Postgres reports as a unique violation
on pg_type.
@patrick-immometrica
patrick-immometrica marked this pull request as ready for review October 26, 2026 14:24
@Huliiiiii

Copy link
Copy Markdown
Member

A few concerns:

  1. The lock is scoped to each migration's transaction, so concurrent up and down calls can still leave the migration state inconsistent.
  2. If install() is called within an existing PostgreSQL transaction, retrying after a unique constraint violation won't work because the transaction is already aborted.
  3. The advisory lock key only includes the migration table name, so migrations in different schemas using the same table name will contend for the same lock. Could we include the table's schema in the lock key?

We should either handle these case or document the limitation.

- Under the lock, each migration now re-reads all applied versions. An up
  whose earlier migration was rolled back meanwhile, or a down whose later
  migration was applied meanwhile, fails instead of leaving the table
  inconsistent with the schema.
- install() takes the same lock in the statement that creates the table,
  instead of retrying on a unique violation; the retry could not work
  inside a caller's transaction, which the first failure had aborted.
- The lock key includes current_schema(), so migrators on tables of the
  same name in different schemas no longer wait for each other.
@patrick-immometrica

Copy link
Copy Markdown
Contributor Author

Thanks, all three are handled now (a59e381):

  1. Under the lock, each migration now re-reads every applied version, not just its own. An up fails if an earlier migration was rolled back in the meantime, and a down fails if a later one was applied, so a concurrent run in the other direction can no longer leave the state inconsistent. A lock held for the whole run would need a session-level lock, which breaks behind PgBouncer in transaction mode.
  2. install() no longer retries. It takes the same advisory lock in the statement that creates the table (SELECT pg_advisory_xact_lock(...); CREATE TABLE IF NOT EXISTS ... as one simple query, which runs as one transaction), so nothing fails and a caller's transaction stays usable. test_concurrent_up_in_transaction runs 8 concurrent ups, each inside its own transaction: it failed 3 of 3 times with the retry (25P02) and passes now.
  3. The lock key now includes current_schema().

@Huliiiiii Huliiiiii self-assigned this Nov 14, 2026
@Huliiiiii

Copy link
Copy Markdown
Member

Sorry for the late follow-up.

A few remaining issues:

  1. should_roll_back only checks migrations known to the current migrator. During a rolling deployment, an older instance could read [m1, m2], then a newer instance applies m3 before it acquires the lock. The older instance would still roll back m2, leaving m3 applied. We should reject unknown applied migrations when rechecking the state under the lock.

  2. The lock-and-recheck approach relies on READ COMMITTED. Under REPEATABLE READ or SERIALIZABLE, acquiring the advisory lock doesn't refresh the transaction snapshot. I'd prefer explicitly checking transaction_isolation and rejecting unsupported isolation levels. The check should use the actual transaction connection and happen before any migration DDL.

  3. lock_and_read_applied only needs migration versions, but get_migration_models fetches full records and sorts them on every iteration. Could we use a version-only query instead? We still need to recheck after acquiring each lock, so caching the initial state wouldn't be correct.

Please also add regression tests for these cases, including concurrent up and down operations. The current tests only run them separately.

Recheck the applied versions with a version-only query, fail when one of
them is unknown to this migrator (a newer instance migrated meanwhile), and
fail unless the transaction is READ COMMITTED, since a snapshot taken
before the lock would not see what other processes committed while it
waited. Tests cover both, and concurrent up and down runs.
@patrick-immometrica

Copy link
Copy Markdown
Contributor Author

Thanks, all three are addressed in 385f185.

  1. The recheck under the lock now fails if the table holds a version this migrator doesn't know, so an older instance stops instead of rolling back under a newer one's migration.
  2. The lock statement also reads current_setting('transaction_isolation') on the migration's own transaction and rejects anything other than READ COMMITTED, before up/down runs.
  3. The recheck reads only version, unsorted.

New tests: test_down_rejects_unknown_migration (a migration outside a transaction inserts an unknown version mid-rollback, the next step has to fail and leave the last known migration applied), test_rejects_snapshot_isolation (REPEATABLE READ and SERIALIZABLE, checks no table was created), and test_concurrent_up_and_down (four up and four down at once from a half-migrated database; every run either succeeds or fails with the "by another process" error, and the applied set stays a prefix). The first two fail without the change.

@Huliiiiii Huliiiiii left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. The previous issues are mostly addressed. A few things left:

  1. The isolation level check still happens after install(), so DDL may already have been executed before we reject the transaction. Could we check it before install() as well? The test should also verify that the migration table hasn't been created. We should keep the check on the actual migration transaction too.

  2. names.contains(&version) performs a linear search for every applied migration on each iteration. We should build a HashSet of known migration names once and reuse it.

  3. Please simplify the comments and error messages around unknown migrations. We only know that a migration version is unknown, not necessarily that another process or a newer migrator applied it. The test also simulates this case rather than running another migrator.

Also, please resolve the merge conflicts with master.

…ent-up

# Conflicts:
#	sea-orm-migration/src/migrator/exec.rs
…sion check

up, down and fresh now reject a snapshot isolation level before the
migration table is created, and each migration transaction still checks
it before taking the lock. The recheck under the lock looks versions up in
a set built once, reports an unknown version with the existing missing
file error, and honours ignore_missing_migrations.
@patrick-immometrica

Copy link
Copy Markdown
Contributor Author

Thanks, addressed in be82a7f, and master is merged in (0a9304a).

  1. up, down and fresh now check the isolation level before install() (and before drop_everything in fresh); each migration transaction still checks it before taking the lock. test_rejects_snapshot_isolation now also asserts that seaql_migrations wasn't created, and fails without the early check.
  2. The known names are collected into a HashSet once per up/down and reused for every recheck.
  3. An unknown version under the lock now gives the same "Migration file of version '…' is missing" error as the initial read, and the comments no longer guess where it came from. Since Add an option to ignore applied migrations without a file #3246 landed, the recheck also honours ignore_missing_migrations(); the test covers both sides of that and is worded as recording an unknown version rather than another migrator.

Comment thread sea-orm-migration/src/migrator/exec.rs Outdated
.await?
.ok_or_else(|| DbErr::Migration("Failed to read the isolation level".to_owned()))?
.try_get("", "isolation")?;
if isolation != "read committed" {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PostgreSQL treats READ UNCOMMITTED as READ COMMITTED, so we should allow both.

@Huliiiiii

Copy link
Copy Markdown
Member

A couple of small test improvements:

  1. test_concurrent_up_and_down duplicates the task spawning logic from concurrently(). Could we reuse that helper and pass the task index to distinguish up and down? Currently it also spawns tasks while still establishing connections, so some migrations may finish before the others even start.

  2. test_fresh_with_extension can reuse the new create_db() helper instead of duplicating the database setup.

Also, please cover READ UNCOMMITTED in the isolation level test when updating the check.

Postgres treats READ UNCOMMITTED as READ COMMITTED, so the isolation
level check accepts both, and the isolation test runs up in such a
transaction. The tests also share more of their setup:
test_concurrent_up_and_down goes through concurrently(), which now passes
the instance index and connects every instance before it spawns the
first, and test_fresh_with_extension uses create_db().
@Huliiiiii

Copy link
Copy Markdown
Member

Thanks.

One minor test improvement: after IgnoresUnknownVersion::down, could we also assert that the expected migration was actually rolled back and the unknown migration remains recorded?

Otherwise, LGTM.

@patrick-immometrica

Copy link
Copy Markdown
Contributor Author

Thanks, added in 3ffebc7: after IgnoresUnknownVersion::down the test now checks that m20230109_000001_seed_cake_table is gone and the unknown version is still recorded.

@patrick-immometrica

Copy link
Copy Markdown
Contributor Author

The CI failure isn't from this change. SeaQL/sea-query#1140 removed the unimplemented-jiff-sqlx-mysql feature that sea-orm's Cargo.toml still enables, so the git patch for sea-query-sqlx is no longer used ("patch was not used in the crate graph") and cargo falls back to 0.9.0 from crates.io, which rejects with-jiff together with sqlx-postgres. master should fail the same way on its next run. I'll merge master again once that's fixed.

@Huliiiiii

Copy link
Copy Markdown
Member

Thanks. I will fix the CI later.

@Huliiiiii
Huliiiiii enabled auto-merge (squash) November 16, 2026 22:58
@Huliiiiii
Huliiiiii disabled auto-merge November 16, 2026 23:12
@Huliiiiii
Huliiiiii merged commit c453c64 into SeaQL:master Nov 16, 2026
49 of 51 checks passed
@patrick-immometrica
patrick-immometrica deleted the migration-concurrent-up branch November 16, 2026 23:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants