Repository navigation
Make concurrent migrations safe on PostgreSQL - #3245
Conversation
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.
|
A few concerns:
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.
|
Thanks, all three are handled now (a59e381):
|
|
Sorry for the late follow-up. A few remaining issues:
Please also add regression tests for these cases, including concurrent |
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.
|
Thanks, all three are addressed in 385f185.
New tests: |
Huliiiiii
left a comment
There was a problem hiding this comment.
Thanks for the update. The previous issues are mostly addressed. A few things left:
-
The isolation level check still happens after
install(), so DDL may already have been executed before we reject the transaction. Could we check it beforeinstall()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. -
names.contains(&version)performs a linear search for every applied migration on each iteration. We should build aHashSetof known migration names once and reuse it. -
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.
|
Thanks, addressed in be82a7f, and master is merged in (0a9304a).
|
| .await? | ||
| .ok_or_else(|| DbErr::Migration("Failed to read the isolation level".to_owned()))? | ||
| .try_get("", "isolation")?; | ||
| if isolation != "read committed" { |
There was a problem hiding this comment.
PostgreSQL treats READ UNCOMMITTED as READ COMMITTED, so we should allow both.
|
A couple of small test improvements:
Also, please cover |
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().
|
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. |
|
Thanks, added in 3ffebc7: after |
|
The CI failure isn't from this change. SeaQL/sea-query#1140 removed the |
|
Thanks. I will fix the CI later. |
Several app instances that each run
Migrator::upon start race: they all see the same pending migrations and run them. The losers fail with a duplicate key onpg_type(CREATE TABLE) or onseaql_migrations, and a migration that isn't idempotent can run twice.install()hits the same race onCREATE TABLE IF NOT EXISTS seaql_migrations.The fix, on Postgres:
pg_advisory_xact_lockand then reads the migrations table again. A migration another process applied (or, fordown, already rolled back) is skipped. If a concurrent run in the other direction changed the state underneath (anupwhose earlier migration was rolled back, adownwhose 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.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_upintests/postgres.rsruns 8 concurrentup, then 8 concurrentdown, on a fresh database. Master failed it 3 of 3 times.test_concurrent_up_in_transactionruns 8 concurrentup, each inside its own transaction. With the earlier retry ininstall()it failed 3 of 3 times (25P02 current transaction is aborted); it passes now.test_lock_per_schemaholds the lock in schemaawith an open transaction and checks thatupin schemabstill finishes; with a key without the schema it waits until the timeout.should_apply/should_roll_backcover the skip and the error for a concurrent run in the other direction.