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

📚 Interview question

Tell me about a database migration that failed in production. What happened, how did you decide between rolling back, restoring and fixing forward, how did you get the system healthy, and what did you change about how migrations are written and deployed?

A STAR story for a failed EF Core or SQL migration in production: impact, partial state, rollback vs restore vs forward fix, recovery, and safer migration practice (expand/contract, idempotent scripts, rehearsal).

Senior RealWorldScenario Advanced azure-sql ef-core migrations real-world star-story zero-downtime

🎯 Key points

  • Failure mode named: lock or timeout on a large table, existing data violating a new constraint, partial apply
  • Assessed the state first: which statements ran, __EFMigrationsHistory, schema vs code
  • Decision: Down migration vs forward fix vs point-in-time restore, by data-loss cost
  • Communicated: incident channel, product owner on impact, DBA/platform on recovery choice
  • Expand/contract (add nullable, backfill, then enforce) so old and new app versions both work
  • Data validated before constraints: find violating rows, clean, add WITH NOCHECK then validate
  • Migrations run once as a pipeline step: bundle or idempotent script that is safe to re-run after a partial failure
  • Rehearsed on a production-sized copy with a rollback / forward-fix plan written in advance

⏱ 30-second answer

My story is a migration that [added a NOT NULL column with a default / created an index] on a [80M-row] table and timed out halfway during deploy, leaving the schema partly changed while the new app version was already rolling out. I first assessed the state (__EFMigrationsHistory, which objects existed), then chose a forward fix over a Down migration or a point-in-time restore, because no data was lost and a restore would have thrown away [two hours] of orders. I stabilised by [rolling the app back to the previous version, which still worked with the schema], then re-applied the change as an expand/contract sequence with batched backfill. Afterwards migrations ran as a separate, rehearsed pipeline step on a production-sized copy. Result: [N min] of errors, no data loss. The trade-off: restores are clean but lose every write since the restore point.

🗣 Full answer (senior)

How I would answer this in an interview

"At [company] we deployed [the orders service] with an EF Core migration that [added a non-nullable Region column with a default and an index] to a table with [80 million] rows. The migration ran at app startup through Database.Migrate(). On [Azure SQL] it took a schema-modification lock and ran past the command timeout, so the first instance failed to start; other instances raced to run it too. For about [15] minutes the API returned errors on [order creation].

I was [the release lead]. First I stopped the rollout and rolled the app back to the previous version, which didn't need the new column, so customers recovered. Then I checked the state: the column existed but the index didn't, and the migration wasn't recorded in __EFMigrationsHistory. Running the Down migration would have dropped a column that was half-populated, and a point-in-time restore would have lost [two hours] of orders, so I chose a forward fix.

I split the change: add the column as nullable, backfill in batches of [5,000] in a background job, build the index with ONLINE = ON and RESUMABLE = ON, then make it NOT NULL in a later release. We moved migrations out of startup into a separate pipeline step using an EF Core migration bundle, rehearsed against a restored copy of production, with a lock timeout so it fails fast instead of blocking. Since then [N] large migrations have shipped with zero downtime. My lesson: the database is the one part of a deployment you can't just redeploy, so every change has to work with both the old and the new code."


Rollback vs restore vs forward fix

Option When it fits Risk
Roll back the app only Schema change is additive; old code still works Low; buys time
Down migration Change fully applied, reversible, no new data in it Drops columns or data written since
Forward fix Partial apply, cause understood Second change under pressure
Point-in-time restore (Azure SQL) Data corrupted or destroyed Loses every write since restore point; takes time on big DBs

What makes migrations fail in production

Cause Prevention
Long locks on large tables Expand/contract, online index ops, batching
Existing bad data violates new constraint Clean data first; add constraint WITH NOCHECK then validate
Migration at startup across many instances Run once, as a pipeline step
Timeout Rehearse on prod-sized copy; set command timeout deliberately
Non-transactional DDL partly applied Idempotent scripts; small migrations

Production example

Template: [orders] migration on [80M] rows timed out; [15] min of errors; app rolled back in [N] min; forward fix as expand/contract with batched backfill; migrations now a separate rehearsed step; [N] large migrations since with no downtime.

🔍 What the interviewer is checking

Checks judgement when state is irreversible: assessing before acting, choosing between rollback, restore and forward fix by data-loss cost, and making migrations safe by design afterwards.

Green flags

  • Assesses the partial state before acting
  • Explains the data-loss trade-off of each option
  • Keeps the old app version compatible (expand/contract)
  • Moves migrations to a rehearsed, separate step; gives numbers

Red flags

  • Restores or runs Down by reflex
  • Migrations at startup with no awareness of the risk
  • Blames the author; no process change

📚 Learn in depth

1. What the interviewer is really assessing

This checks judgement under pressure with irreversible state: do you look before you act, do you understand what each recovery option costs in data, and did you change the process so migrations are safe by design. It also checks EF Core and SQL knowledge: transactions around DDL, locks, and how __EFMigrationsHistory works.

2. How EF Core applies migrations

dotnet ef migrations bundle -> efbundle.exe
   |
   v
For each pending migration (in order):
   BEGIN TRAN (per migration, on SQL Server, unless suppressed)
      DDL / SQL statements
      INSERT INTO __EFMigrationsHistory
   COMMIT

On SQL Server most DDL is transactional, so a failed migration usually rolls back as a whole, but statements marked suppressTransaction: true (and some operations) aren't, and a timeout can leave you unsure what committed. Running Migrate() at startup across several instances adds races; EF Core 9 added a migration lock to stop concurrent application, but long locks on the table still hurt live traffic.

3. Expand/contract

Release N:   add nullable column; app writes both old and new
Job:         backfill in batches
Release N+1: app reads new column
Release N+2: make NOT NULL / drop old column

At every step the schema works with both the current and the previous app version, so app rollback is always safe.

4. Frameworks for telling it

STAR, with the decision (rollback vs restore vs forward fix) as the centrepiece of the Action. SOAR fits well: the obstacle is the partial state.

5. How it is scored

Weak: "we restored the database." Good: describes the recovery. Strong: explains the decision with data-loss trade-offs. Excellent: changed migration practice (expand/contract, bundles, rehearsal, lock timeouts) and quantifies the result.

6. Adapting the story

The same story answers "a mistake you made", "a time you improved a deployment process" and "a decision under pressure". For a non-technical audience: "A database change locked a huge table during release; I rolled the app back, fixed it in smaller steps, and changed how we release database changes."

Try it yourself

  1. Create a test table with a few million rows and add a NOT NULL column with a default; time it and watch locks in sys.dm_tran_locks.
  2. Redo it as nullable + batched backfill + NOT NULL and compare.
  3. Build an EF Core migration bundle and run it against a local database.
  4. Generate an idempotent script with dotnet ef migrations script --idempotent and read it.
  5. Write and time your STAR version.

💻 Code

The forward fix as expand/contract, and running migrations as a pipeline step.

namespace Orders.Data.Migrations;

// Release N: expand only. Nullable column, no long lock, old app version unaffected.
public partial class AddOrderRegionNullable : Migration
{
    protected override void Up(MigrationBuilder mb)
    {
        mb.AddColumn<string>(name: "Region", table: "Orders", type: "varchar(10)", nullable: true);

        // Online, resumable index build (Azure SQL / SQL Server Enterprise) so writes continue.
        mb.Sql("CREATE INDEX IX_Orders_Region ON dbo.Orders(Region) WITH (ONLINE = ON, RESUMABLE = ON);",
            suppressTransaction: true);
    }

    protected override void Down(MigrationBuilder mb)
    {
        mb.Sql("DROP INDEX IF EXISTS IX_Orders_Region ON dbo.Orders;", suppressTransaction: true);
        mb.DropColumn(name: "Region", table: "Orders");
    }
}
-- Backfill in batches (run by a job, not the migration), short transactions, low lock footprint
SET LOCK_TIMEOUT 5000;
WHILE 1 = 1
BEGIN
    UPDATE TOP (5000) dbo.Orders SET Region = 'AU' WHERE Region IS NULL;
    IF @@ROWCOUNT = 0 BREAK;
    WAITFOR DELAY '00:00:00.200';
END
# Pipeline step, run once before the app rollout (not Database.Migrate() at startup)
dotnet ef migrations bundle --project src/Orders.Data --startup-project src/Orders.Api -o efbundle --self-contained
./efbundle --connection "$ORDERS_DB"

⚠ Common mistakes

  • Mistake: Running the Down migration by reflex. Why it is wrong: It can drop columns holding new data. Instead: Assess state first and weigh data loss.
  • Mistake: Restoring the database as the first move. Why it is wrong: Loses every write since the restore point. Instead: Use PITR only when data is damaged; otherwise roll the app back and fix forward.
  • Mistake: Shipping a migration with no recovery plan. Why it is wrong: The team improvises under pressure and loses time arguing about options. Instead: Write the plan in the PR: is app rollback safe, is Down safe, what is the forward fix, when would we restore.
  • Mistake: Adding a constraint without checking existing data. Why it is wrong: The migration fails on the first bad row, often after minutes of work. Instead: Query for violating rows first, clean them in a data migration, add the constraint WITH NOCHECK, then validate it separately.
  • Mistake: Running migrations in Program.cs on every instance. Why it is wrong: Races, startup failures, long locks during rollout. Instead: A separate pipeline step with a bundle or idempotent script.
  • Mistake: Big-bang schema changes on large tables. Why it is wrong: Long locks and timeouts. Instead: Expand/contract with batched backfill.
  • Mistake: Not rehearsing on production-sized data. Why it is wrong: A 2-second migration in test can take 40 minutes in production. Instead: Rehearse on a restored, masked copy.
  • Mistake: Going quiet during the incident. Why it is wrong: Product, support and other teams make their own guesses. Instead: Regular updates in the incident channel with impact, decision and next update time.
  • Mistake: Blaming the migration's author, or no numbers. Why it is wrong: It was a process gap, and impact is unclear. Instead: Describe the guardrail you added; give minutes of errors and data lost (ideally none).

🏛 Senior insight: trade-offs

The senior signal is treating the database as the irreversible part of a release and owning the incident: you designed for both app versions working against the schema, you chose recovery options by their data-loss cost, and you made the call and communicated it. In the story, say who you involved and how: you opened the incident channel, told the product owner what customers were seeing and that no orders would be lost, agreed the forward-fix approach with the DBA or platform team, and posted updates every [15] minutes until it was closed. That is what leadership looks like in an incident: a clear decision, its trade-off, and everyone aligned.

Why bundles and idempotent scripts help: a migration bundle is a single executable built from the exact migrations in the release, so the pipeline applies the same, versioned set once, with no SDK on the agent and no race between app instances. An idempotent script (dotnet ef migrations script --idempotent) checks __EFMigrationsHistory before each migration, so after a partial failure you can re-run it safely and it only applies what's missing. Expand/contract means you first expand the schema in a backwards-compatible way (add a nullable column, a new table), move data across, and only contract (enforce NOT NULL, drop the old column) once no running code needs the old shape.

Practice Benefit Cost When not to
Expand/contract App rollback always safe More releases per change Tiny tables, internal tools
Migration bundle as pipeline step Runs once, auditable Pipeline work Local dev
Idempotent SQL script reviewed by a DBA Full visibility; safe to re-run Slower Teams without DBA support
Rehearsal on prod-sized copy Realistic duration and locks Restore time, data handling (mask personal data) Never skip for large tables
Online / resumable index ops Writes continue Edition/tier dependent Not available on your tier

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions rollback, Down migrations or point-in-time restore. Why: Checks the technical detail of each recovery option and the state each leaves.
    How to 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.

  2. When: Candidate mentions expand/contract or zero-downtime migrations. Why: Checks they can apply the pattern to renames, NOT NULL columns and backfills.
    How to 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.

  3. When: Candidate says they now test migrations before production. Why: Checks what that testing actually involves.
    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

NOT NULL column on an 80M-row table times out mid-deploy
Situation
[Orders service] on [Azure SQL, Business Critical], [Orders] table [~80M] rows, [~200] orders a minute at peak. Release [x.y] added a non-nullable `Region` column with a default and an index, applied with `Database.Migrate()` at startup. I was [the release lead / on call].
Signals
New instances failing to start (migration timeout in startup logs); 500s on order creation for [~15] minutes; `LCK_M_SCH_M` / `LCK_M_IX` waits in Azure SQL; blocked sessions behind the ALTER; the pipeline still trying to roll out more instances.
Investigation
Stopped the rollout. Checked state: `Region` column existed, the index didn't, and the migration row was missing from `__EFMigrationsHistory`; confirmed with `sys.indexes` and `sys.columns`. Ruled out data damage (no deletes or updates beyond the default). Confirmed the previous app version didn't reference the new column, so it would work against the partial schema. Rehearsed the original migration later on a restored copy: [~35] minutes with a schema lock.
Resolution
Mitigation: rolled the app back to the previous version (slot swap), killed the blocked migration session, errors stopped within [N] minutes. Real fix: forward fix as expand/contract: nullable column (already present, migration made idempotent), batched backfill job of [5,000] rows per batch, online resumable index build, NOT NULL constraint in a later release once backfill finished. Point-in-time restore rejected because it would have lost [~2 hours] of orders.
Prevention
Migrations removed from startup; an EF Core migration bundle runs as a separate pipeline stage before app rollout, with a lock timeout; rehearsal on a masked, production-sized copy for any migration touching tables over [1M] rows; a pull-request checklist for migrations (expand/contract, online ops, backfill plan, Down safety); a short ADR documenting the approach.

How to tell it (STAR)

**S:** At [company], a release of [our orders service] included a migration adding a required column and index to an [80-million-row] table, and it timed out halfway, so order creation failed for about [15] minutes. **T:** As [release lead] I had to restore service without losing orders and make sure it couldn't happen again. **A:** I stopped the rollout and rolled the app back, since the old version still worked with the partial schema. I checked exactly what had applied, ruled out the Down migration and a point-in-time restore because they'd have lost [two hours] of orders, and re-did the change as expand/contract: nullable column, batched backfill, online index, then NOT NULL in a later release. I also moved migrations out of startup into a separate, rehearsed pipeline step with a lock timeout. **R:** No orders were lost, and since then we've shipped [N] large migrations with zero downtime.

More in Production Incidents

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me