The deploy you rolled back that did not roll back the data
A team ships a migration that renames a column from email to primary_email, backfills a new notification_preference column by parsing a JSON blob, and drops the original JSON blob column. The application deploy fails health checks. The on-call engineer reverts the application to the previous version. The old application code tries to read from email, which no longer exists. The revert made things worse.
The root cause is not a missing rollback script. It is a missing mental model: application code and database state are coupled but do not move in lockstep, and data transformations can cross a point of no easy return where reversal requires reconstruction, not just an undo command.
This guide gives you a reusable structure for planning, testing, and executing rollbacks for changes that touch data -- not just application code.
Quick-start path
If you need a rollback plan for a data change shipping this week:
- Classify every change in the migration as additive, destructive, or transformative (definitions below).
- For each destructive or transformative change, write the specific reversal step and confirm the original data still exists or can be reconstructed.
- Identify the point of no easy return -- the step after which reversal requires more than running a down-migration.
- Take a verified backup before the point of no easy return. Verify means you restore it to a scratch environment and run a query that proves data is usable, not just that a file exists.
- Fill out the go/no-go checklist below. If any row is "no" and has no documented exception, do not proceed.
- Run the migration in a staging environment with the old application version still running and confirm it does not break reads or writes.
If you have more time, read the full guide and adapt the worksheet to your deployment pipeline.
Three categories of database change and why they matter for rollback
Every schema or data change falls into one of three categories. The category determines what rollback costs.
Additive changes
Adding a column, a table, or an index. The old application version ignores the new object. Rollback is simple: drop the new object. Risk is low, but not zero -- a new NOT NULL column without a default will break inserts from the old application version.
Destructive changes
Dropping a column, table, or constraint. Removing data. The old application version expects the removed object. Rollback requires recreating the object and restoring data from a backup or replica. If you did not preserve the data, rollback is reconstruction from logs, replicas, or nothing.
Transformative changes
Renaming a column, splitting a table, merging rows, normalizing denormalized data, changing a column type, parsing a blob into structured fields. The old and new shapes are both internally consistent, but converting between them may lose information. Rollback requires a reverse transformation, and that reverse transformation may not be lossless. If you parsed a JSON blob into three columns and dropped the blob, you cannot perfectly reconstruct the blob from the columns alone -- key ordering, whitespace, and any fields you did not extract are gone.
Why the category matters: Additive changes can be rolled back with a single DDL statement. Destructive and transformative changes need preserved source data and a tested reverse path. Most incidents happen when a team treats a transformative change as if it were additive.
The expand-migrate-contract pattern and where rollback lives in each phase
The safest way to ship a data change is in three separate deployments: expand (add the new structure), migrate (copy or transform data), and contract (remove the old structure). Each phase has a different rollback profile.
Phase 1: Expand
You add the new column, table, or index alongside the old one. Both the old and new application versions work. The new version writes to both old and new structures (dual-write) or the new structure is populated by a background job.
Rollback: Drop the new structure. No data loss because the old structure is untouched. This is the cheapest rollback you will ever get.
Phase 2: Migrate
You backfill the new structure from the old one. The old structure still exists and is still the source of truth. The new application version may start reading from the new structure.
Rollback: Stop the backfill. Optionally truncate the new structure. Switch reads back to the old structure. Still cheap, because the old data is intact.
Caution: If the new application version writes only to the new structure during this phase, the old structure drifts. Rollback now requires merging changes back. Dual-write avoids this, but dual-write has its own bugs -- you need to decide which write wins on conflict.
Phase 3: Contract
You drop the old column, table, or blob. The old application version no longer works against this database.
Rollback: You need a backup of the old structure, a script to recreate it, and a script to populate it from the new structure (reverse transformation). If the transformation was lossy, some data is unrecoverable from the new structure alone. This is the point of no easy return.
The key insight: Delay the contract phase. Keep the old structure around for a soak period -- hypothetically, one to two weeks depending on your deployment cadence and incident response patterns. The cost is a wider schema and some extra storage. The benefit is that rollback remains cheap for the entire soak period.
Worked hypothetical scenario: splitting a user preferences JSON blob into columns
Setup
A hypothetical team has a users table with a preferences JSONB column. The column contains keys like theme, locale, timezone, and email_digest_frequency. Some rows have additional keys added by older application versions that are no longer used (beta_features, legacy_layout). The team wants to extract the four active keys into proper columns for query performance and validation.
Expand phase
Migration adds four nullable columns: pref_theme, pref_locale, pref_timezone, pref_email_digest_frequency. The old preferences column stays. The new application version writes to both the new columns and the JSON blob on every update.
Verification query (hypothetical):
-- After deploying new app version, confirm dual-write is active
SELECT count(*) FROM users
WHERE updated_at > NOW() - INTERVAL '1 hour'
AND pref_theme IS NOT NULL
AND preferences->>'theme' IS NOT NULL
AND pref_theme = preferences->>'theme';
If this count does not match the total recently-updated rows, dual-write has a bug.
Migrate phase
A background job backfills the four columns from the JSON blob for all existing rows. The job processes in batches of 1,000 with a 500ms pause between batches to limit database load.
Verification query (hypothetical):
-- Confirm backfill completeness
SELECT count(*) FROM users WHERE pref_theme IS NULL AND preferences->>'theme' IS NOT NULL;
-- Should return 0 when backfill is complete
The team switches reads to the new columns. The old code path (reading from JSON) is behind a feature flag. If the new columns return wrong data, the flag flips reads back to JSON.
Rollback at this point: Flip the feature flag. No data loss, no schema change.
Contract phase (delayed)
Two weeks after the read switch, the team drops the preferences column.
Before dropping, the team:
- Takes a logical backup of the
preferencescolumn:CREATE TABLE users_preferences_backup AS SELECT id, preferences FROM users; - Verifies the backup:
SELECT count(*) FROM users_preferences_backup;matchesSELECT count(*) FROM users; - Confirms that no application code references
preferences(code search, not just grep -- check ORM mappings, raw SQL strings, and reporting queries). - Documents that the backup preserves all JSON keys, including unused ones like
beta_features. The new columns do not contain these keys, so the reverse transformation from columns back to JSON would lose them.
Point of no easy return: Dropping the preferences column. After this, restoring the original JSON requires the backup table. If the backup table is also dropped (say, by a cleanup script three months later), the unused keys are gone permanently.
What the team would do if rollback were needed after contract
- Recreate the
preferencescolumn:ALTER TABLE users ADD COLUMN preferences JSONB; - Populate it from the backup:
UPDATE users SET preferences = b.preferences FROM users_preferences_backup b WHERE users.id = b.id; - For rows created after the backup, synthesize JSON from the new columns. These rows will not have the unused keys.
- Deploy the old application version that reads from JSON.
- Confirm reads work: run the application's test suite against the restored database.
Total hypothetical recovery time: 30-90 minutes depending on table size and whether the team rehearsed the restore.
Forward repair: the rollback alternative most teams underuse
When rollback is expensive or impossible, writing a targeted fix-forward migration is often faster and less risky than restoring a backup. But it requires that you can identify the affected rows and know the correct value. This section walks through what forward repair looks like in practice.
When forward repair is the right choice
Forward repair fits when three conditions hold: (1) you can identify exactly which rows are wrong, (2) you know or can compute the correct value for each row, and (3) the cost of leaving the system in the new schema while fixing data is lower than reverting to the old schema.
Hypothetical forward-repair walkthrough: correcting a wrong default
A hypothetical team adds a billing_cycle column to an accounts table and backfills it with the value monthly. After deployment, a support engineer notices that roughly 50,000 accounts on annual plans now show monthly. The old schema had billing cycle stored inside a plan_details JSON column as "cycle": "annual", but the backfill script used a hardcoded default instead of reading the JSON.
Step 1: Quantify the damage.
-- Hypothetical: find accounts where the new column disagrees with the source of truth
SELECT count(*) FROM accounts
WHERE billing_cycle = 'monthly'
AND plan_details->>'cycle' = 'annual';
-- Hypothetical result: 50,412 rows
This query works because the team has not yet dropped the plan_details column -- they are still in the migrate phase. The source of truth is still available.
Step 2: Write a targeted correction.
-- Hypothetical: fix the affected rows
UPDATE accounts
SET billing_cycle = plan_details->>'cycle'
WHERE billing_cycle = 'monthly'
AND plan_details->>'cycle' != 'monthly';
Step 3: Verify the fix.
-- Hypothetical: confirm no remaining mismatches
SELECT count(*) FROM accounts
WHERE billing_cycle != plan_details->>'cycle';
-- Should return 0
Step 4: Determine whether downstream effects need compensation. If any invoices were generated between the bad backfill and the correction, those invoices used the wrong billing cycle. Forward repair of the accounts table does not fix already-generated invoices. The team needs a second repair query or a manual review for affected invoices.
Why forward repair is not always available
Forward repair fails when any of these conditions hold:
- The source of truth is gone. If the team had already dropped
plan_details, they would have no way to determine which accounts should beannual. The backup table would be needed, and at that point you are doing a restore, not a forward repair. - The correct value is ambiguous. If the backfill corrupted data in a way that makes the correct value unknowable (e.g., a hash function was applied), no query can reverse it.
- The error is in the schema, not the data. If you chose the wrong column type (e.g., integer for a value that needs decimal precision), a forward repair requires an
ALTER COLUMNthat may lock the table, and the data already written may have lost precision irreversibly.
The decision between forward repair and rollback is not philosophical -- it depends on whether the original data or a reliable derivation of it is still accessible. This is one more reason to delay the contract phase: it keeps forward repair viable longer.
Go/no-go checklist and recovery ownership (copyable worksheet)
Copy this worksheet into your migration pull request or deployment document. Fill in every row before proceeding. If any required row is "No" without a documented exception, stop and resolve it.
Usage instructions: One engineer fills this out as part of the migration PR. A second engineer reviews it before the migration is approved. During deployment, the deploying engineer confirms the pre-deployment rows are still accurate. After deployment, the deploying engineer fills in the post-deployment rows and posts the completed checklist in the deployment channel.
## Database Change Rollback Plan
### Change summary
Migration name: _______________________________________________
Change category: [ ] Additive [ ] Destructive [ ] Transformative
One-sentence description: _____________________________________
Point of no easy return (specific step): ______________________
Recovery owner (name, not team): ______________________________
Escalation contact if recovery owner unavailable: _____________
Forward-repair feasible after contract? [ ] Yes [ ] No [ ] TBD
If yes, describe data source for correction: ________________
### Pre-deployment checks
| # | Check | Status | Evidence or exception |
|---|----------------------------------------------------------|--------|------------------------------|
| 1 | Backup taken and restore tested in scratch environment | Yes/No | Backup ID: _____, test date: |
| 2 | Old app version works against new schema (tested) | Yes/No | Test environment: _________ |
| 3 | New app version works against old schema (tested) | Yes/No | Test environment: _________ |
| 4 | Reverse migration script exists and has been run once | Yes/No | Script location: __________ |
| 5 | No DROP or destructive step before soak period ends | Yes/No | Soak end date: ____________ |
| 6 | External systems notified if schema affects APIs/exports | Yes/No | Systems: __________________ |
| 7 | Monitoring alert exists for error rate on affected tables | Yes/No | Alert name: _______________ |
| 8 | Forward-repair script drafted for known failure modes | Yes/No | Script location: __________ |
### Post-deployment checks (fill within 30 minutes of deploy)
| # | Check | Status | Evidence |
|---|----------------------------------------------------------|--------|------------------------------|
| 9 | Verification query confirms data correctness | Yes/No | Query + result: ___________ |
|10 | Application error rate unchanged or within threshold | Yes/No | Dashboard link: ____________ |
|11 | Old app version still deployable (image/artifact exists) | Yes/No | Artifact ID: ______________ |
### Soak period sign-off (fill at soak end date)
| # | Check | Status | Evidence |
|---|----------------------------------------------------------|--------|------------------------------|
|12 | No rollbacks triggered during soak period | Yes/No | Incident log: _____________ |
|13 | Backup retention extended or contract phase approved | Yes/No | Retention policy: __________ |
Filled example (hypothetical):
Migration name: 20240615_split_user_preferences
Change category: [x] Transformative
One-sentence description: Extract theme, locale, timezone, email_digest_frequency
from users.preferences JSONB into dedicated columns.
Point of no easy return: DROP COLUMN preferences (scheduled for Phase 3,
not before 2024-07-01)
Recovery owner: Jamie Chen
Escalation contact: Pat Rivera (database team lead)
Forward-repair feasible after contract? [x] Yes
If yes, describe data source for correction: users_preferences_backup
table preserves full JSONB; four active keys can also be recomputed
from dedicated columns, but unused keys (beta_features, legacy_layout)
exist only in backup.
Pre-deployment checks:
1. Yes -- Backup ID: snap-20240615-0800, tested 2024-06-15 in scratch-db-3
2. Yes -- Tested in staging-blue with app version 4.11.2
3. Yes -- Tested in staging-green with app version 4.12.0-rc1
4. Yes -- Script at db/rollbacks/20240615_restore_preferences.sql, ran in scratch-db-3
5. Yes -- Soak end date: 2024-07-01
6. Yes -- Analytics pipeline team notified (reads preferences column in nightly export)
7. Yes -- Alert: "users-table-error-rate" in PagerDuty
8. Yes -- db/repairs/20240615_fix_preferences_backfill.sql handles null-theme case
Comparing realistic options for rollback strategy
| Strategy | When it works | When it fails | Cost |
|---|---|---|---|
| Reverse migration script | Additive changes, simple renames with alias. | Lossy transformations. The reverse script produces a schema, but the data in it is incomplete. | Low. A SQL file in the repo. |
| Backup and restore | Any change, if backup is fresh and tested. | Backup is stale (hours of writes lost), or restore has never been tested and fails on a constraint. | Medium. Storage for backup, time to restore, write downtime during restore. |
| Dual-write with feature flag | Transformative changes during expand and migrate phases. | If dual-write logic has bugs, the two structures diverge and you do not know which is correct. | Medium-high. Dual-write code, flag infrastructure, verification queries. |
| Forward repair | When you can identify affected rows and know the correct value. Source of truth still exists (old column, backup table, or application logs). | When the correct value is unknowable, the source of truth is gone, or the error is in the schema itself rather than the data. | Variable. Requires understanding the exact error. Can be very fast for simple cases (one UPDATE), or complex when downstream effects need compensation. |
| Point-in-time recovery (PITR) | Catastrophic data loss with no targeted fix. | Reverts all changes to the database, not just the migration. Every write from every user since the recovery point is lost. | Very high. Usually a last resort. |
Choosing between forward repair and rollback is the most common real-time decision during a migration incident. The question is not "can we go back?" but "is the data we need to compute correct values still accessible?" If the old structure is still present (you delayed the contract phase), forward repair is almost always faster. If the old structure is gone, you are choosing between backup restore and PITR, and both cost you recent writes.
Failure symptoms, corrective actions, and escalation points
| Symptom | Likely cause | Corrective action | Escalate if... |
|---|---|---|---|
| Old app version crashes after migration | Migration removed or renamed an object the old version needs | Deploy new app version or run reverse migration to restore the object | Reverse migration does not exist or fails |
| New app version returns wrong data after migration | Backfill is incomplete or transformation logic has a bug | Flip feature flag to read from old structure; investigate backfill | Old structure was already dropped |
| Migration locks table for minutes | Large table, no batching, or missing index on join column | Kill the migration, add batching or use an online DDL tool (e.g., pt-online-schema-change, gh-ost) | Lock has already caused downstream timeouts |
| Backup restore fails with constraint violation | Schema drifted between backup and restore target, or backup is from a different migration state | Match the target schema to the backup's expected schema before restoring | You cannot determine which schema version the backup expects |
| Verification query shows row count mismatch | Rows created between backup and migration, or migration filtered incorrectly | Identify missing rows from write-ahead logs or application audit logs | Gap exceeds your data-loss tolerance |
| External system breaks after migration | Column rename or type change affects an API, export, or replication consumer | Revert the external system's config or add a view/alias that presents the old shape | External system is managed by another team with a different deploy cadence |
| Forward-repair query affects more rows than expected | WHERE clause is too broad, or the bug is wider than initially diagnosed | Stop the repair, verify the WHERE clause against a sample, re-run on a smaller batch | Affected rows include data outside the migration's scope |
Escalation rule of thumb: If you have been troubleshooting for more than 15 minutes and the issue affects production reads or writes, escalate to the database team lead and the incident channel. Do not wait until you have a diagnosis.
Test interrupted migrations and mixed-version behavior before deployment
Two conditions that rollback plans rarely cover:
Interrupted migrations
A migration that adds a column, backfills it, and sets it NOT NULL may fail partway through. If it fails after backfill but before the NOT NULL constraint, you have a partially-filled nullable column. If it fails during backfill, some rows have the new value and some do not. Your rollback plan must account for partial completion, not just "migration succeeded" or "migration never ran."
Test method: In a staging environment, start the migration and kill the database connection mid-backfill (hypothetically, after 40% of rows). Then run the old application version. Then run the reverse migration. Document what state each step produces.
Mixed-version application behavior
During a rolling deployment, some application instances run the old version and some run the new version. Both hit the same database. If the new version writes data in a format the old version cannot read (e.g., an enum value the old version does not recognize), the old instances will error.
Test method: In staging, deploy the new application version to one instance and keep the old version on another. Run your integration tests against both. Check for write conflicts, unrecognized values, and constraint violations.
If your team uses FeatureFactory to examine engineering delivery and code quality, including changes flagged during review, look at whether migration-related pull requests consistently include evidence of these two tests. Their absence is a process gap, not just a code gap.
Explicit limitations
- This guide does not cover distributed databases with eventual consistency. If your migration touches multiple databases or services that replicate asynchronously, the rollback window and verification approach differ significantly.
- PITR and backup strategies depend on your database engine. The specific commands, backup formats, and recovery time vary between PostgreSQL, MySQL, managed services, and NewSQL databases. This guide describes the decision structure, not the CLI commands.
- External side effects are not reversible by database rollback. If your migration triggered an event that sent emails, updated a search index, or called a third-party API, rolling back the data does not unsend the email. You need a separate compensation plan for external effects.
- This checklist does not replace a tested disaster recovery plan. It covers planned migrations, not unplanned data loss. If your team does not have a tested DR plan, this checklist will help with migration safety but will not protect you from hardware failure or accidental deletion.
- Dual-write correctness is hard. This guide recommends dual-write during the expand/migrate phases but does not cover conflict resolution strategies in depth. If two structures diverge, deciding which is authoritative is a design problem specific to your application.
- Forward repair assumes you can identify affected rows. If your migration corrupted data in a way that is indistinguishable from correct data (e.g., truncated strings that still look valid), forward repair requires external evidence such as application logs or user reports, and may not reach every affected row.
Ongoing review routine
After every migration that reaches the contract phase:
- Did the soak period surface any issues? If not, is the soak period the right length, or was it too conservative? Adjust for next time.
- Did the verification queries catch a real problem, or were they pro-forma? If pro-forma, write more specific queries next time.
- Was the backup actually restorable? If no one tested the restore, the backup was decorative.
- Did any external system break that was not in the notification list? Add it.
- Was a forward-repair script prepared? If so, was it needed? If it was needed and did not exist, add forward-repair drafting to the pre-deployment checklist for the next migration of that category.
Monthly (or per-sprint for teams with frequent migrations):
- Review all open "soak period" items. Are any past due for contract? Are any backups approaching retention expiry?
- Check that reverse migration scripts still work against the current schema. Schema drift during the soak period can break a rollback script that worked when it was written.
- If your team tracks delivery signals in a tool like FeatureFactory, look at whether migration PRs have longer cycle times or higher revert rates than other changes. That pattern suggests the planning or testing step is being skipped under time pressure.
Quarterly:
- Run a tabletop exercise: pick a past migration and walk through the rollback plan as if it failed today. See if the backup still exists, the reverse script still runs, and the recovery owner still knows the plan. This takes 30-60 minutes and consistently reveals gaps.
- Separately, pick a past migration and walk through the forward-repair path: can you still identify the affected rows? Is the source data still available? This tests whether your team defaults to rollback when forward repair would have been cheaper.
Next-action checklist
- Pick the next schema or data migration your team plans to ship.
- Classify every change in it as additive, destructive, or transformative.
- Identify the point of no easy return.
- Write the reverse migration script and run it once in a non-production environment.
- Draft a forward-repair script for the most likely backfill or transformation error.
- Fill out the go/no-go checklist above and attach it to the migration PR.
- Schedule a soak period end date and set a calendar reminder to complete the soak sign-off.
- Test an interrupted migration and mixed-version application behavior in staging.
- After the migration ships, complete the post-deployment rows in the checklist within 30 minutes.
- At the next team retrospective or planning session, review whether the checklist caught anything or needs adjustment.
For teams beginning to formalize how they plan product and engineering work, adding a rollback-plan review step to your migration approval process is a low-cost way to prevent the class of incident where a code revert makes a data problem worse.
Measure what you ship - for real.
Put your team’s AI web-development on the outcome loop.
Get early access