Video in progress

How do you deploy a service that has a Flyway migration without downtime?

Every schema change must work with the old and the new code at the same time. Breaking changes (dropping or renaming a column) are split into several releases: first add, then move, and drop last.

📖 Answer

During a rolling update the old pods are still running, while the migration has already been applied when the first new pod came up. If the migration renames the name column to full_name, the old pods start throwing errors from that moment.

Renaming a column with the "expand / contract" method:

-- Release 1 (V12): expand
ALTER TABLE customer ADD COLUMN full_name VARCHAR(200);
UPDATE customer SET full_name = name WHERE full_name IS NULL;
-- code: writes to both columns, reads from full_name

-- Release 2: code works only with full_name

-- Release 3 (V14): contract
ALTER TABLE customer DROP COLUMN name;

Other practical rules:

  • on a big table, an UPDATE or an index build can hold a lock for a long time. In Postgres use CREATE INDEX CONCURRENTLY (in Flyway it has to run outside a transaction), and copy the data in batches;
  • do not add a NOT NULL column without a default, because the old code will not write to it;
  • several pods will not try to migrate at once: Flyway uses a table lock, but a long migration can fail the pod's startup probe. That is why the migration is sometimes run as a separate Kubernetes Job or a CI step.

Another benefit of this approach: rollback becomes safe, because the old code can work with the new schema.