skip to content

Why can validates :username, uniqueness: true still let two players register the same username, and how do you close the gap in a Rails app?

level: seniorimportance: must knowfreq 65%

answer

  1. check, then insert: two statements
  2. both requests see no row
  3. unique index is the real guard
  4. rescue ActiveRecord::RecordNotUnique
  5. keep the validation for the message

basics

~20 s

The validator runs a SELECT and the save runs a later INSERT, so two concurrent requests can both find no row and both insert. A unique index makes the second INSERT fail with ActiveRecord::RecordNotUnique, which the app rescues into a :taken error.

solid answer

~40 s

Uniqueness validation is a read followed by a write. Two sign-ups for `coachamy` arrive together; each runs `SELECT 1 ... WHERE username = 'coachamy' LIMIT 1`, each sees nothing, and each INSERT succeeds. Wrapping the save in a transaction does not help, because the check reads committed rows and takes no lock. The fix has two parts: a **unique index** on the same columns the validator uses (lower-cased if the validator is case-insensitive), so the database rejects the second INSERT; and handling that rejection, which Active Record raises as `ActiveRecord::RecordNotUnique`. Rescue it around the save and add `errors.add(:username, :taken)` so the user sees the same message as the validator would give. Keep the validation: it catches the common case with a friendly error before touching the index.

code

ruby · 17 lines
ruby
class Player < ApplicationRecord
  validates :username, uniqueness: { scope: :league_id }

  def register
    save
  rescue ActiveRecord::RecordNotUnique
    errors.add(:username, :taken)
    false
  end
end

# A unique index on (league_id, username) is assumed to exist.
if @player.register
  redirect_to @player
else
  render :new, status: :unprocessable_content
end

go deeper

for a junior

Recall that the uniqueness validator checks with a query and that a unique index in the database is the real guarantee.

for a middle

Explain the check-then-insert gap and why a transaction around the save does not close it.

for a senior

Pair every uniqueness rule with a matching index and a RecordNotUnique handler, including case and scope, and test the concurrent path.

for a principal

Make database constraints the source of truth for invariants and treat model validations as user-facing feedback layered on top.

## The race, step by step Registration for a youth-sports league opens at 9:00 and hundreds of parents sign up at once. Two of them choose `coachamy` within the same few milliseconds. With only the model validation in place: | Time | Request A | Request B | |---|---|---| | t1 | `SELECT 1 ... WHERE username = 'coachamy' LIMIT 1` returns nothing | | | t2 | | the same SELECT returns nothing | | t3 | `INSERT INTO players ... 'coachamy'` succeeds | | | t4 | | `INSERT INTO players ... 'coachamy'` succeeds | Two rows now hold the same username. Every individual step behaved correctly: the validator's query was true when it ran. The problem is that **the check and the write are separate statements**, and nothing reserves the value in between. ## Why the usual reflexes do not fix it - **A transaction around the save** does not help: the SELECT sees only committed rows and takes no lock, so both transactions still pass the check. - **Running the validation twice** narrows the window but cannot close it. - **`validates :username, uniqueness: true` plus `save!`** only changes how a validation failure is reported, not whether the race exists. ## The fix: a unique index plus a handler 1. **Add a unique index** covering exactly what the validator checks: `username` alone, or `(league_id, username)` for a scoped rule. For a case-insensitive rule the index must be case-insensitive too (an index on the lower-cased value, or a normalized column). Writing that migration belongs to the migrations topic; the point here is that the database is the only component that sees both INSERTs. 2. **Handle the violation.** When the second INSERT breaks the index, the adapter raises `ActiveRecord::RecordNotUnique`. Without a handler, the user gets an error page. With one, they get a form error: ```ruby def register save rescue ActiveRecord::RecordNotUnique errors.add(:username, :taken) false end ``` 3. **Keep the validation.** It still catches nearly every duplicate with a friendly message and no database exception, and it lets `valid?` report the problem before a save is attempted. ## What each layer contributes | Layer | Catches | User experience | |---|---|---| | `uniqueness` validation | duplicates that already exist when the request starts | normal form error | | unique index | the concurrent duplicate the validation missed | `RecordNotUnique`, turned into the same error by the rescue | ## Related details - **Which exception.** The bundled adapters (PostgreSQL, MySQL via mysql2 or Trilogy, SQLite) raise `ActiveRecord::RecordNotUnique` for unique-index violations, so you do not need to parse database messages. - **Inside a larger transaction.** On PostgreSQL a failed statement aborts the surrounding transaction, so rescuing inside an outer transaction and carrying on does not work; rescue at the boundary of the transaction, or keep the save in its own (savepoint and transaction mechanics belong to the transactions topic). - **Updates as well as inserts.** Renaming a player to an existing username races the same way and is caught by the same index. - **`create_or_find_by`** relies on the same unique index: it attempts the INSERT first and falls back to a lookup when `RecordNotUnique` is raised. ## What an interviewer is checking The expected answer names the gap (check-then-act across two statements), names the guard (a unique index the database enforces), and names the Rails exception and how to turn it back into a validation error. Saying "add a unique index" without handling `RecordNotUnique` leaves users with an error page in exactly the moment the race occurs. ## Testing the concurrent path The race itself is hard to reproduce in a test, but the handler is easy to exercise by letting only the index see the duplicate: 1. Create `coachamy` normally. 2. Build a second player with the same username and stub its `valid?` to return `true`, standing in for a validation that ran before the first row existed. 3. Call `register` and assert it returned `false` and that `errors.of_kind?(:username, :taken)` is true. That proves the rescue turns `ActiveRecord::RecordNotUnique` into the same error the validator would give, which is the part users actually see when the race happens.

  • The validator says uniqueness: { case_sensitive: false } but the unique index is on username as stored. Which duplicates can still get in?
    Concurrent sign-ups that differ only in case, such as `CoachAmy` and `coachamy`. The validator treats them as equal, but a plain index sees two different values. The index must enforce the same rule, on the lower-cased value or a normalized column.
  • Why is a transaction around the save not enough to prevent the duplicate?
    The validator's SELECT reads only committed rows and takes no lock, so two transactions running at once both see no matching row and both insert. Only a constraint checked by the database on write, the unique index, sees both.

The validation is a receptionist checking the sign-up sheet for your name before handing you a pen; two people can both see a blank line and both write. The unique index is the sheet itself refusing a second identical line, and the rescue is the receptionist apologising instead of the room catching fire.

  • Saying a transaction around save makes uniqueness validation race-free.
  • Removing the validation once the unique index exists, losing the friendly message.
  • Adding the index but letting RecordNotUnique surface as an error page.
  • Expecting save to return false when the unique index rejects the INSERT.
  • Backing a case-insensitive validator with a case-sensitive index.