Sub topic 14
Backward-compatible schema changes with expand and contract
This chapter assumes you can write versioned SQL migrations, know how Spring Boot runs Flyway at startup, and have used ddl-auto: validate with Hibernate. It builds on the naming rules, the flyway_schema_history table, and repeatable migrations from earlier chapters.
Why one migration is not enough
When you deploy a new version of a Spring Boot service, Flyway runs at startup of the first new instance. During a rolling deploy, instances of the old version keep serving traffic against the schema that Flyway just changed. The same happens when you roll the application back: the old code meets the newer schema.
A migration that breaks the old code causes errors during every deploy, even if the new code is correct. Examples are renaming a column, dropping a column, or adding a NOT NULL column with no default. The old instances still run INSERT and SELECT statements that name the old column.
Flyway Community Edition has no undo migrations. Your rollback strategy is therefore the previous application version, and that version has to keep working with the current schema. Expand and contract gives you that guarantee.
The pattern
Expand and contract splits one breaking change into several releases. Each release is compatible with the one before it.
- Expand. Add the new structure next to the old one. Nothing the running code uses is removed or changed.
- Migrate. Copy existing data into the new structure. Make the application write to both structures, then read from the new one.
- Contract. After no running version uses the old structure, drop it in a later migration.
Worked example: renaming display_name to full_name
The running example uses the app_user table from earlier chapters. A direct ALTER TABLE app_user RENAME COLUMN display_name TO full_name would break every old instance at once. Instead, you do the rename in three releases.
Release A: expand
The first migration adds the new column as nullable. This is a metadata-only change in PostgreSQL, so it is fast and takes no long lock.
-- src/main/resources/db/migration/V4__add_full_name.sql
ALTER TABLE app_user ADD COLUMN full_name VARCHAR(200);The second migration copies the existing values.
-- src/main/resources/db/migration/V5__backfill_full_name.sql
UPDATE app_user SET full_name = display_name WHERE full_name IS NULL;The active_users view from the repeatable migration also depends on the old column. PostgreSQL refuses to drop a column that a view uses. Move the view to the new column now, while both columns still exist, and keep its output column name unchanged.
-- src/main/resources/db/migration/R__active_users_view.sql
CREATE OR REPLACE VIEW active_users AS
SELECT id, username, full_name AS display_name
FROM app_user;Flyway applies pending versioned migrations first and then repeatable ones. The view therefore switches to full_name after V5 has filled it. CREATE OR REPLACE VIEW works here because the column names and types of the view are unchanged.
The application code in release A writes both columns and reads the new one, with a fallback for rows that are not yet backfilled.
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "app_user")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(name = "display_name")
private String displayName;
@Column(name = "full_name")
private String fullName;
protected AppUser() {
}
public AppUser(String username) {
this.username = username;
}
public void rename(String name) {
this.fullName = name;
this.displayName = name;
}
public String name() {
return fullName != null ? fullName : displayName;
}
}With ddl-auto: validate, Hibernate checks that both mapped columns exist. They do, so startup succeeds.
Release B: migrate
While release A was rolling out, some old instances were still inserting rows with only display_name. Those rows have a null full_name. Release B closes the gap and then tightens the constraint.
-- src/main/resources/db/migration/V6__finish_full_name.sql
UPDATE app_user SET full_name = display_name WHERE full_name IS NULL;
ALTER TABLE app_user ALTER COLUMN full_name SET NOT NULL;Release A instances may still be running while V6 executes, but they write both columns, so no new null appears. Release B removes displayName from the entity completely, including from JPQL queries and projections. That removal is the preparation for the contract step. Hibernate selects every mapped column, so any remaining mapping to display_name would fail once the column is dropped.
Release C: contract
By now every running instance is release B or later, and none of them mentions display_name.
-- src/main/resources/db/migration/V7__drop_display_name.sql
ALTER TABLE app_user DROP COLUMN display_name;This step destroys data. Take a backup first, or keep the column for one more release if you are unsure whether anything else, such as a reporting job, still reads it.
Which changes are safe
The first column of the table shows a change. The second shows whether it is safe in a single release, and the third shows the safer sequence.
| Change | Safe in one release? | Safer approach |
|---|---|---|
| Add a nullable column | Yes | Add it directly |
| Add a table | Yes | Add it directly |
| Add a `NOT NULL` column | No | Add nullable with a default or backfill, then add the constraint later |
| Rename a column or table | No | Expand and contract |
| Drop a column or table | No | Stop using it in one release, drop it in the next |
| Change a column type | No | Add a new column of the new type, then expand and contract |
| Add a unique constraint | Only if the data is already unique | Check for duplicates first, fix them, then add it |
| Add an index | Yes, but may block writes | Use your database's online index option |
Problems you will meet
Old code and new constraints
A new constraint, such as NOT NULL, is a breaking change for any old code that does not supply the value. Add constraints only after the last version that violates them is gone. This is why V6 sets NOT NULL in release B and not release A.
Long locks and large backfills
An UPDATE over a large table runs inside the migration transaction and holds row locks until it commits. Startup blocks until Flyway finishes, so a slow migration delays the whole deploy. For large tables, backfill in batches from a separate job and keep the Flyway migration limited to the structural change. Some operations, such as CREATE INDEX CONCURRENTLY in PostgreSQL, cannot run inside a transaction. Check the Flyway documentation for your version on how to run such a migration outside one.
Migrations run on every instance
Several instances may start at once. Flyway takes a lock through the database, so one instance applies the migrations while the others wait. A slow migration therefore delays all of them, and a health check with a short timeout can kill instances that are only waiting.
Skipping the pause between releases
The pattern works only if release B is fully rolled out before release C starts. If you merge V7 into the same release as the code change, the old instances are still running against a schema that no longer has their column. Treat each phase as a separate deploy, and do not squash them.
Tests that only see the final schema
Migration tests run against an empty database and see the end state. They cannot show that release A works against the schema from release B. To check this, deploy the previous application version in a staging environment against the newer schema.
Releases and team workflow
Expand and contract works best when each phase is a separate pull request with its own migration version. The team then sees which release a given contract migration is allowed to ship in. A short comment in the pull request that links to the expand release also helps. Later chapters in this tutorial cover version conflicts between branches. The rule from this chapter still holds there: a contract migration needs a higher version than every expand migration it depends on.
Exercise
A teammate puts ALTER TABLE app_user DROP COLUMN display_name into the same release that stops the application from reading display_name. Why is this still unsafe in a rolling deploy, and how do you fix it?
Show answer
During the rolling deploy, old instances that still read or write display_name run against a schema where the column is already gone. The migration runs when the first new instance starts, so those old instances fail with errors. The fix is to ship the code change first, wait until every instance runs it, and drop the column in a later release with its own migration.
Exercise
You need to change username from VARCHAR(100) to VARCHAR(255) with no downtime. Which parts of the expand and contract pattern apply, and which do not?
Show answer
In PostgreSQL, widening a VARCHAR limit is a metadata-only change, and old code keeps working, so it is already backward-compatible and can ship in one migration. The full pattern of a new column, backfill, dual write, and drop is only needed for changes that are not compatible, such as changing the type to something incompatible or narrowing the limit. Check the behavior of your database for the specific type change before you decide.