Video in progress

You need to rename a column or change its type in a table running in production. How do you do it with no downtime and with the ability to roll back?

The expand/contract method: first a new column is added, the code writes to both columns, old data is copied in batches, reads switch to the new column, and only at the end is the old column dropped. Each stage is a separate deploy, and at each one the old version of the code can still work.

📖 Answer

ALTER TABLE users RENAME COLUMN phone TO phone_number is a single line, but during a rolling deploy the old pods still reference phone and crash. If you roll back, the old code runs against the new schema. And on a big table, changing a type rewrites the whole table and holds a long lock.

The stages (each a separate release):

  1. Expand. Add the new column, nullable, with no default (in PostgreSQL 11+ adding it with a default is fast too, but the plain way is safer):
    ALTER TABLE users ADD COLUMN phone_number VARCHAR(20);
    
  2. Dual write. The code writes to both phone and phone_number, and reads still come from the old one.
  3. Backfill. Old rows are copied in batches:
    UPDATE users SET phone_number = phone
    WHERE id BETWEEN :from AND :to AND phone_number IS NULL;
    
    Each batch is a separate short transaction — replica lag and locks stay under control.
  4. Verification. Check with a query that the two columns match.
  5. Switching reads. The code reads from the new column and still writes to both — rollback is still safe.
  6. Contract. Writing to the old column stops, and after a release or two the column is dropped.

Additional subtle points:

  • Adding NOT NULL scans a big table; in PostgreSQL first add CHECK (phone_number IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT — the validation doesn't block writes.
  • For an index, CREATE INDEX CONCURRENTLY; in Flyway/Liquibase this migration must run outside a transaction.
  • The DDL lock queue: if a long-running query exists, the ALTER waits for it, and all ordinary queries line up behind the ALTER. Use SET lock_timeout = '3s' and retry.
  • Don't use ddl-auto=update in Hibernate on prod — it changes the schema without control.

It's slower, but you can go back at every step. On a small table it's overkill; on a big table running 24/7, it's the only safe way.