📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you run EF Core migrations with zero downtime? Explain the expand/contract pattern, how you handle a column rename, adding a NOT NULL column to a large table, backfilling data, and the fact that the old and new app versions run against the same database at once.

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.

Senior Theory Advanced azure-sql deployment ef-core expand-contract migrations zero-downtime

🎯 Key points

  • During a rolling or slot-swap deploy, version N and N+1 both run against one schema, so every migration must be backward compatible with N
  • Expand/contract: add new structures first, dual-write, backfill, switch reads, then drop the old structure in a later release
  • RenameColumn (sp_rename) is fine in EF Core but breaks version N instantly in a live deploy, so a rename becomes add + dual-write + backfill + drop
  • NOT NULL: add nullable or with a constant default (metadata-only on SQL Server), backfill, verify no NULLs remain with a count query, then tighten
  • Backfill in small batches (e.g. 5,000 rows per short transaction) outside the migration to limit locks and transaction log growth
  • Sch-M locks from DDL block every query on the table; use SET LOCK_TIMEOUT, ONLINE = ON index builds and off-peak windows, and watch blocking while it runs
  • Review the idempotent script, test migrations in CI against real SQL Server and rehearse on a production-sized copy; destructive steps ship a release later
  • Every step stays reversible by redeploying the previous app version; apply migrations as a pipeline step, not Database.Migrate() on every instance

⏱ 30-second answer

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).

  • A rename becomes add + dual-write + backfill + drop, never RenameColumn in one step.
  • A NOT NULL column is added nullable or with a default, backfilled, then tightened.
  • Destructive changes ship one release after the code stops using them.

The trade-off: three or four small releases instead of one, in exchange for no outage and an easy rollback at every step.

🗣 Full answer (senior)

How I would answer this in an interview

"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 FullName column into GivenName and FamilyName on 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 a DropColumn plus AddColumn if it guesses wrong, and a NOT NULL column with a default of empty string. Every migration gets reviewed as SQL, with dotnet ef migrations script --idempotent, before it goes near production. Zero downtime is a discipline about ordering, not a feature you switch on."


The compatibility rule, change by change

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

The release sequence for a rename

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.

Where EF Core helps and where it does not

  • It generates the DDL and the model snapshot, and dotnet ef migrations script --idempotent produces a script safe to run against any database state.
  • Since EF Core 9, 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.
  • It does not know which version of your code is running. Ordering is your job.

Production example

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.

🔍 What the interviewer is checking

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

  • States the N and N+1 compatibility rule unprompted
  • Breaks a rename into expand, dual-write, backfill, contract
  • Keeps large backfills out of the migration and batches them
  • Mentions reviewing the generated SQL and online index builds

Red flags

  • "EF Core migrations handle that" or Migrate() at start-up as the whole answer
  • Drops or renames in the same release that changes the code
  • No awareness of locking or table size

📚 Learn in depth

1. Why two versions always coexist

Every 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.

2. What SQL Server actually does for each DDL

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.

3. Doing it in EF Core

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.

4. Dual-writing in code

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).

5. Rollback at each step

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).

6. Tooling that helps

  • dotnet ef migrations script <from> <to> --idempotent for review and for applying with a DBA-friendly script.
  • Migration bundles (dotnet ef migrations bundle) for a self-contained executable in the pipeline.
  • A CI check that fails the build on DropColumn, DropTable, RenameColumn or AlterColumn without an explicit allow-list comment.
  • Query Store and sys.dm_exec_requests to watch blocking while a migration runs.

Try it yourself

  1. Create a 5-million-row table in a local SQL Server container and time ALTER TABLE ADD col NOT NULL DEFAULT vs ADD col NULL + UPDATE + ALTER COLUMN NOT NULL.
  2. Generate a migration that renames a property and inspect the SQL with dotnet ef migrations script. Then rewrite it as expand/contract.
  3. Run a long SELECT in one session, start a DDL in another, and watch the blocking chain in sys.dm_exec_requests.
  4. Write a batched backfill loop with UPDATE TOP (5000) and measure transaction log usage with sys.dm_db_log_space_usage.
  5. Add a CI step that greps the generated script for DROP COLUMN and sp_rename and fails the build.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Accepting a scaffolded 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.
  • Mistake: Adding a NOT NULL column with 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.
  • Mistake: Running a huge 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.
  • Mistake: Dropping a column in the same release that stops using it. Why it is wrong: The old version is still running during the deploy and rollback brings it back. Instead: Contract one release later.
  • Mistake: Creating indexes offline on hot tables. Why it is wrong: Writes block for the whole build. Instead: Use WITH (ONLINE = ON), ideally off-peak.
  • Mistake: Calling 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.
  • Mistake: Forgetting non-web consumers. Why it is wrong: Background workers, reports and ETL jobs still read the old column after the API moves on. Instead: Search every consumer (and Query Store) before contracting.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions renaming a column Why: Checks the full rename sequence in detail
    How to answer

    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.

  2. When: Candidate mentions running migrations in the pipeline Why: Checks how migrations are applied in CI/CD and why not at start-up
    How to answer

    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.

  3. When: Candidate mentions constraints in the compatibility table Why: Checks WITH NOCHECK, data clean-up and validating constraints later
    How to answer

    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.

🛠 Real-world problems: how you handle them

A one-line migration blocked checkout for six minutes
Situation
[Retail ordering API on Azure SQL, Australia East, ~40 million rows in OrderLines, peak 300 requests per second]. A release added a NOT NULL `CurrencyCode` column and renamed `Qty` to `Quantity` in one EF Core migration, applied by the pipeline during business hours.
Signals
Application Insights showed SQL dependency durations jumping to the 30-second command timeout, a spike of `SqlException` timeouts, and checkout failures. The slot swap health check failed and the old slot kept serving traffic, which then threw `Invalid column name 'Qty'`.
Investigation
`sys.dm_exec_requests` and `sp_WhoIsActive` showed the migration session holding a Sch-M lock on OrderLines with 200+ sessions waiting. The generated script (`dotnet ef migrations script --idempotent`) contained `ALTER COLUMN ... NOT NULL` after a full-table `UPDATE`, plus `sp_rename`. Query Store confirmed every OrderLines query was blocked during the window.
Resolution
Immediate: killed the migration session (the transaction rolled back), redeployed the previous release so the schema and code matched again. Real fix: three releases. Release 1 added `CurrencyCode` with a constant default and a nullable `Quantity`, with dual-writes. A batched backfill job copied `Qty` in 5,000-row transactions. Release 2 switched reads. Release 3 dropped `Qty` and made `Quantity` NOT NULL with `SET LOCK_TIMEOUT` in an off-peak window.
Prevention
A CI step that fails the build when the generated script contains `sp_rename`, `DROP COLUMN` or `ALTER COLUMN ... NOT NULL` without an approved marker; a zero-downtime migration checklist in the PR template; timing every migration against a restored production copy in a pre-production environment; an alert on blocked sessions over 10 seconds.

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.

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me