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

📚 Interview question

An EF Core migration failed halfway through in production and the API is throwing errors. What is your rollback strategy? Compare running the Down migration, writing a forward fix and Azure SQL point-in-time restore, and explain how idempotent scripts and transactions change what state you are left in.

Recovering from a partly applied EF Core migration on Azure SQL: assessing state, forward fix vs Down migration vs point-in-time restore, idempotent scripts, transactional DDL and prevention.

Senior RealWorldScenario Advanced azure-sql ef-core incident-response migrations point-in-time-restore rollback

🎯 Key points

  • First establish the actual state: __EFMigrationsHistory, the schema, and which statements ran; do not guess
  • SQL Server DDL is transactional, so a migration that runs in one transaction rolls back cleanly; steps with suppressTransaction or non-transactional tools can leave partial state
  • Restore service first: redeploy the previous app version if the schema is still compatible with it
  • Prefer a reviewed forward fix over Down methods, which teams rarely exercise and which often drop data
  • Point-in-time restore (Azure SQL: 7 days by default, configurable 1–35 days, plus long-term retention for older backups) restores to a new database and loses every write since
  • Idempotent scripts (--idempotent) check __EFMigrationsHistory per migration, so re-running after a fix is safe
  • Prevention: backward-compatible migrations, tests against real SQL Server in CI, rehearsal on a production-like copy, lock timeouts and blocking alerts during the run, and a written runbook

⏱ 30-second answer

First find out what state the database is actually in: read __EFMigrationsHistory, compare the schema with the expected script, and check the error. On SQL Server each migration normally runs in a transaction, so a failure usually rolls that migration back cleanly; the danger is statements EF Core runs outside a transaction and earlier migrations in the same batch that already committed.

Then restore service: if the schema is still compatible with the previous app version, redeploy it. Fix the problem with a reviewed forward fix, not by running untested Down() methods. Point-in-time restore is the last resort, for real data damage, because it loses every write since the restore point.

The trade-off: a forward fix keeps all data but takes thinking time; a restore is fast to start but expensive in lost writes.

🗣 Full answer (senior)

How I would answer this in an interview

"My first rule is: don't make it worse by guessing. Before touching anything I establish three facts: which migrations are recorded in __EFMigrationsHistory, what the schema actually looks like, and what the error was. On SQL Server, EF Core wraps each migration in a transaction, so if the failing migration was a normal one it has rolled back and the only applied migrations are the earlier ones in the batch. The exceptions are statements that can't run in a transaction, or SQL marked with suppressTransaction: true, and those can leave you half-done.

Then I restore service, which is a separate problem from fixing the schema. If the new code is failing because its migration didn't apply, I redeploy the previous release, which works because our migrations are backward compatible. For example, at [company] a migration that created a unique index failed on [duplicate rows nobody knew existed]. The transaction rolled back, the new slot never swapped in, and the old version kept serving. We cleaned the duplicates with a reviewed script, re-ran the idempotent migration script, and shipped [two hours] later with no data loss.

The mistake I see is reaching for dotnet ef database update <previous> to run the Down methods. Down migrations are almost never tested, and a Down that drops a column drops the data written to it. I treat a forward fix as the default, Down only when it is trivial and reviewed, and point-in-time restore only when data itself has been damaged, because a restore loses every legitimate write since that moment. A rollback plan you haven't rehearsed is a hope, not a plan."


Decision table

Situation Action
Migration failed, its transaction rolled back, old app still compatible Keep or redeploy the old app; fix the migration; re-run the idempotent script
Partially applied (non-transactional step) Write a script that completes or reverses the applied steps; record it in history only when the schema matches
Migration succeeded but new code is broken Redeploy old code (schema is backward compatible); forward-fix the code
Migration destroyed or corrupted data (bad UPDATE, wrong DROP) Point-in-time restore to a new database; copy back the lost data or switch over
No backward compatibility and app is down Emergency forward fix or tested Down, under change control

Forward fix vs Down vs restore

Forward fix Down migration Point-in-time restore
Data written since Kept Often lost (dropped columns) Lost unless merged back
Tested? Reviewed now Usually never Platform feature, but your runbook may not be
Speed Minutes to hours Fast if it works Minutes to hours for large databases, plus switch-over
Best for Most failures Trivial, additive migrations Data damage

Production example

On a [payments API on Azure SQL Business Critical], a migration's CREATE UNIQUE INDEX failed on [1,200] duplicate rows. Because the migration was transactional and backward compatible, the error budget impact was [zero failed requests]. The fix took [two hours], including a reviewed de-duplication script and an idempotent re-run. A point-in-time restore would have discarded [about 40 minutes] of payments.

🔍 What the interviewer is checking

Checks calm incident handling: establishing facts first, separating service restoration from schema repair, and knowing the real cost of each recovery option.

Green flags

  • Reads __EFMigrationsHistory and the schema before acting
  • Knows SQL Server DDL is transactional and where that breaks down
  • Prefers a forward fix; explains why Down methods are risky
  • Knows point-in-time restore creates a new database and loses writes

Red flags

  • "Just run the Down migration" or "restore the backup" as the first move
  • Editing the history table by hand
  • No mention of restoring service first

📚 Learn in depth

1. What "failed halfway" really means

dotnet ef database update  (or the bundle / idempotent script)
  ├─ Migration A  BEGIN TRAN ... INSERT __EFMigrationsHistory ... COMMIT   ✔ applied
  ├─ Migration B  BEGIN TRAN ... CREATE UNIQUE INDEX ✖ error → ROLLBACK      ✘ not applied
  └─ Migration C  never started

On SQL Server, DDL is transactional, so CREATE TABLE, ALTER TABLE and CREATE INDEX roll back with the transaction. EF Core writes the history row in the same transaction, so history and schema agree. Each migration commits separately, so earlier migrations in the batch stay applied.

Partial state happens when:

  • a migration uses migrationBuilder.Sql(..., suppressTransaction: true) (needed for some operations such as certain full-text or database-level statements),
  • a script is applied by a tool that does not use transactions,
  • someone runs parts of a script by hand.

2. Reading the state

SELECT MigrationId, ProductVersion FROM __EFMigrationsHistory ORDER BY MigrationId;

-- Does the schema match what the migration should have produced?
SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('dbo.Orders');
SELECT name, is_unique FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Orders');

Compare against dotnet ef migrations script A B for the failing migration. Every statement is either present or absent.

3. Idempotent scripts

dotnet ef migrations script --idempotent wraps every migration in a check:

IF NOT EXISTS (SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20261101_AddUniqueEmail')
BEGIN
    CREATE UNIQUE INDEX ...
END;

So once the cause is fixed you can run the same script again and it applies only what is missing. Bundles (dotnet ef migrations bundle) behave the same way, because they consult the history table.

4. Point-in-time restore on Azure SQL

  • Azure SQL Database keeps automated backups (full, differential, log) that support restore to any point in the retention window: 7 days by default, configurable from 1 to 35 days, plus optional long-term retention.
  • A restore always creates a new database. You then either copy specific data back (safer) or rename and repoint the app (loses all writes since the restore point).
  • Restore time depends on size and log volume; large databases can take hours. Know your number before the incident.
  • For data residency, restore within the same region (Australia East or Australia Southeast) so personal information under the Privacy Act stays where your privacy policy says it is.

5. Why Down methods are risky

Scaffolded Down methods mirror Up mechanically. A Down for AddColumn is DropColumn, which deletes every value written since. A Down for migrationBuilder.Sql is empty unless someone wrote it. And they are rarely run in any test, so the first execution is in production under pressure.

6. A rehearsed runbook

  1. Stop the pipeline; do not retry automatically.
  2. Capture the error, the history table and the schema.
  3. Restore service (old app or feature flag).
  4. Decide: forward fix, reviewed Down, or restore.
  5. Apply the fix through the same pipeline path.
  6. Post-incident review: why did the test environment not catch it?

Try it yourself

  1. Write a migration that creates a unique index, seed duplicates, apply it, and confirm the history table and schema after the failure.
  2. Add a migrationBuilder.Sql("...", suppressTransaction: true) step before a failing statement and observe the partial state.
  3. Generate an idempotent script and run it twice against the same database.
  4. In a test subscription, run a point-in-time restore of a small Azure SQL database and time it.
  5. Write the runbook for your own service and do a tabletop exercise with the team.

💻 Code

A pre-flight check you can run in the pipeline before applying migrations, so data problems fail the build instead of production:

namespace Orders.Deploy;

using Microsoft.EntityFrameworkCore;

public sealed record PreflightResult(bool Ok, string? Reason);

public static class MigrationPreflight
{
    // Run against production (read-only login) before applying the migration that adds a unique index.
    public static async Task<PreflightResult> CheckUniqueEmailAsync(OrdersDbContext db, CancellationToken ct)
    {
        var duplicates = await db.Database
            .SqlQuery<int>($"""
                SELECT COUNT(*) AS [Value] FROM (
                    SELECT Email FROM Customers WHERE Email IS NOT NULL
                    GROUP BY Email HAVING COUNT(*) > 1) d
                """)
            .SingleAsync(ct);

        return duplicates == 0
            ? new PreflightResult(true, null)
            : new PreflightResult(false, $"{duplicates} duplicate emails would fail IX_Customers_Email");
    }
}

Applying migrations from the pipeline with an idempotent script and a lock timeout:

# Build once, review in the PR, apply the same artefact
dotnet ef migrations script --idempotent --output artefacts/migrate.sql \
  --project src/Orders.Infrastructure --startup-project src/Orders.Api

# Apply with a short lock timeout so blocking fails fast instead of piling up
sqlcmd -S "$SQL_SERVER" -d Orders --authentication-method ActiveDirectoryDefault \
  -b -Q "SET LOCK_TIMEOUT 5000;" -i artefacts/migrate.sql

Reading the state after a failure:

SELECT TOP (5) MigrationId FROM __EFMigrationsHistory ORDER BY MigrationId DESC;
SELECT name, is_unique FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.Customers');

⚠ Common mistakes

  • Mistake: Re-running the pipeline straight away. Why it is wrong: The same data problem fails it again, or a non-transactional step runs twice. Instead: Stop, read the history table and schema, then decide.
  • Mistake: Running dotnet ef database update <previous> to execute Down methods. Why it is wrong: Down methods are untested and often drop columns, deleting data written since. Instead: Default to a reviewed forward fix.
  • Mistake: Treating point-in-time restore as an undo button. Why it is wrong: It creates a new database and loses every write since the restore point. Instead: Use it for data damage, and copy back only what was lost.
  • Mistake: Inserting a row into __EFMigrationsHistory by hand to "skip" a migration. Why it is wrong: History and schema now disagree, and the next migration fails in a confusing way. Instead: Only record a migration once the schema matches it.
  • Mistake: Mixing app rollback and schema rollback. Why it is wrong: Rolling the schema back while new code runs causes a second outage. Instead: Restore service with app versions first; fix the schema separately.
  • Mistake: Testing migrations only against an empty database. Why it is wrong: Real data (duplicates, NULLs, long strings) is what makes them fail. Instead: Rehearse against a restored, masked copy of production.

🏛 Senior insight: trade-offs

The best rollback strategy is not needing one. In practice that means three habits: migrations that are backward compatible, so the old app version is always a safe place to retreat to; migrations tested in CI against real SQL Server and rehearsed on a restored, masked production copy, so data problems surface before release; and a monitored run (lock timeout, blocked-session alerts, a person watching) so a problem is stopped in seconds. Everything else in this answer is the fallback for when that discipline slipped.

If a team does rely on Down methods, they must be exercised in the same CI tests as Up (apply, roll back, apply again); otherwise treat them as untested code. I also want the runbook written and rehearsed before the incident, including the measured restore time for our database size. "We can restore" is not a plan; "a restore of our 400 GB database to a new server takes about 90 minutes and we copy back with this script" is.

Option When it fits Cost When not to
Redeploy previous app Schema still compatible Minutes New schema broke old code
Forward fix migration Most failures Time to write and review Data already destroyed
Reviewed, tested Down migration Trivial additive change Data in new columns lost Anything that drops data
Point-in-time restore Data corruption or deletion Lost writes, switch-over effort Schema-only failures

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the pipeline step that applies migrations Why: Checks scripts vs bundles vs Migrate() and pipeline design
    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.

  2. When: Candidate mentions migration bundles Why: Checks what a bundle is and when to prefer it
    How to answer

    dotnet ef migrations bundle builds a single executable (efbundle) that contains your compiled migrations and applies the pending ones to whatever connection string you pass (./efbundle --connection "..."). The target machine needs no .NET SDK, no source and no dotnet-ef tool; with --self-contained -r linux-x64 it does not even need the .NET runtime. It runs migrations idempotently against __EFMigrationsHistory, so it fits a CI/CD release stage or a Kubernetes job. Choose an idempotent SQL script (dotnet ef migrations script --idempotent) instead when a DBA must review and run the SQL, when change control requires the exact statements as an artefact, or when the pipeline cannot reach the database with an executable. Both are better than Database.Migrate() at app start-up.

  3. When: Candidate says the test environment did not catch the failure Why: Checks rehearsal against realistic data and CI gates
    How to answer

    Apply every migration in CI against a real SQL Server (a Testcontainers container, not the in-memory provider), from an empty database and from the previous release's schema. Then rehearse it in pre-production against a restored, masked copy of production to catch real data problems (duplicates, NULLs, oversized strings) and to time it. Add a CI gate that scans the idempotent script for destructive operations, and a test that dotnet ef migrations has-pending-model-changes returns nothing.

🛠 Real-world problems: how you handle them

Unique index migration failed on hidden duplicates
Situation
[Customer portal API on Azure SQL, Australia Southeast, ~3 million customers]. A release added a unique index on `Customers.Email` through an EF Core migration applied by an idempotent script in the release pipeline, before the slot swap.
Signals
The pipeline's migration step failed with `CREATE UNIQUE INDEX statement terminated because a duplicate key was found`. The staging slot's health check returned 500 because the new code queried a table the failed migration had not created. Production traffic stayed on the old slot.
Investigation
Queried `__EFMigrationsHistory`: the two earlier migrations in the batch were recorded, the failing one was not. `sys.indexes` and `sys.tables` confirmed its changes had rolled back with the transaction. A `GROUP BY Email HAVING COUNT(*) > 1` query found [1,200] duplicate emails, mostly case variants created before email normalisation existed.
Resolution
Immediate: confirmed production was healthy on the old slot (the earlier migrations were additive and backward compatible) and paused the release. Real fix: a reviewed, batched de-duplication script that merged accounts with the product owner's agreement, a normalised `EmailNormalised` column, then re-ran the same idempotent script. The release shipped two hours later.
Prevention
A pipeline pre-flight query for each constraint-adding migration, rehearsal on a restored masked production copy in pre-production, and a runbook entry for partial migration failures.

How to tell it (STAR)

**S:** At [company] we released a change that added a unique index on customer email, applied by our pipeline before the slot swap. **T:** The migration step failed and I had to decide how to recover. **A:** I checked the history table and the schema to confirm the failing migration had rolled back and the earlier ones were backward compatible, so production was safe on the old slot. I found [1,200] duplicate emails, wrote a reviewed merge script with the product owner, and re-ran the idempotent script. Then I added pre-flight checks and rehearsal on a production copy. **R:** Customers saw [zero] errors, we shipped [two hours] later, and the pre-flight checks caught [two] similar problems in the following [quarter].

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me