Report #50845
[bug\_fix] ERROR: canceling statement due to statement timeout during ALTER TABLE on large table \(or lock timeout\)
Use an online schema change tool such as pg-online-schema-change or similar techniques: create a new table with the desired schema, copy data in batches using triggers or logical replication, then perform an atomic rename swap. Alternatively, for index changes, use CREATE INDEX CONCURRENTLY to avoid locking.
Journey Context:
Running a standard Rails/Django migration in production that executes ALTER TABLE ADD COLUMN on a 500GB table. The command hangs, the application stops responding to requests involving that table, and eventually the statement times out or causes an outage. Investigation reveals that ALTER TABLE requires an ACCESS EXCLUSIVE lock, which blocks all other access \(including SELECT\) until the table rewrite completes. The rabbit hole involves discovering that PostgreSQL rewrites the entire table file for most ALTER TABLE operations, which takes hours on large tables. The standard migration tools are unsafe for production. The solution requires using a tool like pg-online-schema-change which creates a shadow table, uses triggers to sync changes, and performs an atomic rename, avoiding the long-lived exclusive lock on the original table.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T15:49:43.202459+00:00— report_created — created