skip to content

In EF Core 10 with Npgsql, what does MigrateAsync actually do when three payroll-service containers call it at startup, and when should a bundle step replace it?

level: seniorimportance: should knowfreq 40%

answer

  1. migration lock since EF Core 9
  2. LOCK TABLE on __EFMigrationsHistory
  3. one transaction per migration in 10
  4. seeding runs inside the lock
  5. runtime login needs DDL rights

basics

~20 s

Replicas take EF Core's migration lock in turn (on Npgsql, an exclusive lock on __EFMigrationsHistory); the first applies pending migrations, one transaction each, the rest find none, and all run seeding. Use a bundle when review or least privilege matters.

solid answer

~50 s

Since EF Core 9, `MigrateAsync` acquires a migration lock before reading the history. With Npgsql it runs `LOCK TABLE "__EFMigrationsHistory" IN ACCESS EXCLUSIVE MODE` inside its transaction, so the three containers serialize: the first applies every pending migration, the others wait, re-read the history and find nothing to apply. Each then runs `UseAsyncSeeding` under the lock. EF Core 10 commits each migration in its own transaction, so a failure part way leaves earlier migrations applied and the container crashes on startup. It also implies the app's runtime login can alter the schema, that nobody reviewed the SQL, and that startup waits on the lock. Do not wrap the call in your own transaction: EF Core then cannot take the lock and logs `MigrationsUserTransactionWarning`. When reviewed SQL, least-privilege credentials or a controlled rollout matter, build an `efbundle` and run it once as a release step instead.

code

csharp · 14 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<PayrollDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("Payroll")));

var app = builder.Build();

if (app.Configuration.GetValue<bool>("Payroll:MigrateOnStartup"))
{
    await using var scope = app.Services.CreateAsyncScope();
    var db = scope.ServiceProvider.GetRequiredService<PayrollDbContext>();
    await db.Database.MigrateAsync(app.Lifetime.ApplicationStopping);
}

app.Run();

go deeper

for a junior

Know that an app can call MigrateAsync at startup and that EF Core 9 and later lock the database so replicas do not apply the same migration twice.

for a middle

Explain the steps of MigrateAsync: pending-model check, history table, provider lock, per-migration transactions in EF Core 10, then seeding.

for a senior

Weigh startup migration against a bundle job: partial application, lock waits, DDL rights for the runtime login, review requirements, and the user-transaction trap.

for a principal

Set the deployment standard for schema changes across services, including which identity owns the schema and how migrations are sequenced against rolling application releases.

## The startup pattern Many services apply migrations from `Program.cs`, after `builder.Build()` and before `app.Run()`, by resolving the context from a scope and calling `MigrateAsync`. Because that code runs after the host is built, the EF design-time tools, which stop the app as soon as the host exists, never execute it. In production, though, every replica of the payroll service executes it. ## What MigrateAsync does, step by step 1. **Pending-model check.** If the model differs from the migrations' snapshot, it throws before touching the database. 2. **Database and history table.** It creates the database if it is missing and the `__EFMigrationsHistory` table if needed. 3. **Lock.** Since EF Core 9 it takes a **migration lock**. Its form is provider-specific: - Npgsql: `LOCK TABLE "__EFMigrationsHistory" IN ACCESS EXCLUSIVE MODE`, released when the transaction ends; - SQL Server: `sp_getapplock` on the resource `__EFMigrationsLock`, held for the session; - SQLite: a `__EFMigrationsLock` table, which can be left behind if a process dies. 4. **Apply.** It reads the applied ids, then applies each pending migration. In EF Core 10 **each migration has its own transaction**; EF Core 9 had wrapped all of them in one, and 10 reverted that. 5. **Seed.** It runs `UseAsyncSeeding` (or throws if only the synchronous `UseSeeding` is configured) while still protected by the lock. ## Three replicas at once | Replica | What it sees | |---|---| | First to get the lock | applies the pending migrations, runs seeding, releases the lock, starts serving | | Second and third | wait on the lock, then read a history that already lists every migration, apply nothing, run seeding, start serving | So concurrent startups no longer corrupt the schema, which was the classic pre-EF 9 failure. What the lock does not fix: - **Partial application.** If the third of five migrations fails, the first two stay committed, the third rolls back if its operations were transactional, and the container fails to start; every restart retries from the same point. - **Waiting.** Replicas queue behind a long migration, and on Npgsql the exclusive table lock also blocks anything else reading the history table. - **Old code against a new schema.** Instances of the previous release keep serving while the new one migrates. ## Mistakes in the startup code - **Wrapping the call in your own transaction.** EF Core then cannot take its lock and logs `RelationalEventId.MigrationsUserTransactionWarning`; with a retrying execution strategy such as `EnableRetryOnFailure` it throws `NotSupportedException`. Call `MigrateAsync` directly; it manages its own transactions and execution strategy. - **Calling `EnsureCreatedAsync` first.** It creates tables without history, and `MigrateAsync` then fails. - **Catching and ignoring the exception.** The app then serves traffic against a schema it does not match. ## When a bundle replaces it Startup migration trades control for simplicity. A separate step built from `dotnet ef migrations bundle` fits better when: - **the SQL or the migration set must be approved** before production; - **the runtime identity should not own the schema**: with startup migration, the payroll API's login must be able to alter tables; - **the rollout is controlled**: the migration runs once, its exit code gates the release, and no replica waits on a lock; - **startup time matters**, for example with aggressive health-check timeouts. The EF Core docs recommend that pattern for containers: build the bundle in CI, run it as a one-shot job after the database is healthy, and do not make every replica migrate from its entrypoint. Startup migration stays reasonable for a single-instance internal tool or a development environment. ## Reading the startup snippet - `CreateAsyncScope()` is needed because `AddDbContext` registers the context as scoped, and no request scope exists yet at startup. - Passing `app.Lifetime.ApplicationStopping` lets a shutdown cancel a replica that is still waiting on the lock. - The configuration switch lets the same image run with startup migration in development and without it where a bundle step owns migrations. - The call is awaited and not wrapped in `try`/`catch`: if migrating fails, the process exits and the orchestrator reports a failed start instead of a healthy instance on the wrong schema.

  • Why must MigrateAsync not be wrapped in BeginTransactionAsync and an execution strategy, the pre-EF 9 resilient pattern?
    Since EF Core 9 `MigrateAsync` starts its own transactions and runs under the context's execution strategy. Inside your transaction it cannot take the migration lock, so EF Core logs `MigrationsUserTransactionWarning`, and with a retrying strategy configured it throws `NotSupportedException`. Remove the wrapper and call `MigrateAsync` directly.
  • A migration fails on the second of three replicas' startups; what state is the payroll database in?
    Only one replica applies migrations at a time. Whichever applied them committed every migration that succeeded, one transaction each, and the failing migration rolled back if its operations ran in a transaction. Every replica that reaches the failing migration fails to start; fix it with a corrective migration rather than editing the one that failed.

  • In EF Core 10, concurrent MigrateAsync calls corrupt the schema, so only one replica may call it.
  • If one migration fails, EF Core 10 rolls back every migration applied in that call.
  • Wrapping MigrateAsync in your own transaction makes startup migration safer.
  • The migration lock on Npgsql is an sp_getapplock call.
  • Startup migration lets the application run with a read and write only database login.

Assumes EF Core 10: migration locking arrived in EF Core 9, and EF Core 10 reverted EF Core 9's single transaction spanning all migrations back to one transaction per migration.