skip to content

Lock-Safe Changes

On a busy table strong_migrations blocks risky DDL until you use concurrent indexes, unvalidated constraints and ignored_columns before a drop. Interviewers ask how to ship each change live.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

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?

level: seniorimportance: must knowfreq 58%

answer

  1. default migration runs in a transaction
  2. algorithm: :concurrently on add_index
  3. disable_ddl_transaction! on the class
  4. no rollback if it fails halfway
  5. invalid index left behind on failure

basics

~20 s

Call 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 s

A 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 lines
ruby
class AddAccountOccurredAtIndexToEvents < ActiveRecord::Migration[8.1]
  disable_ddl_transaction!

  def change
    add_index :events, [:account_id, :occurred_at],
      algorithm: :concurrently
  end
end

go deeper

for a junior

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.

for a middle

Explain why the pair exists: Rails wraps migrations in a transaction, and PostgreSQL will not build an index concurrently inside one.

for a senior

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.

for a principal

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
open as a page

In a Rails 8.1 app, how do you drop the legacy_payload column from a busy events table without errors from servers still running the old code?

level: seniorimportance: must knowfreq 55%

basics

~10 s

Ship it in two releases: first add self.ignored_columns += ["legacy_payload"] to Event and remove every use, then deploy a migration with safety_assured { remove_column :events, :legacy_payload, :jsonb }, and finally delete the ignore line.

open as a page

In a Rails app using the strong_migrations gem, what happens when a migration runs a risky operation, and what is safety_assured for?

level: juniorimportance: should knowfreq 38%

basics

~20 s

strong_migrations checks each schema call a Rails migration makes and stops risky ones, such as blocking index builds or column drops, with StrongMigrations::UnsafeMigration and a safer recipe. safety_assured { ... } skips the check for a step you made safe.

open as a page

Why should a Rails migration that adds a column to the busy events table not also backfill it with Event.update_all?

level: middleimportance: should knowfreq 50%

basics

~20 s

Rails runs the migration in one transaction, so add_column's lock on events lasts until the UPDATE over every row commits, blocking traffic for the whole backfill. Add the column in one migration; backfill in batches outside a transaction.

open as a page

With strong_migrations in a Rails app, where do the 10-second lock timeout and 1-hour statement timeout come from, and why does a migration need them?

level: middleimportance: should knowfreq 28%

basics

~20 s

They come from config/initializers/strong_migrations.rb, which bin/rails generate strong_migrations:install writes; the gem itself sets no timeout. The short lock timeout stops a waiting ALTER from queueing all traffic behind it, and the long statement timeout lets index builds finish.

open as a page

In a Rails migration on PostgreSQL, why add a foreign key from events to accounts with validate: false and validate it in a second migration?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Adding a validated foreign key makes PostgreSQL check all 50 million existing events while writes are blocked. With validate: false only new writes are checked, and validate_foreign_key later scans the old rows under a lock that lets writes continue.

open as a page