Deploy migration rewrote a Postgres table and blocked all writes
A routine deploy changed an integer column to bigint. Postgres rewrote the 90-million-row table under an ACCESS EXCLUSIVE lock and every write to orders queued for 14 minutes. We rebuilt the change as expand and contract with a trigger, batched backfill, lock_timeout and a separate migration step.
The deploy pipeline for our order service runs database migrations in the release job, right before the new pods roll out. On a Tuesday afternoon the release job stalled at the migration step. Within a minute, checkout error rates climbed and API latency for anything that wrote to orders hit the 30-second gateway timeout:
upstream request timeout
POST /v1/orders 504 30001ms
The pipeline log just showed the migration waiting:
== 20270209_widen_order_ids: migrating =====
-- change_column(:order_items, :order_id, :bigint)
Reads mostly kept working. Inserts and updates to orders and order_items piled up.
Reproducing it
On a staging copy with production-sized data, in one session:
ALTER TABLE order_items ALTER COLUMN order_id TYPE bigint;
In a second session, any INSERT INTO order_items hangs until the first statement finishes. On 90 million rows, it took 14 minutes on our instance size.
What we ruled out
A long-running transaction holding a lock (the case post 25 describes).
pg_stat_activityshowed no idle-in-transaction sessions older than a few seconds before the migration started.MySQL-style metadata lock wait (post 31). This was Postgres, and the migration was not waiting to acquire its lock; it held it and was working.
Disk or CPU saturation. I/O was high, as expected for a rewrite, but not enough by itself to explain blocked writes.
The lock view made it clear:
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 60)
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';
Every waiting session listed the migration's PID in blocked_by.
Root cause
ALTER COLUMN ... TYPE bigint on an integer column is not a metadata-only change in Postgres. The on-disk size of the value changes, so Postgres rewrites the whole table and rebuilds every index that includes the column, while holding an ACCESS EXCLUSIVE lock on the table. That lock conflicts with every other lock mode, including the ROW EXCLUSIVE lock that INSERT, UPDATE and DELETE take. Our migration framework ran it as one statement, with no lock timeout, in the deploy path.
What is happening under the hood
Postgres ALTER TABLE forms fall into three groups by cost:
Change | Lock | Rewrite or scan |
|---|---|---|
| ACCESS EXCLUSIVE, brief | None |
| ACCESS EXCLUSIVE, brief | None |
| ACCESS EXCLUSIVE, held throughout | Full table rewrite + index rebuild |
| ACCESS EXCLUSIVE | Full scan, unless a valid |
| SHARE ROW EXCLUSIVE on both tables | Full validation scan |
| Brief lock, then SHARE UPDATE EXCLUSIVE during validation | Scan without blocking writes |
Two more facts make the "brief" cases dangerous too. First, even a brief ACCESS EXCLUSIVE request waits behind any running query on the table, and every new query queues behind the waiting request. Second, without lock_timeout, that wait is unlimited.
Environment
Component | Version / value |
|---|---|
Database | PostgreSQL 16 on a managed service, 8 vCPU |
Tables |
|
Migration tool | Framework migrations run by the CI release job |
Deploy | GitLab pipeline: migrate job, then Kubernetes rolling update |
Trigger |
|
Minimal reproduction
CREATE TABLE order_items (id bigserial PRIMARY KEY, order_id integer NOT NULL, sku text);
INSERT INTO order_items (order_id, sku)
SELECT g % 1000000, 'sku-' || g FROM generate_series(1, 20000000) g;
CREATE INDEX ON order_items (order_id);
-- session 1
ALTER TABLE order_items ALTER COLUMN order_id TYPE bigint;
-- session 2, blocks until session 1 finishes
INSERT INTO order_items (order_id, sku) VALUES (42, 'sku-x');
Who is affected
Any Postgres deployment that runs type changes, SET NOT NULL, validated constraints or non-concurrent index builds on large, busy tables inside a deploy. The pressure to widen integer keys usually arrives when a sequence approaches its limit, which is exactly when the table is biggest.
The fix
We stopped the incident by cancelling the migration (SELECT pg_cancel_backend(<pid>)), which rolled back cleanly; writes resumed within seconds. Then we rebuilt the change as expand and contract, spread over three releases.
Step 0: protect every migration with timeouts. Our migration runner now sets these for each migration session:
SET lock_timeout = '3s';
SET statement_timeout = '15min';
A migration that cannot get its lock fails fast instead of queuing all traffic behind it:
ERROR: canceling statement due to lock timeout
The pipeline retries such migrations up to three times with a delay.
Release 1, expand: add the new column and keep it in sync.
ALTER TABLE order_items ADD COLUMN order_id_new bigint;
CREATE FUNCTION order_items_sync_order_id() RETURNS trigger AS $$
BEGIN
NEW.order_id_new := NEW.order_id;
RETURN NEW;
END $$ LANGUAGE plpgsql;
CREATE TRIGGER order_items_sync_order_id
BEFORE INSERT OR UPDATE OF order_id ON order_items
FOR EACH ROW EXECUTE FUNCTION order_items_sync_order_id();
Both statements take only brief locks.
Backfill in batches, outside the deploy. A background job copies existing values in small chunks, committing each batch so locks and WAL stay small:
UPDATE order_items
SET order_id_new = order_id
WHERE id >= $1 AND id < $1 + 10000
AND order_id_new IS NULL;
It ran for about six hours with a short sleep between batches and replica lag kept under one second.
Build indexes and constraints without blocking writes.
CREATE INDEX CONCURRENTLY order_items_order_id_new_idx ON order_items (order_id_new);
ALTER TABLE order_items
ADD CONSTRAINT order_id_new_not_null CHECK (order_id_new IS NOT NULL) NOT VALID;
ALTER TABLE order_items VALIDATE CONSTRAINT order_id_new_not_null;
CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so this migration is flagged to run outside one. If it fails midway it leaves an INVALID index that must be dropped before retrying.
Release 2, switch: swap the columns in one short transaction.
BEGIN;
SET LOCAL lock_timeout = '3s';
ALTER TABLE order_items ALTER COLUMN order_id_new SET NOT NULL; -- uses the valid CHECK, no scan
DROP TRIGGER order_items_sync_order_id ON order_items;
ALTER TABLE order_items RENAME COLUMN order_id TO order_id_old;
ALTER TABLE order_items RENAME COLUMN order_id_new TO order_id;
COMMIT;
The application reads the column by name, so the rename is invisible to it.
Release 3, contract: drop the old column and its indexes once no running version references order_id_old.
We ran the same sequence for orders.id itself. A primary key swap needs one extra step: build a unique index on the new column concurrently, then attach it in the switch transaction with ADD CONSTRAINT orders_pkey PRIMARY KEY USING INDEX, and move the sequence ownership with ALTER SEQUENCE ... OWNED BY and ALTER SEQUENCE ... AS bigint. Foreign keys that point at the old key must be dropped in the same transaction and re-added as NOT VALID, then validated in a later migration.
Move migrations out of the rollout path. Migrations now run in their own pipeline job with its own approval for anything flagged "heavy" by a lint script. The rollout job only starts after the migration job succeeds, and app code in each release works with both the before and after schema.
Alternatives and trade-offs
Online schema change tools.
pg-oscandpgrollautomate shadow-table or expand/contract migrations for Postgres;gh-ostandpt-online-schema-changedo the same for MySQL. They save effort on repeated changes and add a dependency to operate.Maintenance window. Running the plain
ALTERat 3 a.m. with traffic stopped is legitimate for internal systems. It was not an option for checkout.Logical replication to a new table. For very large tables, replicate into a pre-created table with the new types and switch over. More moving parts, but no long backfill on the primary.
How to test the fix
We rehearsed every step on a staging snapshot while a load generator issued production-like inserts. Pass criteria: no insert latency above 200 ms during any migration step, and the lock view returning no rows blocked for more than one second.
SELECT count(*) FILTER (WHERE wait_event_type = 'Lock') AS waiting
FROM pg_stat_activity WHERE datname = current_database();
Confirming in production
During the three releases, p99 insert latency on order_items stayed under 40 ms, and the migration jobs each took less than five seconds of lock time. After the switch, orders.id and order_items.order_id were both bigint, and a check of information_schema.columns confirmed no remaining integer foreign keys to orders.
Regression guard
A migration lint step fails merge requests that contain
ALTER COLUMN ... TYPE,SET NOT NULLwithout a prior valid check constraint,ADD FOREIGN KEYwithoutNOT VALID, orCREATE INDEXwithoutCONCURRENTLY, unless the migration is explicitly marked safe with a reason.The migration runner refuses to run without
lock_timeoutset.An alert fires when any sequence passes 70% of its type's maximum, so key widening is planned months ahead.
SELECT schemaname, sequencename, last_value, max_value,
round(100.0 * last_value / max_value, 1) AS pct
FROM pg_sequences
WHERE last_value IS NOT NULL
ORDER BY pct DESC LIMIT 5;
Security implications
The incident was an availability problem rather than a data-exposure one, but a migration that blocks writes for minutes is effectively self-inflicted denial of service. The trigger function runs with the privileges of its owner; keep it owned by the migration role and do not mark it SECURITY DEFINER. Migration credentials should be separate from application credentials, available only to the migration job, and not to every pod.
Prevention checklist
Set
lock_timeoutandstatement_timeoutfor every migration session.Treat type changes,
SET NOT NULL, constraint validation and index builds on large tables as multi-release changes.Run migrations as a separate pipeline step, never inside app startup.
Rehearse heavy migrations on production-sized data under load.
Alert on sequences approaching their limit.
References
PostgreSQL Docs, ALTER TABLE: https://www.postgresql.org/docs/16/sql-altertable.html
PostgreSQL Docs, Explicit locking (table-level lock modes): https://www.postgresql.org/docs/16/explicit-locking.html
PostgreSQL Docs, CREATE INDEX (building indexes concurrently): https://www.postgresql.org/docs/16/sql-createindex.html
PostgreSQL Docs, Client connection defaults (lock_timeout): https://www.postgresql.org/docs/16/runtime-config-client.html
pgroll README: https://github.com/xataio/pgroll
Add a label
Embed this post
<iframe src="https://www.hibug.me/deploy-migration-locked-table-expand-contract" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I lead security operations for engineering organisations that are too big to ignore security and too small for a large security team. That means a bit of everything: vulnerability management, logging and detection, cloud configuration reviews, phishing response and incident handling. The posts here are practical: what to set up first, what to measure, which alerts are worth waking someone for, and what to do in the first hour of an incident. Where I describe incidents, details are changed, but the mistakes and the fixes are real patterns I have seen more than once.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.