One line stops a migration from taking down production. Almost nobody adds it.
Here is how a migration that does no work at all takes a table offline. ALTER TABLE orders ADD COLUMN note text; A nullable column, no default. This is a catalog change; on its own it holds its lock for a few milliseconds. It does not matter how big the table is. What matters is who else is holding a lock on the table when it asks for its own, and that is something the migration author can not…
ALTER TABLE statements that add a column to a table without specifying a lock timeout can cause database migrations to stop, even if the migration itself is harmless. This happens because the ALTER TABLE statement requests a lock called ACCESS EXCLUSIVE, which conflicts with all other locks including the read-only ACCESS SHARE lock used by simple SELECT queries. If another transaction already holds any lock on the table, the ALTER TABLE statement must wait, as it cannot proceed until that lock is freed.
PostgreSQL grants locks in order, so once the ALTER TABLE statement is queued, every subsequent request that conflicts with ACCESS EXCLUSIVE will be queued behind it, regardless of whether it is a read or write operation. This means that even a seemingly harmless migration that adds a nullable column to a table can lock the entire table for a significant amount of time, potentially causing downtime for the entire application.
A simple way to prevent this issue is to add a line setting the lock_timeout parameter to a value such as 2 seconds when running the ALTER TABLE statement. This tells PostgreSQL to give up the lock after the specified time if it cannot be obtained. By using this guard, the migration can be retried until it successfully acquires the lock, ensuring that the table change is completed without locking the entire database. This small addition can prevent unexpected outages and ensure smooth migration processes.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.