Prompt
How do I do zero-downtime schema changes in PostgreSQL?
Latest observation
Zero-downtime schema changes in PostgreSQL usually means changing the schema in a way that doesn’t block reads/writes for long and can be deployed safely while the application is still serving traffic.
The main ideas are:
- Make changes in small, backward-compatible steps
- Avoid long
ACCESS EXCLUSIVElocks - Deploy application changes in phases
- Use concurrent/online variants of operations where possible
- Backfill data asynchronously
Core rules
1) Prefer additive changes first
Safe-ish changes:
- Add new nullable columns
- Add new tables
- Add indexes with
CONCURRENTLY - Add new enum values carefully
- Add triggers/functions if needed
Riskier changes:
- Dropping columns/tables
- Renaming columns used by old code
- Changing column type directly
- Adding
NOT NULLwith table scan - Adding a column with a volatile default on old PG versions
- Creating regular indexes on large tables during peak traffic
2) Use the expand/contract pattern
This is the standard zero-downtime approach:
Phase A: Expand
Add new schema elements without breaking old code.
- Add new column
- Add new table
- Add new index concurrently
Phase B: Backfill
Populate new data in batches in the background.
Phase C: Dual-write / dual-read
Update the app so it writes to both old and new, and reads from the new schema when ready.
Phase D: Contract
Remove old schema only after all traffic uses the new path.
Common PostgreSQL techniques
Add a column safely
ALTER TABLE users ADD COLUMN last_login_at timestamptz;
This is usually fast if no default is set.
If you need a default
On modern PostgreSQL versions, adding a column with a constant default is much safer than it used to be:
ALTER TABLE users ADD COLUMN is_active boolean DEFAULT true;
But for very large/old tables, it’s often still better to:
- add the column without default
- backfill
- add default later
ALTER TABLE users ADD COLUMN is_active boolean;
UPDATE users SET is_active = true WHERE is_active IS NULL;
ALTER TABLE users ALTER COLUMN is_active SET DEFAULT true;
Add an index without blocking writes
Use:
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
Important:
CONCURRENTLYavoids blocking writes, but takes longer- cannot run inside a transaction block
- if it fails, it may leave an invalid index that needs cleanup
For uniqueness:
CREATE UNIQUE INDEX CONCURRENTLY idx_users_email_unique ON users(email);
Add a foreign key safely
Foreign keys can be added with minimal locking if done carefully.
Pattern:
- Add the constraint as
NOT VALID - Validate it later
ALTER TABLE orders
ADD CONSTRAINT orders_user_id_fkey
FOREIGN KEY (user_id) REFERENCES users(id)
NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_user_id_fkey;
This avoids long blocking during constraint creation.
Add NOT NULL safely
Instead of directly:
ALTER TABLE users ALTER COLUMN email SET NOT NULL;
Do:
- Ensure no nulls exist
- Add a check constraint or backfill
- Set
NOT NULLafter validation
Example:
ALTER TABLE users ADD CONSTRAINT users_email_not_null CHECK (email IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT users_email_not_null;
ALTER TABLE users ALTER COLUMN email SET NOT NULL;
ALTER TABLE users DROP CONSTRAINT users_email_not_null;
Change a column type safely
If compatible, sometimes:
ALTER TABLE t ALTER COLUMN x TYPE bigint USING x::bigint;
But this can rewrite the table and block heavily.
Safer pattern:
- Add new column with target type
- Backfill in batches
- Dual-write
- Swap reads
- Drop old column later
Rename columns/tables carefully
Renames are fast, but they break old application code immediately.
Use only when:
- all app instances have been updated
- or the app supports both names temporarily
Backfilling data without downtime
For large tables, backfill in batches:
UPDATE users
SET last_login_at = now()
WHERE id IN (
SELECT id
FROM users
WHERE last_login_at IS NULL
ORDER BY id
LIMIT 1000
);
Run repeatedly in a job/worker until done.
Tips:
- Keep transactions short
- Use small batch sizes
- Add
WHEREconditions that use indexes - Sleep briefly between batches if needed
- Monitor replication lag if using replicas
Deployment sequence example
Suppose you want to replace users.full_name with users.first_name and users.last_name.
Step 1: Expand
ALTER TABLE users ADD COLUMN first_name text;
ALTER TABLE users ADD COLUMN last_name text;
Step 2: Backfill
UPDATE users
SET first_name = split_part(full_name, ' ', 1),
last_name = nullif(split_part(full_name, ' ', 2), '');
Step 3: App dual-write
Deploy app version that:
- writes
full_name - writes
first_nameandlast_name - reads from new columns if present
Step 4: Verify and switch reads
Once all code is reading new columns, stop using full_name.
Step 5: Contract
ALTER TABLE users DROP COLUMN full_name;
Things to avoid
Avoid long-running DDL during peak traffic
Examples:
ALTER TABLE ... ADD COLUMN ... DEFAULT ... NOT NULLon large tables (depending on version/behavior)CREATE INDEXwithoutCONCURRENTLYALTER TABLE ... TYPEon huge tablesVACUUM FULLCLUSTERREINDEXwithout planning
Avoid large transaction blocks
Huge transactions:
- hold locks longer
- bloat tables
- delay autovacuum
- can create replication lag
Locking considerations
PostgreSQL DDL often requires locks. The goal is to:
- choose operations with lighter locks
- keep them brief
- retry if needed
Useful settings:
SET lock_timeout = '2s';
SET statement_timeout = '30s';
This helps your migration fail fast instead of blocking production.
Recommended migration workflow
-
Check impact
- table size
- current traffic
- existing locks
- replication lag
-
Plan backward compatibility
- old app must work with new DB
- new app must work with old DB during rollout
-
Apply additive schema changes
-
Backfill asynchronously
-
Deploy app changes
-
Validate
-
Remove old schema later
Useful PostgreSQL features for online changes
CREATE INDEX CONCURRENTLYALTER TABLE ... ADD CONSTRAINT ... NOT VALIDALTER TABLE ... VALIDATE CONSTRAINT- Batch updates
lock_timeoutstatement_timeoutpg_repackfor some maintenance tasks
Practical checklist
Before migrating:
- Is the change backward compatible?
- Does it avoid table rewrites?
- Are there large indexes or constraints that need concurrent validation?
- Is the app deploy split into expand/backfill/contract phases?
- Have you tested on a production-like dataset?
During migration:
- Use small batches
- Watch locks and replication lag
- Set lock/statement timeouts
- Be ready to retry
After migration:
- Remove old code paths
- Drop obsolete columns/indexes later
- Confirm constraints and indexes are valid
If you want, I can also give you:
- a zero-downtime migration playbook,
- examples for specific schema changes like renaming a column or splitting a table, or
- a PostgreSQL lock matrix showing which operations block reads/writes.
Brands