Zero-downtime EF Core schema changes on Azure SQL: expand/contract, renames, NOT NULL columns, backfills, and keeping two app versions compatible with one schema.
Zero downtime means every migration must be compatible with the app version that is already running, because during a rolling deploy or slot swap the old and new code share one database. The pattern is expand/contract: first expand (add nullable columns, new tables, new indexes online), deploy code that writes both shapes, backfill in batches, switch reads, and only in a later release contract (drop the old column or table).
RenameColumn in one step.The trade-off: three or four small releases instead of one, in exchange for no outage and an easy rollback at every step.
"The key fact is that during any real deployment, two versions of the app talk to the same database. With an Azure App Service slot swap or a Kubernetes rolling update, version N is still serving traffic while N+1 starts. So the rule I apply is: the schema after a migration must work for both N and N+1. That rules out anything that removes or renames something N still uses, and anything that adds a constraint N does not satisfy.
The way to live with that rule is expand/contract. Expand first: add the new column as nullable, add the new table, create indexes online. Ship code that writes to both old and new shapes. Backfill existing rows in small batches outside the migration. Then ship code that reads from the new shape. Only in a later release do I contract: drop the old column, make the new one NOT NULL. For example, at [company] we split a
FullNamecolumn intoGivenNameandFamilyNameon a [12-million-row] table across [three] releases, and nobody noticed. The single-step version would have taken a schema lock for [minutes] and broken every running pod.The mistake I see is trusting the scaffolded migration. EF Core will happily generate a
RenameColumn, or aDropColumnplusAddColumnif it guesses wrong, and aNOT NULLcolumn with a default of empty string. Every migration gets reviewed as SQL, withdotnet ef migrations script --idempotent, before it goes near production. Zero downtime is a discipline about ordering, not a feature you switch on."
| Change | Safe in one release? | Zero-downtime approach |
|---|---|---|
| Add nullable column | Yes | Just add it |
| Add NOT NULL column | No (old code inserts without it) | Add nullable or with default → backfill → ALTER ... NOT NULL later |
| Rename column | No | Add new → dual-write → backfill → switch reads → drop old |
| Drop column | No (old code selects it) | Stop using it in release N, drop in N+1 |
Change type (widen, e.g. nvarchar(50) → (100)) |
Usually yes | Check it is metadata-only; narrowing is add/copy/drop |
| Add index | Yes, if online | ONLINE = ON; avoid offline builds on hot tables |
| Add FK or CHECK constraint | Risky | Add WITH NOCHECK, clean data, then validate |
| Split or merge tables | No | New table + dual-write + backfill + switch + drop |
| Release | Schema | Code |
|---|---|---|
| 1 (expand) | Add Email (nullable) next to EmailAddress |
Write both, read old |
| — | Backfill job copies EmailAddress → Email in batches |
— |
| 2 | (none) | Read Email, still write both |
| 3 (contract) | Drop EmailAddress, make Email NOT NULL |
Write only Email |
In EF Core, release 1 maps both properties; release 3 removes the old property and generates the drop.
dotnet ef migrations script --idempotent produces a script safe to run against any database state.Migrate() takes a database-wide lock so two instances cannot apply migrations at once, and it throws if the model has pending changes with no migration. That helps, but running migrations from every instance at start-up is still a poor pattern.On a [B2B ordering API on Azure SQL, 40 million rows in OrderLines], adding a NOT NULL CurrencyCode in one migration held a schema modification lock for [6 minutes] in staging. Splitting it into add-with-default, a batched backfill of [5,000 rows per transaction], and a later NOT NULL step brought the blocking to under [1 second] per batch and zero failed requests in production.
Checks whether the candidate has shipped schema changes to a live system and understands that two app versions share one database during every deploy.
Green flags
Red flags
Migrate() at start-up as the whole answerEvery hosted deployment has an overlap window:
time ──────────────────────────────────────────────▶
v1 pods ████████████████████░░░░░░░
v2 pods ░░░░░████████████████████████
migration ▲
│ schema must satisfy v1 AND v2 here
App Service slot swaps warm the new slot against the production database before the swap. Kubernetes rolling updates keep old pods until new ones are ready. Even a "stop everything" deploy has a rollback path where v1 comes back on the new schema. So the real requirement is: schema version S+1 must work with app versions N and N+1.
| DDL | Lock and cost on SQL Server / Azure SQL |
|---|---|
ADD col NULL |
Metadata-only, brief Sch-M lock |
ADD col NOT NULL DEFAULT 'AUD' (constant) |
Metadata-only since SQL Server 2012 Enterprise; Azure SQL supports it. The default is stored once, rows are not rewritten |
ALTER COLUMN ... NOT NULL |
Scans the table to check for NULLs while holding Sch-M; long on big tables |
sp_rename |
Instant, but every query using the old name breaks immediately |
CREATE INDEX offline |
Blocks writes for the duration |
CREATE INDEX ... WITH (ONLINE = ON) |
Allows reads and writes; short locks at start and end |
DROP COLUMN |
Metadata-only; space is reclaimed later by a rebuild |
A Sch-M lock is incompatible with every other lock, so even a "fast" DDL waits behind long-running queries and then blocks everything queued behind it. Setting a lock timeout in the migration script (SET LOCK_TIMEOUT 5000) turns a pile-up into a fast, retryable failure.
EF Core maps the expand step naturally: add a nullable property, generate a migration. For the parts EF Core cannot express, use migrationBuilder.Sql(...) inside the migration.
Release 1 migration: AddColumn(Email, nullable: true)
Backfill job: UPDATE TOP (5000) ... WHERE Email IS NULL (loop)
Release 3 migration: AlterColumn(Email, nullable: false); DropColumn(EmailAddress)
Keep the backfill out of the migration when the table is large. Migrations on SQL Server run each migration inside a transaction; a single UPDATE of 40 million rows in that transaction bloats the log and holds locks for its whole duration. A separate, idempotent job (a BackgroundService, an Azure Function or a SQL Agent / Elastic Job) can be paused, resumed and monitored.
During the transition both properties exist on the entity. Write both in one place (the domain method or a SaveChangesInterceptor), never scattered across handlers, so nothing writes only the old one. Read from the old column until the backfill is verified with a count query (SELECT COUNT(*) WHERE Email IS NULL).
The pay-off: each release is independently reversible. If release 2 misbehaves you redeploy release 1 code; the schema is still compatible. Contract steps are the only irreversible ones, which is why they wait at least one release, after the old code is gone everywhere (including background workers and reporting jobs).
dotnet ef migrations script <from> <to> --idempotent for review and for applying with a DBA-friendly script.dotnet ef migrations bundle) for a self-contained executable in the pipeline.DropColumn, DropTable, RenameColumn or AlterColumn without an explicit allow-list comment.sys.dm_exec_requests to watch blocking while a migration runs.ALTER TABLE ADD col NOT NULL DEFAULT vs ADD col NULL + UPDATE + ALTER COLUMN NOT NULL.dotnet ef migrations script. Then rewrite it as expand/contract.SELECT in one session, start a DDL in another, and watch the blocking chain in sys.dm_exec_requests.UPDATE TOP (5000) and measure transaction log usage with sys.dm_db_log_space_usage.DROP COLUMN and sp_rename and fails the build.Release 1 (expand): add the new column as nullable and keep writing both. The backfill runs separately.
namespace Orders.Infrastructure.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
public partial class AddCustomerEmail : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Nullable: v1 code inserts without it, so NOT NULL would break the running version.
migrationBuilder.AddColumn<string>(
name: "Email",
table: "Customers",
type: "nvarchar(320)",
maxLength: 320,
nullable: true);
// Online index build so writes continue on a large table (Azure SQL supports ONLINE).
migrationBuilder.Sql(
"CREATE INDEX IX_Customers_Email ON Customers (Email) WITH (ONLINE = ON);");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DROP INDEX IX_Customers_Email ON Customers;");
migrationBuilder.DropColumn(name: "Email", table: "Customers");
}
}
The backfill, as an idempotent batched job outside the migration:
namespace Orders.Infrastructure.Backfills;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public sealed class CustomerEmailBackfill(
IDbContextFactory<OrdersDbContext> contextFactory,
ILogger<CustomerEmailBackfill> logger) : BackgroundService
{
private const int BatchSize = 5_000;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using var db = await contextFactory.CreateDbContextAsync(stoppingToken);
// Short transaction per batch: small locks, small log growth, safe to stop and resume.
var updated = await db.Database.ExecuteSqlAsync($"""
UPDATE TOP ({BatchSize}) Customers
SET Email = EmailAddress
WHERE Email IS NULL AND EmailAddress IS NOT NULL
""", stoppingToken);
logger.LogInformation("Backfilled {Count} customer emails", updated);
if (updated == 0) break;
await Task.Delay(TimeSpan.FromMilliseconds(200), stoppingToken); // leave headroom for live traffic
}
}
}
Release 3 (contract), shipped only after no running code reads EmailAddress:
-- Generated by: dotnet ef migrations script AddCustomerEmail DropCustomerEmailAddress --idempotent
SET LOCK_TIMEOUT 5000; -- fail fast instead of queueing behind long queries
ALTER TABLE Customers ALTER COLUMN Email nvarchar(320) NOT NULL;
ALTER TABLE Customers DROP COLUMN EmailAddress;
RenameColumn for a property rename. Why it is wrong: sp_rename is instant, so every running v1 instance starts failing on the next query. Instead: Add the new column, dual-write, backfill, switch reads, drop the old one a release later.defaultValue: "" to satisfy the compiler. Why it is wrong: It fills millions of rows with meaningless data that later looks valid. Instead: Add it nullable (or with a meaningful constant default), backfill real values, then tighten.UPDATE inside the migration. Why it is wrong: It runs in the migration's transaction, holds locks for minutes and grows the log; a timeout rolls the whole thing back. Instead: Batch the backfill in a separate idempotent job.WITH (ONLINE = ON), ideally off-peak.Database.Migrate() from every instance at start-up. Why it is wrong: Start-up time grows, failures crash-loop every pod, and the app needs DDL permissions. Instead: Apply an idempotent script or bundle in a dedicated pipeline step.Zero downtime is a sequencing problem, and the senior move is to make it boring: a written checklist, a CI gate on destructive operations, automated migration tests against real SQL Server, and the expectation that a schema change is two or three PRs. The real cost is coordination, so I assess each change by impact and only pay that cost where it matters: hot, customer-facing tables get full expand/contract; a rarely used admin table can take a two-second lock at 2 am in an agreed window.
Measure before you plan. Check row counts, Query Store for who reads the column, and run the DDL against a restored copy of production to time it and watch the blocking. A test on an empty dev database tells you nothing. During the rollout, watch blocked sessions and SQL dependency latency in Application Insights, and know that the rollback at every expand step is simply redeploying the previous version.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Expand/contract over several releases | Hot tables, rolling or slot deploys | More PRs, temporary dual-write code | Tiny internal tables |
| Single migration in a maintenance window | Internal systems with agreed downtime | An outage | Customer-facing 24/7 services |
Online DDL only (ONLINE = ON) |
Index changes | Longer build time, more tempdb | Column renames and drops |
| Blue/green with a copied database | Huge restructures | Data sync complexity, double cost | Routine changes |
Never use RenameColumn while old and new app versions overlap: the old version would query a column that no longer exists. Use expand and contract over several releases. 1. Expand: add the new column (nullable). 2. Dual write: release an app version that writes both columns in the same SaveChanges (same transaction), or add a trigger that copies writes made by the old version, and still reads the old column. 3. Backfill existing rows in small batches (UPDATE TOP (5000) ... WHERE New IS NULL) to avoid long locks and log growth, then verify with a count of mismatches. 4. Switch reads to the new column; keep writing both so a rollback to the previous version still works. 5. Contract: once no running version uses the old column, stop writing it and drop it in a later migration. Each step is backward compatible with the version before it.
I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.
Add the constraint WITH NOCHECK so SQL Server enforces it for new writes without scanning existing rows, which avoids a long Sch-M lock. Then find and fix the violating rows in batches, and finally run ALTER TABLE ... WITH CHECK CHECK CONSTRAINT so the constraint becomes trusted (is_not_trusted = 0). Untrusted constraints are still enforced, but the optimiser cannot use them for join elimination or plan simplification, so the last step matters for performance. In EF Core, add the constraint with migrationBuilder.Sql because the scaffolded AddForeignKey always validates.
How to tell it (STAR)
**S:** At [company] we ran an ordering API on Azure SQL with about [40 million] order lines. A routine release added a NOT NULL column and renamed another in a single EF Core migration. **T:** I was [on call / the tech lead], and checkout was timing out across the board. **A:** I found the migration holding a schema lock with hundreds of sessions queued behind it, killed it, and rolled back to the previous release. Then I rewrote the change as expand/contract across three releases, moved the backfill into a batched job, and added a CI gate that flags renames, drops and NOT NULL changes in generated scripts. **R:** The outage lasted [6 minutes]; the reworked change shipped with zero failed requests, and in the next [year] the gate caught [several] risky migrations before review.
Last updated 23 Nov 2026.