skip to content

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%

answer

  1. a validated constraint scans every row
  2. validate: false checks only new writes
  3. validate_foreign_key in its own migration
  4. same transaction keeps the blocking lock
  5. check constraint route to NOT NULL

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.

solid answer

~40 s

`add_foreign_key :events, :accounts` adds the constraint and checks every existing row in one step, blocking writes on both tables until the scan ends. With `validate: false` (a PostgreSQL-only option) the constraint is created in a moment and enforced for every new insert and update, but existing rows are not checked. A second migration then calls `validate_foreign_key :events, :accounts`, which scans the old rows while writes keep flowing. It must be a separate migration (or one with `disable_ddl_transaction!`): in the same transaction, the lock taken by the add is still held, so the scan would block writes after all, and strong_migrations stops it. The same pair, `add_check_constraint ... validate: false` then `validate_check_constraint`, is how you reach `NOT NULL` on an existing column.

code

ruby · 18 lines
ruby
class AddAccountIdNotNullCheckToEvents < ActiveRecord::Migration[8.1]
  def change
    add_check_constraint :events, "account_id IS NOT NULL",
      name: "events_account_id_null", validate: false
  end
end

class ValidateAccountIdNotNullOnEvents < ActiveRecord::Migration[8.1]
  def up
    validate_check_constraint :events, name: "events_account_id_null"
    change_column_null :events, :account_id, false
    remove_check_constraint :events, name: "events_account_id_null"
  end

  def down
    change_column_null :events, :account_id, true
  end
end

go deeper

for a junior

Remember that a foreign key or check constraint on a big table goes in two migrations: add it with validate: false, then validate it.

for a middle

Explain what each step checks: new writes from the first moment, existing rows only when validate_foreign_key or validate_check_constraint runs.

for a senior

Explain why the steps need separate transactions, how to reach NOT NULL through a check constraint, and how to handle orphan rows that make validation fail.

for a principal

Weigh database constraints against model validations on the largest tables, and decide whether safe_by_default or explicit two-step migrations fit the team.

## The constraint and its cost In the analytics product, `events.account_id` points at `accounts.id`, but the column was added without a database-level **foreign key**. Now the team wants one, so that no event can reference a deleted account. `add_foreign_key :events, :accounts` makes PostgreSQL do two things at once: create the constraint, and **validate** it, meaning check that every one of the 50 million existing rows has a matching account. During that scan, writes to both tables are blocked. strong_migrations flags it: adding a foreign key blocks writes on both tables. ## Splitting creation from validation Active Record's `add_foreign_key` accepts **`validate: false`** on PostgreSQL. The constraint is then created as `NOT VALID`: - creation needs only a short lock and no table scan; - from that moment, **every new insert or update** is checked against `accounts`; - the **existing rows** are not checked yet, so the constraint is not marked valid. A second migration runs **`validate_foreign_key :events, :accounts`**, which runs `ALTER TABLE ... VALIDATE CONSTRAINT`. Validation still reads the whole table, but under a lighter lock that lets reads and writes continue. ```ruby class AddAccountsForeignKeyToEvents < ActiveRecord::Migration[8.1] def change add_foreign_key :events, :accounts, validate: false end end class ValidateAccountsForeignKeyOnEvents < ActiveRecord::Migration[8.1] def change validate_foreign_key :events, :accounts end end ``` ## Why the second step is a separate migration Rails runs each migration in **one transaction** on PostgreSQL, and a lock taken inside a transaction is held until it commits. If the same migration adds the constraint and then validates it, the lock from the add is still held while validation scans 50 million rows, and writes block exactly as before. strong_migrations checks for this: before `validate_foreign_key` or `validate_check_constraint`, it looks for a lock held by the current transaction that blocks writes, and if it finds one it stops with "Validating a foreign key while writes are blocked is dangerous. Use disable_ddl_transaction! or a separate migration." If validation fails because some events point at deleted accounts, the migration raises and you fix the orphans first; the constraint stays `NOT VALID` and keeps protecting new rows. ## The same pattern for other constraints | Goal | Step 1 | Step 2 | |---|---|---| | foreign key | `add_foreign_key ..., validate: false` | `validate_foreign_key` | | check constraint | `add_check_constraint :events, "duration_ms >= 0", name: "events_duration_ms_non_negative", validate: false` | `validate_check_constraint :events, name: "events_duration_ms_non_negative"` | | `NOT NULL` on an existing column | `add_check_constraint :events, "account_id IS NOT NULL", name: "events_account_id_null", validate: false` | `validate_check_constraint`, then `change_column_null :events, :account_id, false`, then `remove_check_constraint` | The `NOT NULL` route exists because `change_column_null :events, :account_id, false` on its own makes PostgreSQL scan every row under a lock that blocks reads and writes. Once a validated check constraint already proves no row is null, PostgreSQL can set `NOT NULL` without that scan, and the helper constraint can go. ## What the schema dump records An unvalidated constraint is a real state of the database, and Rails records it. `db/schema.rb` writes `validate: false` on an `add_foreign_key` or check constraint that has not been validated yet, so a fresh `bin/rails db:schema:load` reproduces the same state rather than pretending the constraint was checked. Once the validating migration has run, the next dump drops the option. You can check the current state from a console with `ActiveRecord::Base.connection.foreign_keys(:events)` and read each key's `validate?`. ## Practical notes 1. Name check constraints explicitly; `validate_check_constraint` and `remove_check_constraint` find them by `name:`. 2. `validate: false` is **PostgreSQL only**. On other adapters, Rails does not support creating an unvalidated constraint. 3. With `StrongMigrations.safe_by_default = true`, the gem rewrites a plain `add_foreign_key` or `add_check_constraint` into this two-step form for you, committing between the steps. 4. Make sure the application already writes valid data before step 1, or new writes will start failing as soon as the unvalidated constraint exists. 5. For a new reference column, `add_reference :events, :campaign, index: {algorithm: :concurrently}, foreign_key: {validate: false}` in a migration with `disable_ddl_transaction!` gives you the column, a non-blocking index and an unvalidated key in one step; validate the key in the next migration. 6. Run the validating migration at a quiet time anyway: it does not block writes, but it reads the whole table and competes for I/O with production traffic.

  • Validation fails because some events reference deleted accounts. What now?
    The validating migration raises and records no version; the constraint stays `NOT VALID` and still checks new writes. Clean up the orphans (delete them or point them at a placeholder account) in a batched data fix, then rerun `bin/rails db:migrate` to validate.
  • Could you validate in the same migration if it declares disable_ddl_transaction!?
    Yes. Without the wrapping transaction, the add commits and releases its lock before validation starts, which is why strong_migrations' message offers either option. A separate migration is still clearer and easier to rerun.

  • validate: false means the constraint checks nothing until it is validated
  • validating in the same migration is fine because it is one transaction
  • change_column_null to false is a quick catalogue change on any size table
  • validate_foreign_key blocks all writes for the length of its scan
  • validate: false works the same way on MySQL and SQLite