Skip to content

Concurrent Migrate() applies the same migration twice: the migration lock ends with each migration's transaction #4162

Backlog

Description

@PieterjanDeClippel

Concurrent Migrate() applies the same migration twice

Since EF Core 9, Database.Migrate() takes a database lock so that several instances of an app can start together. With Npgsql the lock does not cover the whole run, and instances re-apply migrations that another instance already applied.

Repro (dotnet run against any PostgreSQL; REPRO_PG sets the connection string): https://github.com/PieterjanDeClippel/efcore-npgsql-migration-lock-race

The program recreates an empty database and runs three MigrateAsync() calls together. There are three migrations, and the second sleeps three seconds, like a data migration or an index build. On Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 with PostgreSQL 18, 3 of 3 runs fail:

OK   instance 1
FAIL instance 2: PostgresException: 42701: column "Email" of relation "People" already exists
FAIL instance 3: PostgresException: 42701: column "Phone" of relation "People" already exists
history rows: 3 (3 expected)

The same scenario on SQL Server (sp_getapplock, LockReleaseBehavior.Connection) applies each migration once.

Cause:

  • NpgsqlHistoryRepository takes LOCK TABLE "__EFMigrationsHistory" IN ACCESS EXCLUSIVE MODE with LockReleaseBehavior.Transaction, so the lock ends with each migration's transaction.
  • EF's Migrator.MigrateImplementationAsync reads the applied migrations once, under the first lock, and plans the whole run from that.
  • MigrationCommandExecutor commits each migration, then begins a new transaction and reacquires the lock for the next one, without re-reading the history.
  • Between instance A's commit of migration 1 and its next lock, instance B (blocked on LOCK TABLE) gets the lock, sees migration 1 applied, and applies migration 2. A then gets the lock back and applies migration 2 again from its stale plan.

Proposed fix: a session-level pg_advisory_lock with LockReleaseBehavior.Connection, so the migrator takes the lock once, before reading the history, and holds it for the run, as SQL Server does. The lock key is a number computed from the history table's schema-qualified name. The patch against hotfix/11.0.1 is on the repro's fix branch (upstream/efcore.pg-hotfix-11.0.1.patch); I have not run it through the provider's test suite. The same branch has the identical code as a workaround for 11.0.0 (ReplaceService<IHistoryRepository, AdvisoryLockHistoryRepository>()), which makes the repro pass 3 of 3 runs.

The trade-off is that a session lock does not hold through PgBouncer in transaction pooling mode, where LOCK TABLE in a transaction does. The alternative is a fix in EF Core's migrator, re-reading the history after reacquiring a transaction-scoped lock, which would cover any provider using LockReleaseBehavior.Transaction. If you would rather go that way, I can move this to dotnet/efcore.

Activity

  1. added 2 commits that reference this issue on Nov 24, 2026
  2. roji commented on Nov 25, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed: concurrent migration runs can execute the same migration twice and fail with PostgreSQL error 42701: column "Email" of relation "People" already exists. This is a regression relative to EF Core 9 for the ordinary, transaction-compatible migrations in the repro, but it was already present in EF Core 10, not introduced in 11.

    Provider / EF Core Result
    Npgsql 11.0.0 / EF Core 11.0.0 Failed twice
    Npgsql 10.0.4 / EF Core 10.0.15 Failed twice; also failed on .NET 10
    Npgsql 9.0.4 / EF Core 9.0.1 Succeeded twice; also succeeded on .NET 10

    These runs used PostgreSQL 18. The 11.0.0 runs used the .NET 11 RC2 runtime; the other repeated runs also used RC2 except where noted. I also reproduced the failure on Npgsql 10.0.0 / EF Core 10.0.0 with the original three-migration scenario. Race outcomes depend on scheduling. The EF Core 9 result does not establish safety for migrations containing transaction-suppressed operations.

    Why: Npgsql's history repository has used a transaction-scoped LOCK TABLE since EF Core 9. EF reads and plans migrations once, but commits and reacquires the lock for subsequent migration transactions without refreshing the plan. Another instance can apply a migration in between.

    The key change appears to be EF Core's return to one transaction per migration in 10; EF 9 normally kept one transaction over the entire run. The provider's EF 11 changes in #3992 and #4071 concern history-table initialization and leave the locking strategy unchanged. The 11.0.0 repro also failed twice when the history table was created before the concurrent calls, so history-table creation is not necessary to trigger this race.

    An adapted EF Core 11 SQLite repro, using a long-running SQLite query instead of pg_sleep, succeeded. SQLite uses an explicitly released lock rather than a transaction-scoped one. SQL Server was not independently tested. The observed failure therefore affects Npgsql's locking strategy, although the stale-plan problem lies in shared EF migration execution and could affect other providers using transaction-scoped locks.

    Related work: dotnet/efcore#34439 discusses transaction-scoped migration locking and reading history under the lock, but is not the same reported race. No direct upstream duplicate was found. #4163 proposes a session advisory lock; as noted there, transaction-pooling proxies such as PgBouncer need consideration. An upstream history refresh might address this particular between-migrations race, but transaction-suppressed commands and partially executed migrations also need consideration.

    minimal repro

    Create a console project referencing Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0 and set REPRO_PG to a connection string for a dedicated disposable database. This program deletes and recreates that database.

    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Migrations;
    using Microsoft.EntityFrameworkCore.Storage;
    using Microsoft.Extensions.Logging;
    
    await using (var context = new AppDb())
    {
        await context.Database.EnsureDeletedAsync();
        await context.GetService<IRelationalDatabaseCreator>().CreateAsync();
    }
    
    await Task.WhenAll(Enumerable.Range(0, 3).Select(async _ =>
    {
        await using var context = new AppDb();
        await context.Database.MigrateAsync();
    }));
    
    public sealed class AppDb : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options.UseNpgsql(Environment.GetEnvironmentVariable("REPRO_PG"))
                .LogTo(Console.WriteLine, LogLevel.Information);
    }
    
    [DbContext(typeof(AppDb))]
    [Migration("20260101000001_People")]
    public sealed class People : Migration
    {
        protected override void Up(MigrationBuilder b)
            => b.CreateTable("People", t => new { Id = t.Column<int>(nullable: false) });
    }
    
    [DbContext(typeof(AppDb))]
    [Migration("20260101000002_SlowAddEmail")]
    public sealed class SlowAddEmail : Migration
    {
        protected override void Up(MigrationBuilder b)
        {
            b.Sql("SELECT pg_sleep(3);");
            b.AddColumn<string>("Email", "People", nullable: true);
        }
    }
  3. added 2 commits that reference this issue on Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions