A database migration passes in staging. The SQL looks simple, and the deployment pipeline reports success.

Then production requests start timing out.

The migration added one column to a large table. Nothing complicated. But while PostgreSQL was waiting for a lock, application queries started piling up behind it.

This is one of the more frustrating backend problems because the SQL can be correct while the deployment strategy is wrong.

I've worked on backend systems where database changes had to fit around running applications. One lesson worth keeping in mind is that a successful migration isn't just one that changes the schema. It's one that lets the application continue working throughout the transition.

Let's walk through a practical approach using PostgreSQL, including the steps I'd take to introduce a required column without turning a routine deployment into an outage.

1. Why Simple Migrations Can Be Dangerous

Imagine a SaaS application with an orders table containing millions of records.

The product team wants to track which sales channel created each order.

We need a new column:

ALTER TABLE orders ADD COLUMN sales_channel TEXT NOT NULL; 

There's an immediate problem.

Existing orders don't have a sales_channel value, so the constraint cannot be satisfied.

A developer might try adding a default:

ALTER TABLE orders ADD COLUMN sales_channel TEXT NOT NULL DEFAULT 'unknown'; 

On modern PostgreSQL versions, adding a column with a non-volatile default can avoid rewriting the entire table.

That's useful, but it doesn't mean the migration has zero operational impact.

ALTER TABLE still requires locks, and an operation waiting for an exclusive lock can cause other queries to queue behind it.

The real risk depends on several factors:

  • Table size and query activity.
  • The exact schema operation.
  • PostgreSQL version.
  • Existing long-running transactions.
  • Whether the migration rewrites or scans the table.
  • How the application handles old and new schema versions.

Rather than treating migrations as isolated SQL commands, I prefer treating them as application changes that happen in stages.

2. Use the Expand-and-Contract Pattern

The main idea is simple: don't change the database and application in a way that requires both to switch versions at exactly the same moment.

Instead, introduce changes gradually.

The process has three phases:

Phase Goal
Expand Add the new schema without breaking existing code
Migrate Update application behavior and existing data
Contract Remove compatibility code and enforce final constraints

For our sales_channel example, the sequence looks like this:

Add nullable column | Deploy code that writes new values | Backfill existing records | Validate data | Enforce NOT NULL | Remove temporary compatibility code 

The important property is backward compatibility.

During the transition, old and new application instances may run simultaneously.

The database must support both until the deployment is complete.

3. Step One: Add the Column Without a Constraint

Start with the smallest compatible schema change:

ALTER TABLE orders ADD COLUMN sales_channel TEXT; 

Existing records receive NULL for the new column.

The current application continues working because it doesn't need to know about the new field.

This operation normally doesn't require rewriting the table. However, it still takes a lock, even if only briefly.

For production migrations, consider a short lock timeout:

BEGIN; SET LOCAL lock_timeout = '3s'; ALTER TABLE orders ADD COLUMN sales_channel TEXT; COMMIT; 

The timeout is an example, not a universal recommendation.

If PostgreSQL cannot acquire the necessary lock within the configured period, the statement fails instead of waiting indefinitely.

That's often preferable to letting a migration wait behind a long transaction while application traffic queues up.

The failed migration can be investigated and retried during a safer window.

One caution: avoid wrapping many unrelated schema changes in a single long transaction. Locks can remain held until the transaction commits.

4. Step Two: Deploy Compatible Application Code

Now update the application to write sales_channel for new orders.

For example:

def create_order(db, product_id, quantity, channel): db.execute( """ INSERT INTO orders ( product_id, quantity, sales_channel ) VALUES (%s, %s, %s) """, (product_id, quantity, channel), ) 

This example assumes the application validates channel before insertion and commits the transaction through its database layer.

The new code should also tolerate older records where sales_channel is still NULL.

For example, the API could display "unknown" until the backfill finishes.

At this stage, the database supports both application versions:

  • Older instances can insert orders without specifying the new column.
  • Newer instances write the new value.
  • Existing rows remain readable.

That compatibility matters when deployments roll out gradually across multiple servers or containers.

Before moving forward, verify that every active writer has been updated.

Don't forget background workers, scheduled jobs, administrative scripts, or other services that insert orders.

A web API might be fully deployed while an older worker is still writing null values.

5. Step Three: Backfill Existing Data in Batches

Now we need to populate the new column for historical orders.

A tempting approach is:

UPDATE orders SET sales_channel = 'unknown' WHERE sales_channel IS NULL; 

For a small table, that might be perfectly fine.

For millions of rows, one large transaction can generate substantial WAL, hold row locks for a long time, create dead tuples, and increase replication lag.

Instead, process records in manageable batches.

Assuming id is the primary key:

WITH batch AS ( SELECT id FROM orders WHERE id > $1 AND id <= $2 AND sales_channel IS NULL ) UPDATE orders AS o SET sales_channel = 'unknown' FROM batch WHERE o.id = batch.id; 

Here, $1 and $2 define a bounded ID range.

An application script can execute one batch per transaction, commit it, and continue with the next range.

For example:

Batch 1: IDs 1–5,000 Batch 2: IDs 5,001–10,000 Batch 3: IDs 10,001–15,000 ... 

These are illustrative ranges, not recommended batch sizes.

Choose a batch size based on actual update latency, replication behavior, lock contention, and database resources.

A few important details:

Make the backfill restartable. The IS NULL condition allows completed records to be skipped if the job restarts.

Don't assume IDs are continuous. Missing IDs are normal. Range-based batching still works.

Monitor the workload. Check transaction duration, database CPU, WAL generation, replication lag, and dead tuples.

Avoid unnecessary overwrites. The IS NULL filter prevents replacing values already written by the updated application.

If historical data allows you to determine the real sales channel, use that information instead of assigning "unknown" to everything.

The backfill should preserve business meaning, not just satisfy a database constraint.

6. Step Four: Validate Before Enforcing NOT NULL

Once the backfill finishes, verify the remaining data.

SELECT COUNT(*) FROM orders WHERE sales_channel IS NULL; 

For a large table, this query may require a substantial scan, so run it with appropriate resource awareness.

If the result is zero, we're close.

But running this immediately:

ALTER TABLE orders ALTER COLUMN sales_channel SET NOT NULL; 

can require PostgreSQL to verify that every row contains a value.

On a busy table, that verification can introduce unwanted locking.

A useful PostgreSQL technique is to validate a check constraint separately.

First, add a constraint without validating historical rows:

ALTER TABLE orders ADD CONSTRAINT orders_sales_channel_nn CHECK (sales_channel IS NOT NULL) NOT VALID; 

The constraint applies to subsequent inserts and updates, but PostgreSQL doesn't scan all existing rows during this statement.

Then validate it:

ALTER TABLE orders VALIDATE CONSTRAINT orders_sales_channel_nn; 

PostgreSQL uses a less restrictive lock for validation, allowing ordinary concurrent updates to continue.

Once validation succeeds, the database has evidence that the column contains no null values.

On supported PostgreSQL versions, this allows the final operation to avoid another full-table verification scan:

ALTER TABLE orders ALTER COLUMN sales_channel SET NOT NULL; 

The final command still takes a lock, so keep the transaction short and consider using lock_timeout.

Afterward, the temporary check constraint can be dropped:

ALTER TABLE orders DROP CONSTRAINT orders_sales_channel_nn; 

Each step should be evaluated separately for lock behavior.

See the PostgreSQL ALTER TABLE documentation for the detailed behavior of NOT VALID, constraint validation, and SET NOT NULL.

7. What If the Migration Also Needs an Index?

Suppose the application frequently filters orders by sales channel.

An index might help:

CREATE INDEX CONCURRENTLY idx_orders_sales_channel ON orders (sales_channel); 

The CONCURRENTLY option allows normal inserts, updates, and deletes to continue while PostgreSQL builds the index.

This reduces write-blocking risk compared with a regular index build.

But it isn't free.

Concurrent index creation can take longer, consume database resources, and wait on existing transactions.

It also cannot run inside a transaction block, which matters if your migration framework automatically wraps migrations in transactions.

If the build fails, PostgreSQL may leave an invalid index that requires cleanup.

More importantly, don't create the index just because the column is new.

Check the actual queries.

If most requests filter by user_id and then sales_channel, a composite index might be more useful than a single-column index.

Use EXPLAIN (ANALYZE, BUFFERS) on representative queries to decide.

Reference: PostgreSQL CREATE INDEX

8. Plan for Rollbacks Before Deploying

Here's an easy mistake: treating an application rollback as if it automatically rolls back a database migration.

It doesn't.

Imagine the new application version starts writing sales_channel values.

Then you discover an unrelated bug and roll back the application.

If the database already requires sales_channel to be non-null, the old application might fail to insert orders.

That's why the deployment order matters.

Don't enforce the final constraint until the older application version is no longer needed or has been made compatible.

A rollback-friendly approach usually keeps expanded schema changes in place while rolling back application code.

Destructive changes, such as dropping columns or renaming fields used by running services, should happen only after all dependencies have been migrated.

For complex changes, I'd explicitly document:

  • Which application versions support each schema state.
  • When the rollback window closes.
  • How to stop and resume the backfill.
  • Which metrics would trigger a rollback.
  • Whether database changes require a forward fix instead of reversal.

This planning is especially valuable when several services share the same database.

9. What I'd Monitor During Deployment

A migration can be technically correct and still put too much pressure on production.

I'd watch database and application behavior throughout the process.

Metric Why it matters
API p95/p99 latency Detect blocked or slower requests
Database lock waits Identify migration contention
Active transactions Find long-running blockers
Replication lag Detect heavy write pressure
Database CPU and I/O Monitor migration resource usage
Error rate Catch compatibility failures

I would also verify that old and new application versions behave correctly against the expanded schema before enforcing the final constraint.

If the migration increases error rates or lock waits, stop and investigate rather than pushing through because the SQL is almost finished.

Reducing deployment risk is more valuable than completing a migration a few minutes earlier.

Final Thoughts

Database migrations are part of application delivery, not separate maintenance tasks.

A schema change that takes seconds in staging can behave very differently under production traffic.

Three lessons are worth remembering:

  1. Expand before you contract. Keep schema changes compatible with multiple application versions during deployment.
  2. Backfill large datasets incrementally. Small, restartable transactions are easier to control than one massive update.
  3. Treat locks and rollback compatibility as first-class concerns. Correct SQL doesn't automatically mean a safe deployment.

The goal isn't literally zero locking. Most schema changes need some level of locking.

The goal is to keep those locks short, predictable, and compatible with normal application traffic.

A well-planned migration should be boring. That's usually a good sign.