
Safe Postgres Migrations in Rails Without Downtime
So adding a column in Postgres is instant, everybody says it, we too were saying, and then why people tell stories that their site was down because of such migration, we decided to make it happen on our laptop, Postgres 18, table users, five million rows which we generated for this.
Three terminals. First one does begin, a small count and then sleeps 10 seconds without commit, pretend it is somebody's long report. Second one runs our ALTER TABLE users ADD COLUMN nickname. Third one, after one second more, asks SELECT email FROM users WHERE id = 1, the most easy question what you can ask a database. And what? ALTER waited 9 seconds, this we expected, but the SELECT also waited, 7.98 seconds, for one row by primary key, because he stands in the queue behind the ALTER and ALTER stands behind the report.
We repeated all this with one line added, SET LOCAL lock_timeout to 2s. Now the ALTER got tired after two seconds, printed canceling statement due to lock timeout, and our poor SELECT was answered after around one second. Yes, the migration is failed and you have to run it again, so what, nobody on the site saw it, only you.
class AddNicknameToUsers < ActiveRecord::Migration[8.0]
def up
execute "SET LOCAL lock_timeout = '5s'"
add_column :users, :nickname, :string
end
def down
remove_column :users, :nickname
end
end
With defaults we were playing next, text default free on all the five million rows, 2 ms, we even did not believe, then uuid column with gen_random_uuid() as default and we could go for water, 11.4 seconds, since each row needs its own uuid Postgres rewrites everything and holds the lock the whole time.
NOT NULL is a funny one, because on our table the direct SET NOT NULL needed only about 140 ms and we thought why to bother, but these 140 ms are under the heavy lock and on your table with 500 million it will not be 140. The long way is CHECK with NOT VALID, 0.5 ms, then VALIDATE, also about 140 ms but people can read and write meanwhile, then SET NOT NULL 0.26 ms, it sees the check and doesn't scan again.
# Migration 1
add_check_constraint :users, "nickname IS NOT NULL",
name: "users_nickname_present", validate: false
# Migration 2
validate_check_constraint :users, name: "users_nickname_present"
change_column_null :users, :nickname, false
remove_check_constraint :users, name: "users_nickname_present"
The index we built two times, plain 5.4 seconds and CONCURRENTLY 5.8, so for almost same price your writes are not blocked. Only we made one email double and asked unique concurrently, boom, could not create unique index, and the broken i3 stayed lying in pg_index with indisvalid false until we will drop him ourselves.
class IndexOrdersOnUserId < ActiveRecord::Migration[8.0]
disable_ddl_transaction!
def change
add_index :orders, :user_id, algorithm: :concurrently
end
end
SELECT indexrelid::regclass
FROM pg_index
WHERE NOT indisvalid;
See also: the indexing guide and Active Record patterns.