Prompt

How do I do zero-downtime schema changes in PostgreSQL?

Technology / Databases2 observationsLast seen Nov 26, 2026

Latest observation

Nov 26, 2026OpenAI APIWeb search: off

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:

  1. Make changes in small, backward-compatible steps
  2. Avoid long ACCESS EXCLUSIVE locks
  3. Deploy application changes in phases
  4. Use concurrent/online variants of operations where possible
  5. 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 NULL with 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:

  1. add the column without default
  2. backfill
  3. 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:

  • CONCURRENTLY avoids 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:

  1. Add the constraint as NOT VALID
  2. 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:

  1. Ensure no nulls exist
  2. Add a check constraint or backfill
  3. Set NOT NULL after 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:

  1. Add new column with target type
  2. Backfill in batches
  3. Dual-write
  4. Swap reads
  5. 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 WHERE conditions 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_name and last_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 NULL on large tables (depending on version/behavior)
  • CREATE INDEX without CONCURRENTLY
  • ALTER TABLE ... TYPE on huge tables
  • VACUUM FULL
  • CLUSTER
  • REINDEX without 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

  1. Check impact

    • table size
    • current traffic
    • existing locks
    • replication lag
  2. Plan backward compatibility

    • old app must work with new DB
    • new app must work with old DB during rollout
  3. Apply additive schema changes

  4. Backfill asynchronously

  5. Deploy app changes

  6. Validate

  7. Remove old schema later


Useful PostgreSQL features for online changes

  • CREATE INDEX CONCURRENTLY
  • ALTER TABLE ... ADD CONSTRAINT ... NOT VALID
  • ALTER TABLE ... VALIDATE CONSTRAINT
  • Batch updates
  • lock_timeout
  • statement_timeout
  • pg_repack for 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:

  1. a zero-downtime migration playbook,
  2. examples for specific schema changes like renaming a column or splitting a table, or
  3. a PostgreSQL lock matrix showing which operations block reads/writes.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.