Skip to content

Implement database locking for migrations #33731

Description

@AndriySvyryd

Generally speaking, concurrent invocations of Migrate() will fail and possibly leave the database in a corrupted state. In order to mitigate this, we could create a temporary table using HistoryRepository that will serve as a lock while the migrations are applied by the process that acquired it. Providers will be able to override all related logic to instead leverage database-specific mechanisms to accomplish this.

Activity

  1. self-assigned this
    on May 16, 2024
  2. roji commented on May 16, 2024

    @roji
    Member

    That's a good idea - databases do frequently expose locking mechanisms that could work well, e.g. full-table exclusive lock on the HistoryRepository table for PG and SQL Server. Though I'm not sure what a default implementation would look like here - what do you have in mind with the temporary table?

  3. AndriySvyryd commented on May 16, 2024

    @AndriySvyryd
    MemberAuthor

    what do you have in mind with the temporary table?

    Before applying migrations create __EFLock table. If it was created successfully - the lock was acquired. If not, enter the normal retry loop.
    After migrations and seeding (#17568) finished applying delete __EFLock table.

  4. added this to the Backlog milestone on May 16, 2024
  5. modified the milestones: Backlog, 9.0.0 on Jun 20, 2024
  6. added a commit that references this issue on Jun 28, 2024
    6923bc0
  7. removed their assignment
    on Jun 28, 2024
  8. added a commit that references this issue on Jun 28, 2024
    6b4331d
  9. 4 remaining items

  10. roji commented on Jul 12, 2024

    @roji
    Member

    PG tracking issue: npgsql/efcore.pg#3223

  11. added a commit that references this issue on Jul 12, 2024
    27ca389
  12. modified the milestones: 9.0.0, on Aug 21, 2024
  13. modified the milestones: , 9.0.0 on Oct 12, 2024
  14. pisc-software commented on Dec 2, 2024

    @pisc-software

    This new feature creates issues when using CrateDB and the NPGSQL implementation it supports. The database does not support the "LOCK" command, hence migrations fail when using Migrate/MigrateAsync with this setup.

    The migration is not executed, because the lock on the history table creates an exception in the Postgres driver.

    How to tell EF to not perform this table lock?

    We are heavily using EF in a large software, and now we are not able to upgrade to .NET 9 because of this.
    Whenever adding such a feature, it MUST be such to allow disabling it from code. Not all Databases support LOCK. The assumption made here is incorrect.

  15. roji commented on Dec 2, 2024

    @roji
    Member

    @pisc-software

    We are heavily using EF in a large software, and now we are not able to upgrade to .NET 9 because of this.
    Whenever adding such a feature, it MUST be such to allow disabling it from code. Not all Databases support LOCK. The assumption made here is incorrect.

    While I'm sorry you're running into trouble, keep in mind that the PostgreSQL EF provider was developed and gets tested against PostgreSQL; it's the responsibility of the various PG-like database (like CrateDB - there are many others) to ensure compatibility. In any case, users shouldn't have to be concerned with controlling a low-level implementation detail such as enabling/disabling migration locking - at most they should configure the EF provider for CrateDB (or similar), and that would determine whether locking is used or not.

    In any case, here's a code snippet that you can drop into your project to disable locking with the PostgreSQL EF provider - this should unblock you and anyone else; we'll discuss how to better address the situation in the team.


    Workaround to disable migration locking with Npgsql

    When configuring your DbContext, add ReplaceService() as follows:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql("Host=localhost;Username=test;Password=test")
            .ReplaceService<IHistoryRepository, NonLockingNpgsqlHistoryRepository>();

    The implementation for NonLockingNpgsqlHistoryRepository:

    #pragma warning disable EF1001
    public class NonLockingNpgsqlHistoryRepository(HistoryRepositoryDependencies dependencies)
        : NpgsqlHistoryRepository(dependencies)
    {
        public override IMigrationsDatabaseLock AcquireDatabaseLock()
            => new NoopMigrationsDatabaseLock(this);
    
        public override Task<IMigrationsDatabaseLock> AcquireDatabaseLockAsync(
            CancellationToken cancellationToken = default)
            => Task.FromResult<IMigrationsDatabaseLock>(new NoopMigrationsDatabaseLock(this));
    
        class NoopMigrationsDatabaseLock(NpgsqlHistoryRepository historyRepository) : IMigrationsDatabaseLock
        {
            public void Dispose() {}
            public ValueTask DisposeAsync() => ValueTask.CompletedTask;
            public IHistoryRepository HistoryRepository => historyRepository;
        }
    }
    #pragma warning restore EF1001
  16. added theissue type on Jun 15, 2025
  17. Timovzl commented on Nov 25, 2025

    @Timovzl

    Great to see that this is implemented.

    Should it be of interest for EF, or to readers using certain providers, we can use a different approach for providers that lack an applock equivalent but that do have a sleep command:

    • Start with connection 1.
    • Acquire a lock. (Create-if-not-exists some lock table, insert-if-not-exists some lock row, etc.)
    • Since we intend to create a sleep task to monitor our lock-holding connection, create a CancellationTokenSource that lets us cancel it at the end.
    • Asynchronously initiate a sleep for [timeout]. (I'm on team 12h, since a rare but known slow migration should not get unexpectedly killed after a few hours.) Pass the new source's CancellationToken.
    • Hold the resulting task without awaiting it.
    • Create a CancellationTokenSource to represent lock interruption (be it timeout, connection loss, or whatever reason).
    • On the running sleep task, set ContinueWith() to cancel the CancellationTokenSource, no matter the reason for completion.
    • Create a linked CancellationTokenSource, combining the input CancellationToken (usually representing startup abort) with the one from the source that monitors the sleep task.
    • Now that we have the lock and are monitoring it, open connection 2.
    • On connection 2, perform migrations, passing the combined cancellation token.
    • Finally, use the first CancellationTokenSource to cancel the sleep task.

    This approach has proven quite reliable over the years. It is session-based, so it leaves no trace, even on a hard crash.

    It also circumvents issues with providers where certain DDL statements cannot be done transactionally. That usually means that any ongoing transaction will commit, which would risk leaving a lock that could inadvertently stick around. By having the lock in a separate connection, we avoid ever committing it. By using that connection as a lifeline, we still interrupt any migrations if we ever lose the lock.

    Here is an example implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions