Video in progress

A Flyway migration that reached prod turned out to be wrong (data got corrupted or the application doesn't work). How do you roll back, and what rules do you set on the team?

On prod I fix forward: with a new V migration, because changing an applied file breaks the checksum. If data was lost, I restore a separate copy with PITR and bring back the needed rows.

📖 Answer

First I determine the state: was the migration fully applied, or did it fail halfway?

  • In PostgreSQL DDL is transactional: if an ordinary migration fails, everything is rolled back, including the flyway_schema_history entry. Fix it and run it again. A success = false entry stays only when a step ran outside the transaction (for example CREATE INDEX CONCURRENTLY), and then you need flyway repair.
  • If a CONCURRENTLY or non-transactional script is left half done, you have to check the state by hand (an INVALID index and so on).

If the migration succeeded but is wrong:

  1. Can the application's previous version run on the new schema? If we followed the expand/contract rule, yes: I roll back the application and the schema stays.
  2. The fix is a new migration, V58__fix_v57_status_mapping.sql. I never edit the V57 file: it has already been applied in other environments, and a checksum difference breaks validation.
  3. If data was deleted or a column was dropped, I do a PITR from the backup onto a separate server and bring back the needed data. Rolling back the main database entirely is the last resort, because the new writes that arrived in the meantime would be lost.

The team rules I usually introduce after such a case:

  • A destructive change (DROP, narrowing a column type) goes in a separate release, delayed by at least a week.
  • Every migration is tried on a prod-sized copy (with its duration and locks).
  • cleanDisabled=true in the prod configuration (the default since Flyway 9), so flyway clean never reaches prod.
  • Undo (U scripts) exists in Flyway's paid version, but it can't bring data back, so I don't rely on it.