In a Rails app on PostgreSQL, how do you add an index to a 50-million-row events table without blocking writes, and what does that cost the migration?
answer
- default migration runs in a transaction
- algorithm: :concurrently on add_index
- disable_ddl_transaction! on the class
- no rollback if it fails halfway
- invalid index left behind on failure
basics
~20 sCall add_index :events, [:account_id, :occurred_at], algorithm: :concurrently in a migration that declares disable_ddl_transaction!. The build no longer blocks writes, but the migration loses its transaction, so a failure leaves partial work and no schema_migrations row.
solid answer
~40 sA plain `add_index` on PostgreSQL blocks writes to `events` for the whole build, which on 50 million rows can be minutes of failed inserts. `algorithm: :concurrently` makes Active Record emit `CREATE INDEX CONCURRENTLY`, which lets writes continue, but PostgreSQL refuses to run it inside a transaction block, and Rails wraps every migration in one. So the class also declares `disable_ddl_transaction!`; forget it and the migration fails with `ActiveRecord::StatementInvalid`. The cost: the migration is no longer atomic. If the build fails or is cancelled, nothing is rolled back, no `schema_migrations` row is written, and PostgreSQL may leave an invalid index that makes the rerun fail. Keep such a migration to that one index, and with strong_migrations set `remove_invalid_indexes = true` or drop the leftover with `remove_index ..., algorithm: :concurrently`.
code
ruby · 8 linesclass AddAccountOccurredAtIndexToEvents < ActiveRecord::Migration[8.1]
disable_ddl_transaction!
def change
add_index :events, [:account_id, :occurred_at],
algorithm: :concurrently
end
endgo deeper
Remember the pair: algorithm: :concurrently on add_index and disable_ddl_transaction! on the migration class. One without the other either blocks writes or fails.
Explain why the pair exists: Rails wraps migrations in a transaction, and PostgreSQL will not build an index concurrently inside one.
Talk about failure: no rollback, no schema_migrations row, an invalid index to remove, one index per migration, a lock timeout so the build does not queue writes.
Decide the team default, such as safe_by_default or reviewed safety_assured blocks, and how index changes on the largest tables are scheduled and watched.
## The problem on a busy table An analytics product stores every tracked action in an `events` table with **50 million rows** and a steady stream of inserts. A new dashboard filters by account and time, so it needs an index on `[:account_id, :occurred_at]`. The obvious migration, `add_index :events, [:account_id, :occurred_at]`, makes PostgreSQL build the index while **blocking writes** to the table. Reads keep working, but every `INSERT` from the tracking endpoint waits until the build finishes, which on a table this size can take minutes. Requests time out, Puma threads pile up, and the incident starts. strong_migrations flags exactly this call on PostgreSQL: a non-concurrent `add_index` on a table that was not created in the same migration raises `StrongMigrations::UnsafeMigration` and prints the safe version. ## The two lines that make it safe ```ruby class AddAccountOccurredAtIndexToEvents < ActiveRecord::Migration[8.1] disable_ddl_transaction! def change add_index :events, [:account_id, :occurred_at], algorithm: :concurrently end end ``` - **`algorithm: :concurrently`** is an `add_index` option. On PostgreSQL, Active Record turns it into `CREATE INDEX CONCURRENTLY`, which builds the index while inserts and updates continue. It takes longer and does more work than a plain build, but nothing queues behind it for long. - **`disable_ddl_transaction!`** is a class method on `ActiveRecord::Migration`. By default Rails runs each migration inside a transaction on adapters that support transactional DDL, which PostgreSQL does. PostgreSQL refuses to run `CREATE INDEX CONCURRENTLY` inside a transaction block, so without this line the migration fails with `ActiveRecord::StatementInvalid` wrapping `PG::ActiveSqlTransaction`. The algorithm name is adapter-specific. PostgreSQL's adapter accepts only `:concurrently`; MySQL's accepts `:default`, `:copy`, `:inplace` and `:instant`. Passing `algorithm: :inplace` on PostgreSQL raises `ArgumentError` before any SQL runs. ## What losing the transaction costs With the transaction gone, the migration is **not atomic** any more: 1. Each statement commits on its own. If a migration had three statements and the second failed, the first stays applied. 2. Rails writes the `schema_migrations` row only after `change` returns. A failure leaves **no row**, so the next `bin/rails db:migrate` runs the whole migration again. 3. A failed or cancelled concurrent build can leave an **invalid index** in the catalogue. The rerun then fails because an index with that name already exists, and `if_not_exists: true` would skip the build and keep the broken one. The habits that follow: - Put **one** concurrent index, and nothing else, in a migration that disables the transaction. - With strong_migrations, set `StrongMigrations.remove_invalid_indexes = true` so a rerun drops an invalid leftover before building again, or drop it yourself with `remove_index :events, [:account_id, :occurred_at], algorithm: :concurrently`. - Set a short **lock timeout** (strong_migrations' generated initializer uses 10 seconds) so the build gives up instead of waiting behind a long transaction while new writes queue behind it. ## Related calls that need the same treatment | Call | Safe form on PostgreSQL | |---|---| | `add_index` | `algorithm: :concurrently` plus `disable_ddl_transaction!` | | `add_reference :events, :campaign` | `index: {algorithm: :concurrently}` plus `disable_ddl_transaction!` | | `remove_index` | `algorithm: :concurrently` (strong_migrations checks it only after `enable_check(:remove_index)`) | | index on a table created in the same migration | plain `add_index`; nobody else can be writing to it yet | `add_reference` adds an index by default, which is why strong_migrations flags it too. A foreign key on the reference brings its own lock, handled with `validate: false`. ## Deploy order for an index An index is the easy case for deploy order. Queries work without it, only more slowly, so the migration can ship **before** the code that depends on it: merge the index migration, let it run, check it, then ship the dashboard query. The reverse order, code first, risks a slow full scan on every dashboard load until the index exists. When an index is being replaced, build the new one first, move the queries, and only then drop the old one, ideally with `remove_index ..., algorithm: :concurrently` in a migration that also declares `disable_ddl_transaction!`. ## Checking the result After the deploy, confirm the index is valid and used before you rely on it. strong_migrations' generated initializer also sets `auto_analyze = true`, which runs `ANALYZE` on the table after an index is added so the planner has fresh statistics. Finally, `db/schema.rb` records the index like any other; the algorithm is not part of the dump, because it describes how the index was built, not what it is.
- The same migration also adds a column to events. Why is that a problem?With `disable_ddl_transaction!` each statement commits alone. If the index build fails after `add_column` succeeded, the column stays, no `schema_migrations` row exists, and the rerun fails on the duplicate column. Split them: the column in a normal transactional migration, the concurrent index in its own.
- How do you add a reference with its index on the busy events table?Declare `disable_ddl_transaction!` and write `add_reference :events, :campaign, index: {algorithm: :concurrently}`. If the reference needs a foreign key, add it separately with `add_foreign_key :events, :campaigns, validate: false` and validate it in a later migration, since a validated foreign key would block writes on both tables.
- algorithm: :concurrently alone is enough; Rails handles the transaction
- a failed concurrent index migration is rolled back like any other
- use algorithm: :inplace on PostgreSQL for a non-blocking index
- put several concurrent indexes and column changes in one migration
- adding an index only blocks reads, so writes keep flowing