Spring › JPA

Zero-downtime column renames with Flyway Expand-Contract

Comparing naive RENAME COLUMN against Expand-Contract on PostgreSQL 18 and Flyway 11.14, with lock wait metrics, backfill caveats, and safe DDL ordering.

Zero-downtime column renames with Flyway Expand-Contract

I had to rename member.nick to nickname on a live production service. Because old and new application instances overlap during rolling deployments, I split the change into an Expand → dual-write → backfill → Contract sequence instead of running a single RENAME COLUMN. This post reproduces both approaches locally and measures error counts, lock wait spikes, and backfill edge cases.

Tested on Spring Boot 4.0.3, Flyway 11.14.1 (managed by Boot 4.0.3 BOM), Kotlin 2.2.21, JDK 21, and PostgreSQL 18.1. I ran the benchmark on a 12-core, 32GB RAM machine (Windows with Docker Desktop/WSL2) using synthetic traffic clients mimicking old and new app versions (2 threads per version looping INSERT, UPDATE, and SELECT).

The problem

I started by testing the simplest possible migration to see the exact blast radius. While v1 application threads were actively reading and writing the nick column, I applied a direct rename:

1
2
-- db/naive/V2__rename_nick_to_nickname.sql
alter table member rename column nick to nickname;

The migration itself finished in 70ms, but the next 3 seconds broke production traffic. Out of 742 operations sent by the v1 client, 724 failed immediately:

1
2
3
phase=before-rename            ops=  1116 errors=    0
phase=after-rename(v1 running) ops=    18 errors=  724
firstError=[V1_OLD_COLUMN] ERROR: column "nick" of relation "member" does not exist

During a rolling deployment, v1 instances keep serving requests until every v2 instance passes readiness checks and takes over. If you rename the column before deploying the app, v1 breaks. If you deploy the app before renaming the column, v2 breaks. Either order guarantees downtime unless you pass through an intermediate schema that both versions can read and write simultaneously.

Hidden DDL lock bottlenecks

Column compatibility wasn’t the only risk. Most ALTER TABLE statements in PostgreSQL acquire an ACCESS EXCLUSIVE lock. Even when the metadata change itself takes only a few milliseconds, waiting to acquire that lock blocks every subsequent SELECT, INSERT, and UPDATE queued behind it.

To measure this effect, I kept a single read transaction open on member for 8 seconds and ran a simple ADD COLUMN migration against it:

ConditionMigration outcomeMax client write latency
No lock_timeoutSucceeded after waiting 7,521ms7,464.5ms
set local lock_timeout = '2s'Failed at 2,057ms, retry succeeded in 61ms2,007.1ms
Baseline (no migration)-5.4ms

Even a lightweight ADD COLUMN stalled all incoming writes for over 7 seconds because of one slow read transaction ahead of it. Adding set local lock_timeout = '2s' forced Flyway to abort cleanly with SQL State: 55P03 (ERROR: canceling statement due to lock timeout). Because PostgreSQL executes standard DDL inside a transaction, the failed migration rolled back cleanly without leaving a broken entry in flyway_schema_history, making it safe to retry right away. You can inspect which session is blocking which using the pg_locks queries I documented in Diagnosing InnoDB row locks, next-key locks, and deadlocks.

xychart-beta
    title "Max write client latency during DDL (ms)"
    x-axis ["ALTER no timeout", "ALTER lock_timeout 2s", "CREATE INDEX", "CREATE INDEX CONCURRENTLY"]
    y-axis "max latency (ms)" 0 --> 8000
    bar [7464.5, 2007.1, 2913.5, 7.7]

Index creation suffers from the same blocking behavior. Running a plain CREATE INDEX on a 2-million-row table blocked writes for 2,970ms, dropping client throughput to just 21 operations during that window. Switching to CREATE INDEX CONCURRENTLY took nearly the same total time (2,949ms), but the client processed 1,000 operations with a maximum latency of only 7.7ms.

The Expand-Contract migration flow

To eliminate both application errors and long lock queues, I broke the column rename into seven small migrations across three application deployments:

flowchart TD
    A["V2: Add nullable nickname column"] --> B["Deploy app v2: dual-write"]
    B --> C["Backfill in 10K-row batches"]
    C --> D["V3-V5: Enforce NOT NULL safely"]
    D --> E["V6: Drop nick NOT NULL, deploy v3"]
    E --> F["V7: Drop nick column"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-- db/expand/V2__expand_add_nickname.sql
set local lock_timeout = '3s';
alter table member add column nickname varchar(50);

-- db/expand/V3__nickname_check_not_valid.sql
set local lock_timeout = '3s';
alter table member add constraint member_nickname_not_null check (nickname is not null) not valid;

-- db/expand/V4__validate_nickname_check.sql
alter table member validate constraint member_nickname_not_null;

-- db/expand/V5__nickname_set_not_null.sql
set local lock_timeout = '3s';
alter table member alter column nickname set not null;
alter table member drop constraint member_nickname_not_null;

-- db/expand/V6__nick_drop_not_null.sql
set local lock_timeout = '3s';
alter table member alter column nick drop not null;

-- db/expand/V7__contract_drop_nick.sql
set local lock_timeout = '3s';
alter table member drop column nick;

Running ALTER COLUMN nickname SET NOT NULL directly forces PostgreSQL to scan the entire table while holding an ACCESS EXCLUSIVE lock. Instead, V3 adds a CHECK (nickname IS NOT NULL) NOT VALID constraint (metadata-only, enforces on new writes), and V4 runs VALIDATE CONSTRAINT, which scans the table under a SHARE UPDATE EXCLUSIVE lock that doesn’t block reads or writes. Since PostgreSQL 12, SET NOT NULL skips the full table scan when a validated NOT NULL check constraint already exists. In my 1-million-row test, V4 validation finished in 160ms and V5 took 67ms.

Don’t skip V6 (ALTER COLUMN nick DROP NOT NULL). Once you deploy app v3, it stops writing to nick altogether. If nick still has its old NOT NULL constraint, every v3 INSERT fails immediately.

Here is the Spring Boot + Flyway setup and the chunked backfill runner I used:

1
2
3
4
5
6
7
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-jdbc")
    implementation("org.springframework.boot:spring-boot-starter-flyway")
    implementation("org.flywaydb:flyway-database-postgresql")
    runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
# src/main/resources/application.yml
spring:
  flyway:
    postgresql:
      transactional-lock: false # Required when running CREATE INDEX CONCURRENTLY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/main/kotlin/lab/NicknameBackfill.kt
package lab

import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component

@Component
class NicknameBackfill(private val jdbc: JdbcTemplate) {

    fun run(batch: Long = 10_000) {
        val maxId = jdbc.queryForObject("select max(id) from member", Long::class.java) ?: return
        var from = 0L
        while (from < maxId) {
            // Independent commit per batch: avoids long row locks and stays safely resumable
            jdbc.update(
                "update member set nickname = nick where id > ? and id <= ? and nickname is distinct from nick",
                from, from + batch,
            )
            from += batch
            Thread.sleep(20) // Give replication lag and autovacuum breathing room
        }
    }
}

Verification and backfill results

Running the full Expand-Contract sequence against 1 million rows produced zero errors across every deployment and migration stage:

StageOperationsErrorsp99 LatencyMax Latency
v1 only1,10204.8ms8.9ms
v1 + v2 overlap (rolling deploy)2,04506.2ms11.8ms
v2 + backfill1,97905.6ms30.6ms
v2 + constraint transition (V3–V6)11306.2ms11.4ms
v2 + v3 overlap2,00705.8ms10.3ms
v3 + Contract (V7)1,12803.8ms8.6ms

The 10K-row chunked backfill copied 1,000,127 rows in 5,699ms total, with the slowest individual batch taking 53ms.

Notice the WHERE predicate in the backfill query: nickname is distinct from nick, not nickname is null. That distinction prevented silent data drift. During the v1 + v2 overlap window, a v2 instance can insert or update a row (setting both nick and nickname), and a v1 instance can subsequently update that same row—changing nick while leaving nickname stale. When I shrank the test table to 2,000 rows to increase write contention, 169 rows drifted in exactly this way. A backfill filtering only on nickname is null would have missed all 169 of them.

When to use it and operational checklist

Schema changeRecommended approach
Adding a nullable column or new tableSingle migration + set local lock_timeout
Renaming a column or changing column typeExpand-Contract (minimum 2 app deployments)
Adding an index to a large tableStandalone CREATE INDEX CONCURRENTLY file
Adding NOT NULL to an existing columnNOT VALID check → VALIDATE → SET NOT NULL

When not to use Expand-Contract: If you run an internal tool with scheduled maintenance windows, or a small service that replaces instances offline all at once, splitting one rename into three deployments adds more operational overhead than it saves. You also don’t need Expand-Contract for brand-new columns that no running version reads yet.

Watch out for Flyway’s default PostgreSQL lock setting when using CREATE INDEX CONCURRENTLY: with postgresql.transactional.lock=true (the default), my migration hung indefinitely. Checking pg_stat_activity showed Flyway’s lock connection sitting idle in transaction holding an advisory lock, while CREATE INDEX CONCURRENTLY waited on virtualxid for that transaction to finish. Because both waited on each other, it stayed deadlocked past 3 minutes until I killed the session. Setting spring.flyway.postgresql.transactional-lock: false fixed it immediately. Also remember that if CREATE INDEX CONCURRENTLY fails midway, PostgreSQL leaves behind an INVALID index—always check pg_index.indisvalid and drop invalid indexes before retrying.

  • Include set local lock_timeout in every DDL migration and document the retry procedure.
  • Verify the intermediate schema supports both old and new app versions during rolling overlap.
  • Use is distinct from (not is null) in backfill queries to catch rows updated by v1 during dual-write.
  • Place CREATE INDEX CONCURRENTLY in its own migration file with transactional-lock: false.
  • Confirm zero running instances read or write the old column before running the Contract migration.
This post is licensed under CC BY 4.0 by the author.