Postgres Lock Modes in Rails: FOR UPDATE vs FOR SHARE vs Advisory
Every Rails row-lock mode: FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, SKIP LOCKED and advisory locks — when to use each and how the wrong one causes deadlocks.
Contents
- The four row-lock modes, from strongest to weakest
- Your writes already take these locks
- How Rails exposes each mode
- NOWAIT and SKIP LOCKED
- Advisory locks: when the thing to lock isn’t a row
- Table locks: migrations take them too
- How the wrong mode causes deadlocks
- Common mistakes
- Key takeaways
- FAQ
- What is the difference between FOR UPDATE and FOR SHARE in Postgres?
- What does .lock do in Rails?
- When should I use FOR NO KEY UPDATE instead of FOR UPDATE?
- What is a Postgres advisory lock and when should I use it in Rails?
- Does .lock work outside a transaction?
- Conclusion
Rails gives you one obvious locking method — .lock — and most engineers use it for everything. But .lock is SELECT ... FOR UPDATE, the strongest row lock Postgres has, and reaching for it reflexively turns a mild concurrency concern into a throughput bottleneck. Postgres offers four row-lock modes of increasing strength, two ways to avoid waiting, and advisory locks for things that aren’t rows at all.
This is the field guide to those modes: what each one blocks, how Rails exposes it, and how the wrong choice shows up as a deadlock. Pair it with the interactive Postgres lock-mode lookup.
The four row-lock modes, from strongest to weakest
The four modes differ in exactly one thing: which other row locks they refuse to coexist with. A lock is defined by what it conflicts with. None of them blocks a plain SELECT; row locks block only writers and other lockers of the same row.
FOR UPDATE — the exclusive lock. Once you hold it, no other transaction can lock, update or delete that row until you commit. This is what .lock gives you.
FOR NO KEY UPDATE — slightly weaker. It behaves like FOR UPDATE except it does not conflict with FOR KEY SHARE, the lock Postgres’s foreign-key checks take on a parent row when another transaction inserts a child referencing it. So FOR NO KEY UPDATE lets those inserts proceed while you update the parent’s non-key columns.
FOR SHARE — the shared lock. Many transactions can hold it on the same row at once; all are guaranteed the row will not be updated or deleted meanwhile, but none of them may update it either.
FOR KEY SHARE — the weakest. It blocks only deletes, key-changing updates and FOR UPDATE. The foreign-key machinery takes it implicitly; you rarely request it by hand.
The conflict matrix (Table 13.3 in the Postgres docs) reads as “a transaction requesting the mode down the side must wait if another transaction holds the mode across the top”:
held: KEY SHARE SHARE NO KEY UPDATE UPDATE
requesting:
KEY SHARE ok ok ok WAIT
SHARE ok ok WAIT WAIT
NO KEY UPDATE ok WAIT WAIT WAIT
UPDATE WAIT WAIT WAIT WAIT
Strength is about how much company the lock tolerates. FOR KEY SHARE tolerates everything except FOR UPDATE; FOR UPDATE tolerates nothing. Choosing the weakest mode that is still correct buys concurrency for free.
Your writes already take these locks
The matrix matters even if you never write SELECT ... FOR. A plain UPDATE that does not change key columns takes FOR NO KEY UPDATE on every row it touches. A DELETE, or an UPDATE that changes a key column (one with a unique index usable by a foreign key, such as the primary key), takes FOR UPDATE. Inserting a child row takes FOR KEY SHARE on its parent.
So account.update!(balance: 0) holds FOR NO KEY UPDATE on that row until the transaction commits. These implicit locks enter the same matrix as the ones you request, which is why deadlocks show up in code with no .lock call in it.
How Rails exposes each mode
Active Record maps onto these modes through lock and with_lock; the string you pass becomes the SELECT’s locking clause:
# FOR UPDATE — the default, exclusive
account = Account.lock.find(id)
# FOR NO KEY UPDATE — update non-key columns, allow FK inserts on this row
account = Account.lock("FOR NO KEY UPDATE").find(id)
account.with_lock("FOR NO KEY UPDATE") do
account.update!(balance: account.balance - 50)
end
# FOR SHARE — the row must not change while you work
plan = Plan.lock("FOR SHARE").find(plan_id)
with_lock is the idiom you will reach for most: it opens a transaction, reloads the record under the lock, yields, and releases on commit. Its optional first argument is the locking clause (default FOR UPDATE), available since Rails 3.2; since Rails 7.0 it also accepts transaction options such as requires_new: and isolation:. It raises if the record has unsaved changes rather than discarding them on reload. This is the pessimistic locking covered in the race-conditions and row-locking guide; this article is about choosing the mode.
Active Record’s optimistic locking (lock_version, ActiveRecord::StaleObjectError) is a different mechanism: it adds a version check to the UPDATE’s WHERE clause instead of locking first. Choose it when conflicts are rare and you would rather retry than block.
NOWAIT and SKIP LOCKED
By default a locking SELECT waits for conflicting locks. Two modifiers change that:
# Fail immediately if the row is locked
Account.lock("FOR UPDATE NOWAIT").find(id)
# => raises ActiveRecord::LockWaitTimeout
# Take the next row nobody else holds — inside a transaction, or the lock
# is released the moment the SELECT finishes and two workers can claim it
Job.transaction do
job = Job.where(state: "ready").order(:id).limit(1)
.lock("FOR UPDATE SKIP LOCKED").first
job&.update!(state: "running")
end
NOWAIT errors instead of waiting (SQLSTATE 55P03, which Rails raises as ActiveRecord::LockWaitTimeout). Use it when failing is better than blocking: a request that should answer “this record is being edited”, or a job that would rather reschedule than tie up a worker.
SKIP LOCKED leaves out rows it cannot lock immediately. The docs warn this gives an inconsistent view of the data, so it is wrong for general queries but right for queue tables: each worker claims a different row and nobody waits. Database-backed job queues claim work this way; how Solid Queue works walks through its claim query.
Both apply only to row locks. The table lock the SELECT needs is still acquired normally, so a query can wait behind a migration even with NOWAIT.
Advisory locks: when the thing to lock isn’t a row
Sometimes the critical section has no row to lock: only one worker may generate the next invoice number, and the row that would represent it may not exist yet. Advisory locks lock an integer key that means whatever your application decides.
Use the transaction-scoped variant, which releases when the transaction ends, and bind the key rather than interpolating it:
def with_account_guard(account_id)
Account.transaction do
sql = ActiveRecord::Base.sanitize_sql_array(
["SELECT pg_advisory_xact_lock(?)", account_id]
)
ActiveRecord::Base.connection.select_value(sql) # waits for the key
yield
end
end
A key is one 64-bit integer or two 32-bit integers, and the two key spaces do not overlap. The two-integer form, pg_advisory_xact_lock(int4, int4), namespaces keys: the first names the feature, the second the entity (which must then fit in 32 bits). For a non-blocking attempt, pg_try_advisory_xact_lock returns true or false immediately:
NIGHTLY_SYNC = 2 # one constant per feature, defined in one place
Account.transaction do
sql = ActiveRecord::Base.sanitize_sql_array(
["SELECT pg_try_advisory_xact_lock(?, ?)", NIGHTLY_SYNC, account_id]
)
next unless ActiveRecord::Base.connection.select_value(sql)
run_sync(account_id)
end
The reason to prefer this over a Redis lock is lifecycle. The advisory lock belongs to the same transaction as your work, so a crash or rollback releases both together. A TTL-based Redis lock can block everyone after its holder crashes, or expire while a paused holder still believes it owns it.
Avoid the session-level pg_advisory_lock in pooled code: it survives rollback and stays held until an explicit unlock or the end of the session, and under PgBouncer transaction pooling that session is shared with other clients.
Table locks: migrations take them too
Migrations take table-level locks, and that is where lock modes bite people who never write a locking SELECT.
Every ALTER TABLE ... ADD COLUMN takes ACCESS EXCLUSIVE, the one table lock that also blocks plain SELECTs. Adding a column with no default has always been metadata-only, and since Postgres 11 so is one with a non-volatile default. Those finish almost instantly, but still need the lock. A volatile default such as clock_timestamp(), or a column type change, additionally rewrites the table while holding it. And even a fast change must queue: behind a long-running query, the waiting ALTER TABLE blocks every later query on the table, reads included. Paste a migration into the Rails safe migration checker to see the lock each line takes and a safer rewrite where one exists.
The defence is lock_timeout, so the migration gives up instead of stalling traffic, and you retry it:
class AddArchivedAtToAccounts < ActiveRecord::Migration[8.0]
def change
execute "SET LOCAL lock_timeout = '5s'" # example value
add_column :accounts, :archived_at, :datetime
end
end
For indexes, add_index ..., algorithm: :concurrently (with disable_ddl_transaction!) runs CREATE INDEX CONCURRENTLY, which takes SHARE UPDATE EXCLUSIVE and lets reads and writes continue.
How the wrong mode causes deadlocks
Two transactions deadlock when they acquire conflicting locks on the same rows in opposite orders, and “conflicting” is defined by the matrix above. Picking FOR UPDATE where FOR NO KEY UPDATE would do widens the set of operations you conflict with. If you hold FOR UPDATE on a parent row, another transaction’s child insert waits on you for its FOR KEY SHARE — a contention point that would not exist under FOR NO KEY UPDATE.
So the two levers are complementary: acquire locks in a consistent order, and request the weakest correct mode. Ordering and live diagnosis are covered in fixing ActiveRecord::Deadlocked.
Common mistakes
- Using
.lockfor every lock. For non-key updates,FOR NO KEY UPDATEconflicts with less. - Holding a lock across a slow call. Acquire, write, commit; keep HTTP calls outside the transaction.
- Interpolating advisory-lock keys into SQL. Bind them.
SKIP LOCKEDoutside queue-like tables. It returns an incomplete result by design.- Migrations without
lock_timeout. Even a metadata-onlyADD COLUMNcan stall a busy table while it waits.
Key takeaways
- From strongest to weakest:
FOR UPDATE,FOR NO KEY UPDATE,FOR SHARE,FOR KEY SHARE. OrdinaryUPDATEs takeFOR NO KEY UPDATEimplicitly. .lockandwith_lockdefault toFOR UPDATE; pass a clause to request less.NOWAITfails fast;SKIP LOCKEDis for queues.- Advisory locks serialize work with no row to lock; use the
_xact_form with bound keys. - Every
ADD COLUMNtakesACCESS EXCLUSIVE; setlock_timeout.
FAQ
What is the difference between FOR UPDATE and FOR SHARE in Postgres?
FOR UPDATE is an exclusive row lock: no other transaction can lock, update, or delete the row until you commit. FOR SHARE is shared: other transactions can also hold FOR SHARE, but none can update or delete the row. Neither blocks a plain SELECT.
What does .lock do in Rails?
Calling .lock on a relation issues SELECT ... FOR UPDATE inside the current transaction. with_lock opens a transaction, reloads the record under FOR UPDATE, and yields. Request a weaker mode with .lock('FOR NO KEY UPDATE') or with_lock('FOR NO KEY UPDATE').
When should I use FOR NO KEY UPDATE instead of FOR UPDATE?
When you update only non-key columns. It does not conflict with the FOR KEY SHARE lock that foreign-key checks take on the parent row, so child inserts can proceed. It is also the lock Postgres takes for an UPDATE that leaves key columns unchanged.
What is a Postgres advisory lock and when should I use it in Rails?
An application-defined lock on an integer key, not tied to any row. Use pg_advisory_xact_lock to serialize work with no single row to lock, such as generating a sequential number. It releases automatically on commit or rollback.
Does .lock work outside a transaction?
Without a transaction the lock is released as soon as that single statement finishes, so it protects nothing. Use with_lock, or wrap .lock in a transaction do block.
Conclusion
Postgres locking is a graded set, and Rails hands you the strongest option by default. Reach past it: FOR NO KEY UPDATE when you touch non-key columns, SKIP LOCKED when workers compete for a queue, an advisory lock when the thing to serialize isn’t a row. Match the mode to the work, hold it briefly, and order your acquisitions consistently.