Webhook icon
If icon
Queries icon
Switch icon
OutputValues icon
LoopUntil icon
Query icon
Set icon
Fail icon
SlackIncomingWebhook icon
Pause icon
Delete icon

Change a Postgres Column Without Downtime (Expand and Contract)

Expand and contract a Postgres column with a sync trigger, a resumable batched backfill, full verification and approval before the old column is dropped.

Categories
DataInfrastructure

Changing a column in a busy table, such as dollars to cents, int to bigint, or a renamed field, cannot be done with one ALTER TABLE without locking writers or breaking the app that still reads the old column. The safe way is expand and contract: add the new column next to the old one, keep both in sync while the backfill runs and the app moves over, prove they agree, and only then drop the old one.

This blueprint runs the whole sequence, and is safe to stop and run again at any point.

How it works

  1. expand adds the new column and a BEFORE INSERT OR UPDATE trigger that fills it from the old one with your transform expression. The trigger only writes the new column when the old one changed (or on an insert without a value), so an app that already writes the new column directly is not overwritten. Before installing the trigger, the transform is tried on 1000 rows: one that does not parse or cast would otherwise break every write.
  2. backfill (LoopUntil) updates one batch per iteration in key order and saves the last key in the KV store after each batch. A killed or failed run resumes from the checkpoint; batch_interval leaves room for production traffic and replication between batches.
  3. verify compares every row with the same transform and fails with the first differing keys. A write that bypassed the trigger (for example a bulk load with session_replication_role = replica) blocks the contract.
  4. approve_contract (Pause) waits for a person to confirm that every app reads the new column. A decline or a timeout keeps the expanded state, and the trigger keeps syncing.
  5. After approval the rows are checked again, then contract drops the trigger, its function and the old column, and the checkpoint is removed.
  6. action: rollback removes the trigger and the new column. It refuses after a contract, when the new column holds the only copy of the data.

Error handling

  • DDL never queues behind a long transaction. Every DDL statement runs with lock_timeout (5 s by default) and is retried 5 times, 10 s apart, inside the database. Only a lock timeout is retried; any other error fails at once. In a test, a 25 s transaction held a lock on the table: the app's queries waited at most 5 s, and the expand completed after the transaction ended.
  • Kill-safe backfill. The checkpoint is written after each batch, so a re-run redoes at most one batch, and an UPDATE with the same transform is harmless.
  • Concurrent writes stay consistent. Rows written during the backfill go through the trigger. The backfill's UPDATE re-evaluates a row changed under it, so it uses the newest value.
  • Nothing is dropped without two verifications and an approval, and every failure message names the task, the cause, the keys involved and where a re-run resumes.
  • One run at a time. concurrency (limit 1, QUEUE) makes a new run wait while another one waits for approval; answer or kill the waiting run first.

What this blueprint teaches about Kestra

  • LoopUntil with a KV checkpoint as a resumable batch job: one task does a batch, kv.Set records progress, and the loop exits when a batch comes back short.
  • Pause with typed onResume inputs (a BOOL and a note) as a human gate in the middle of a long operation, with behavior: RESUME and a duration so an unanswered request never drops anything.
  • Switch to run the same flow forward (migrate) or backward (rollback), and input validators that keep table and column names to safe identifiers.
  • errorLogs() and jq in the errors handler, so the Slack alert quotes the reason rather than "task failed".

Prerequisites

  • PostgreSQL 11 or later, a table with an integer primary key, and a role that can ALTER it and create a function in its schema.
  • A Slack incoming webhook.

Secrets

  • POSTGRES_URL (JDBC URL, e.g. jdbc:postgresql://db:5432/app), POSTGRES_USER, POSTGRES_PASSWORD.
  • SLACK_WEBHOOK_URL.
  • EXPAND_CONTRACT_WEBHOOK_KEY: a long random string for the deploy pipeline's webhook.

Inputs

  • action: migrate (default) or rollback.
  • schema, table, key_column, old_column, new_column, new_type.
  • transform: SQL that computes the new value from the row, e.g. CAST(round(amount * 100) AS bigint), lower(email) or CAST(legacy_id AS bigint).
  • batch_size (5000), batch_interval (PT0.2S), lock_timeout (5s), approval_timeout (PT24H), seed_demo.

Outputs

  • verification (JSON): total_rows, mismatched and sample_keys from the full comparison, e.g. {{ outputs.verify.row.mismatched }}. The checkpoint is the KV entry expand_contract_<schema>_<table>_<new_column>.

Quick start

  1. Add the Postgres and Slack secrets and run the flow with the defaults. It creates demo_orders with 100,000 rows and migrates amount (numeric dollars) to amount_cents (bigint).
  2. While the run waits for approval, write through the "old app" (UPDATE demo_orders SET amount = 7.25 WHERE id = 10) and see amount_cents follow.
  3. Resume with Drop the old column now? checked: the trigger and amount are gone, and every row was verified twice.
  4. For your table, set seed_demo: false and the column inputs, deploy the app version that writes both columns, then run migrate.

How to extend

  • Add an index on the new column with CREATE INDEX CONCURRENTLY in its own Queries task between verify and approval (it cannot run in a transaction).
  • Poll replication lag (pg_stat_replication.replay_lag) inside the loop and pause the backfill while a replica is behind.
  • Trigger the flow from your deploy pipeline through the webhook, so the migration starts once the dual-write release is live.

Plugins used

See How

New to Kestra?

Use blueprints to kickstart your first workflows.