> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Safe PostgreSQL Schema Migrations

> How to avoid production outages from PostgreSQL ALTER TABLE locks by understanding metadata changes and using session lock_timeout with retryable migrations

Let's walk through a common production surprise and how to prevent it.

Scenario
Your teammate runs a small migration to add one nullable column to the `users` table. In staging it completed in milliseconds. In production, within a minute every read and write against `users` times out — and the ALTER still hasn't finished.

How can adding one empty column block reads? What could have prevented this outage?

The common instinct is to assume the ALTER rewrites the whole table (e.g., rewriting 50 million rows). That intuition is usually wrong.

![A dark-themed mockup of a "users" database table (with a PostgreSQL elephant logo) showing columns id, name, and created\_at filled with many empty red row placeholders. The top reads "THE INSTINCT" and the footer notes "50,000,000 rows."](https://mintcdn.com/kodekloud-c4ac6d9a/IK4ISE2GFis3psR1/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/Databases/Safe-PostgreSQL-Schema-Migrations/users-table-dark-postgres-50m-rows.jpg?fit=max\&auto=format\&n=IK4ISE2GFis3psR1\&q=85\&s=514f543c61df4bf2ccd6883dd6429a7c)

Short answer: metadata vs. locks

* Adding a nullable column with no default in modern PostgreSQL is a metadata-only change — it does not rewrite the table on disk.
* The outage happens because many `ALTER TABLE` operations acquire an ACCESS EXCLUSIVE lock. That lock conflicts with normal reads/writes and blocks them until the ALTER can obtain and finish its operation.

Why reads and writes stalled

* If a long-running transaction (for example, an analytics query) already holds locks on `users`, the ALTER cannot acquire ACCESS EXCLUSIVE and blocks waiting.
* While the ALTER is waiting, PostgreSQL will also block subsequent statements that would conflict with the pending schema change. Those client queries queue up and eventually time out, causing the visible outage.
* This explains why staging (which typically has no long-running analytic jobs) completes fast, while production can deadlock the table for minutes.

Illustration (sequence of events)

* Ongoing queries: SELECT, UPDATE, long analytics SELECT...
* An ALTER TABLE users arrives and waits for ACCESS EXCLUSIVE
* The long analytics job runs for 20+ minutes, so the ALTER waits
* New incoming queries block and eventually time out

Example timeline:

```text theme={null}
INCOMING QUERIES
SELECT
UPDATE
SELECT
UPDATE
SELECT
ALTER TABLE users
waiting...
users
long analytics query
20 MIN
```

Mitigation: use a lock timeout and retry
A practical and safe approach is to set a short session `lock_timeout` before running DDL so the ALTER fails fast if it cannot get the lock. Your migration tooling should catch that failure and retry later during a quieter window.

Example (run in the same session that executes the ALTER):

```sql theme={null}
-- Set a short lock timeout in the migration session:
SET lock_timeout = '2s';

-- Attempt the schema change in the same session:
ALTER TABLE users
ADD COLUMN customer_note text;
```

If PostgreSQL cannot acquire the required lock within the timeout, you’ll see:

```text theme={null}
ERROR:  canceling statement due to lock timeout
```

Handle this error in your migration runner by retrying with exponential backoff or scheduling the migration during a maintenance window.

Quick retry loop example (bash + psql)

* Note: `SET lock_timeout` must be in the same session executing the DDL. This example runs both commands in one psql invocation and retries on error.

```bash theme={null}
#!/usr/bin/env bash
RETRIES=10
SLEEP=2

for i in $(seq 1 $RETRIES); do
  psql -v ON_ERROR_STOP=1 --username="$PGUSER" --dbname="$PGDATABASE" <<'SQL'
SET lock_timeout = '2s';
ALTER TABLE users ADD COLUMN customer_note text;
SQL
  if [ $? -eq 0 ]; then
    echo "Migration applied"
    exit 0
  fi
  echo "Lock timed out, retrying in $SLEEP seconds ($i/$RETRIES)..."
  sleep $SLEEP
  SLEEP=$((SLEEP * 2)) # exponential backoff
done

echo "Migration failed after $RETRIES retries"
exit 1
```

Important details and tips

| Topic | Recommendation / Notes |
| - | - |
| Metadata-only columns | Adding a nullable column with no default is metadata-only and generally does not rewrite rows. |
| Non-null/default behavior | Adding a column with a non-NULL default or `NOT NULL` constraint may cause a table rewrite depending on PostgreSQL version and the exact command. Test on the same PG version as production. |
| `lock_timeout` scope | `lock_timeout` is session-local — set it in the same session that runs the ALTER. |
| Error handling | Expect `canceling statement due to lock timeout` when timed out; design the migration runner to retry or abort gracefully. |
| Staging vs. production | Staging often lacks long-running analytic jobs, so it frequently won’t reproduce lock contention seen in production. |

Additional considerations

* If you must perform DDL during high load, consider:
  * Scheduling during a maintenance window.
  * Using a connection pooler that counts and rejects long-running sessions when applying schema changes.
  * Breaking large migrations into smaller steps where feasible.
* Monitor long transactions and locks (`pg_stat_activity`, `pg_locks`) to identify offending queries before running DDL.

Best practice: Always set a short `lock_timeout` (e.g., `1s`–`2s`) in the same session before running online schema changes in production, and ensure your migration runner can safely retry on timeout. This prevents long-running queries from turning a quick migration into a production outage.

References and further reading

* PostgreSQL: ALTER TABLE — [https://www.postgresql.org/docs/current/sql-altertable.html](https://www.postgresql.org/docs/current/sql-altertable.html)
* PostgreSQL: Locking — [https://www.postgresql.org/docs/current/explicit-locking.html](https://www.postgresql.org/docs/current/explicit-locking.html)
* Monitoring locks: `pg_stat_activity`, `pg_locks`

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/1ee75c71-d566-42df-8cc2-7aa8e79b0f04/lesson/8bb754e8-71a9-49ed-87a8-252f55ecdb9e)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.