Rails Database Deadlocks: Detect, Prevent, and Recover in Production
Rails database deadlocks: detect PostgreSQL deadlocks in production, fix lock-ordering bugs, add retry logic, and keep background jobs safe.
It was a Thursday morning and both payment processing jobs had been hanging for eleven minutes. No exception in Sentry, no timeout logged, just two Sidekiq workers stuck at database level with the CPU pegged. When I ran SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock', I found them: two transactions, each waiting on a row lock the other held, neither ever going to move again.
That was the first production deadlock I could not dismiss as a fluke. It had been in the codebase for months, a latent bug that only manifested when two jobs processed overlapping order batches at exactly the right moment. Nineteen years of Rails, and deadlocks still have a way of hiding in perfectly reasonable-looking code until the conditions align.
This post is what I wish I had read before that morning: how to find deadlocks in Postgres, understand why they happen in Rails applications, and fix them systematically.
What a Rails Database Deadlock Actually Is
A deadlock is two (or more) transactions each holding a lock and waiting for a lock the other holds. Postgres detects this automatically with a background process that checks for cycles in the lock-wait graph. When it finds one, it picks a “victim” transaction and kills it with error code 40P01:
ERROR: deadlock detected
DETAIL: Process 12345 waits for ShareLock on transaction 67890; blocked by process 11111.
Process 11111 waits for ShareLock on transaction 67890; blocked by process 12345.
HINT: See server log for query details.
In Rails, this surfaces as ActiveRecord::Deadlocked, a subclass of ActiveRecord::StatementInvalid. Without handling it, the exception propagates up, rolls back the transaction, and fails the request or job.
Deadlocks are distinct from lock timeouts — a lock timeout (statement_timeout or lock_timeout) means a single transaction waited too long for a lock and gave up. A deadlock means two transactions are mutually blocking each other and neither can proceed regardless of how long they wait. The Rails timeouts post covers lock timeouts in depth; this post focuses on the deadlock case.
Detecting Deadlocks in Production
PostgreSQL Logging
Before you can fix deadlocks, you need to see them. By default, Postgres logs deadlocks, but you need to confirm your config:
-- Check current settings
SHOW log_min_messages;
SHOW deadlock_timeout;
The deadlock_timeout setting (default: 1 second) controls how long Postgres waits before checking for a deadlock cycle. It is not how long transactions wait before being killed — it is the detection interval. A shorter deadlock_timeout means faster detection at the cost of slightly more lock-check overhead.
Configure it in postgresql.conf:
deadlock_timeout = 1s # default; fine for most apps
log_min_messages = warning # deadlocks log at ERROR, so this captures them
log_lock_waits = on # also log slow lock acquisitions (> deadlock_timeout)
With log_lock_waits = on, you get a heads-up when a transaction is waiting on a lock — often useful for diagnosing slow queries that are not quite deadlocks yet.
In a Rails app deployed with Kamal or Docker, inject these via environment variables in DATABASE_URL or via a custom postgresql.conf:
# config/database.yml
production:
url: <%= ENV["DATABASE_URL"] %>
variables:
deadlock_timeout: "1s"
lock_timeout: "5s"
Finding Deadlocks in Application Logs
Wire a subscriber to ActiveRecord::Deadlocked so you have visibility in your app logs and error tracker:
# config/initializers/deadlock_monitoring.rb
ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|
next unless payload[:exception]&.first == "ActiveRecord::Deadlocked"
Rails.logger.error(
"DEADLOCK detected",
sql: payload[:sql].truncate(500),
binds: payload[:binds]&.map(&:value),
caller: caller_locations(0, 20).map(&:to_s)
)
end
For Sentry, deadlocks are automatically captured if you rescue and re-raise, or if the exception propagates to the top-level handler. Tag them explicitly so you can filter:
Sentry.configure_scope do |scope|
scope.set_tag("error.type", "deadlock")
end if exception.is_a?(ActiveRecord::Deadlocked)
Reading pg_stat_activity During a Live Deadlock
When a deadlock is happening right now, this query shows the blocked transactions:
SELECT
pid,
now() - pg_stat_activity.query_start AS duration,
query,
state,
wait_event_type,
wait_event,
pg_blocking_pids(pid) AS blocked_by
FROM pg_stat_activity
WHERE wait_event_type = 'Lock'
ORDER BY duration DESC;
The pg_blocking_pids function returns the PIDs holding the locks that the current process is waiting for. Cross-reference those PIDs with their own rows to see the full lock cycle.
Common Rails Deadlock Patterns
Understanding why deadlocks happen in Rails is 80% of fixing them. These are the patterns I see in the wild.
Pattern 1: Lock Ordering Violations
The most common root cause. Two code paths acquire locks on the same rows, but in different orders.
# In OrderProcessor
def process_payment(order_id, user_id)
ActiveRecord::Base.transaction do
order = Order.lock.find(order_id) # Lock order first
user = User.lock.find(user_id) # Then user
# ...
end
end
# In NotificationService (called from a different job)
def send_confirmation(user_id, order_id)
ActiveRecord::Base.transaction do
user = User.lock.find(user_id) # Lock user first
order = Order.lock.find(order_id) # Then order — opposite order!
# ...
end
end
If OrderProcessor and NotificationService run concurrently for the same (user_id, order_id) pair, you get a deadlock: each transaction holds one lock and waits for the other.
The fix is a canonical lock ordering: always acquire locks on multiple tables in the same order across all code paths. Establish the convention at the application level:
# Lock in table-name alphabetical order: orders before users
def process_payment(order_id, user_id)
ActiveRecord::Base.transaction do
order = Order.lock.find(order_id)
user = User.lock.find(user_id)
# ...
end
end
def send_confirmation(user_id, order_id)
ActiveRecord::Base.transaction do
# Flip to match canonical order
order = Order.lock.find(order_id)
user = User.lock.find(user_id)
# ...
end
end
For locking multiple rows of the same model, sort by primary key:
# WRONG: each job processes its own list in arbitrary order
items = LineItem.where(id: item_ids).lock
# CORRECT: canonical ordering prevents deadlock between concurrent jobs
items = LineItem.where(id: item_ids).order(:id).lock
This is the single most effective deadlock prevention technique. Enforce it in code review.
Pattern 2: Implicit Locks from Foreign Key Cascades
Postgres acquires a share lock on the parent row when you insert or update a row with a foreign key, to validate the FK constraint. This is usually invisible but becomes a deadlock source when combined with explicit row locks.
# Transaction A: explicitly locks the parent account
account = Account.lock.find(account_id)
account.update!(balance_cents: new_balance)
# Transaction B (concurrent): inserts a child record with FK to account
# Postgres implicitly locks the account row to validate the FK
Payment.create!(account_id: account_id, amount_cents: 100)
If Transaction A holds a row lock on the account while Transaction B waits for it, and Transaction B holds some other lock that Transaction A needs, you have a deadlock.
Mitigation: minimize the duration of explicit row locks. Take the lock as late as possible in the transaction and release it quickly:
# Less likely to deadlock: lock only when writing, not for the whole transaction
ActiveRecord::Base.transaction do
# Do reads without locks
account = Account.find(account_id)
new_balance = account.balance_cents + payment.amount_cents
# Lock only when updating
account.lock! # SELECT FOR UPDATE on the specific record
account.update_column(:balance_cents, new_balance)
end
Pattern 3: Concurrent Background Jobs Processing Overlapping Sets
This is the deadlock pattern I see most often in production. Two Sidekiq or Solid Queue workers each process a batch of records, with batches that overlap:
class ReconciliationJob < ApplicationJob
def perform(account_ids)
Account.transaction do
# Each job locks its own list; if lists overlap, deadlock is possible
accounts = Account.where(id: account_ids).lock.to_a
# ... process accounts
end
end
end
If Job A processes accounts [1, 3, 5] and Job B processes accounts [3, 5, 7], and Job A has locked account 3 while Job B has locked account 5, they will deadlock waiting for each other’s locks.
The first line of defense is ensuring batch ranges do not overlap — use deterministic sharding in the enqueuing logic. The second is lock ordering (sort by ID). The third is advisory locks as a mutex around the whole batch:
class ReconciliationJob < ApplicationJob
def perform(batch_key, account_ids)
# Advisory lock ensures at most one job runs per batch_key
ApplicationRecord.with_advisory_lock("reconciliation_#{batch_key}") do
Account.transaction do
accounts = Account.where(id: account_ids.sort).lock.to_a
# ...
end
end
end
end
Pattern 4: update_all on Overlapping Ranges
update_all acquires row locks during execution and processes rows in an internal order that you do not control. Two concurrent update_all calls on overlapping row sets are a deadlock waiting to happen:
# Two jobs running simultaneously:
# Job A: Order.where(status: :pending, region: "eu").update_all(status: :processing)
# Job B: Order.where(status: :pending, assigned_to: worker_id).update_all(status: :locked)
# These can share rows and deadlock.
Replace with an explicit ordered lock when you need to update overlapping sets:
def update_orders_safely(scope)
ids = scope.order(:id).pluck(:id)
Order.where(id: ids).lock.each do |order|
order.update!(status: :processing)
end
end
This is slower than update_all on large sets, but correct. For high-volume updates, use INSERT ... ON CONFLICT patterns or partition the update into non-overlapping shards.
Retry with Exponential Backoff
Even with correct lock ordering, deadlocks can occur under unusual concurrency conditions. The retry pattern is your safety net — Postgres has already rolled back the failed transaction, so a retry is always safe:
# app/concerns/deadlock_retryable.rb
module DeadlockRetryable
MAX_RETRIES = 3
BASE_DELAY = 0.05 # 50ms
JITTER_RANGE = 0.02 # ±20ms
def with_deadlock_retry(retries: MAX_RETRIES, &block)
attempt = 0
begin
yield
rescue ActiveRecord::Deadlocked => e
attempt += 1
raise if attempt >= retries
delay = BASE_DELAY * (2**attempt) + rand(-JITTER_RANGE..JITTER_RANGE)
Rails.logger.warn("Deadlock on attempt #{attempt}, retrying in #{delay.round(3)}s")
sleep(delay)
retry
end
end
end
Usage:
class PaymentService
include DeadlockRetryable
def process(order_id)
with_deadlock_retry do
ActiveRecord::Base.transaction do
order = Order.lock.order(:id).find(order_id)
# ... process
end
end
end
end
The jitter prevents “thundering herd” behaviour where multiple retried transactions all hit the database at the same moment and immediately deadlock again.
For background jobs, Rails’s built-in retry mechanism handles this cleanly:
class PaymentProcessingJob < ApplicationJob
retry_on ActiveRecord::Deadlocked, wait: :polynomially_longer, attempts: 5
def perform(order_id)
ActiveRecord::Base.transaction do
order = Order.lock.find(order_id)
# ...
end
end
end
polynomially_longer uses Solid Queue’s or Sidekiq’s built-in backoff formula. A deadlocked job is rescheduled, not lost. This is the most important layer of safety for jobs — the application code stays simple, and the retry semantics are correct.
Do not use retry_on ActiveRecord::StatementInvalid — that is too broad. ActiveRecord::Deadlocked is the specific subclass you want. StatementInvalid also covers syntax errors and type errors; retrying those is never correct.
Optimistic Locking as a Deadlock Avoidance Strategy
For update-heavy models where concurrent modifications are common, optimistic locking eliminates the need for SELECT FOR UPDATE locks entirely:
# db/migrate/20261124000001_add_lock_version_to_accounts.rb
add_column :accounts, :lock_version, :integer, default: 0, null: false
# app/models/account.rb
class Account < ApplicationRecord
# lock_version column enables optimistic locking automatically
end
With optimistic locking, concurrent transactions proceed without taking row locks. At commit time, Rails checks that lock_version has not changed since the record was read. If it has, ActiveRecord::StaleObjectError is raised and you retry:
def credit_account(account_id, amount_cents)
retries = 0
begin
account = Account.find(account_id)
account.increment!(:balance_cents, amount_cents)
rescue ActiveRecord::StaleObjectError
retries += 1
retry if retries < 3
raise
end
end
Optimistic locking is the right choice when most concurrent transactions do not actually conflict. It is the wrong choice when conflict is frequent — StaleObjectError retries under high contention can cause more load than a well-ordered pessimistic lock strategy. For payment processing and financial ledgers, pessimistic locking with correct lock ordering is usually safer. For user profile updates and content editing, optimistic locking is the natural fit.
Deadlocks Inside Migrations
One deadlock source developers overlook is database migrations. ALTER TABLE requires an exclusive lock on the entire table. If a long-running transaction (a background job, a slow API request) is in progress when a migration runs, the migration blocks. And if other requests then queue behind the migration’s lock wait, you can get a deadlock between the migration’s lock attempt and an in-progress transaction that itself needs to wait for a lock.
The strong_migrations gem catches the most dangerous migration patterns. For large tables, follow the zero-downtime migration approach:
# Safe: add column without constraints first, backfill separately
class AddPriorityToOrders < ActiveRecord::Migration[8.0]
def change
add_column :orders, :priority, :integer # Fast, no lock held long
# Backfill in a separate migration or background job
end
end
For the full zero-downtime migration strategy, see the database migrations post.
Production Alerting: When to Page Yourself
A single deadlock that retries successfully is not worth waking anyone up. A burst of deadlocks is a signal that something structural is wrong — a new code path with a lock-ordering bug, a background job that just started running concurrently, or a schema change that added a FK cascade.
Track the deadlock rate and alert on anomalies:
# config/initializers/deadlock_monitoring.rb
DEADLOCK_THRESHOLD = 5 # deadlocks per minute before alerting
$deadlock_counter = Concurrent::AtomicFixnum.new(0)
ActiveSupport::Notifications.subscribe("deadlock.application") do
count = $deadlock_counter.increment
if count == DEADLOCK_THRESHOLD
# Alert through your preferred channel
PagerDuty.trigger("Deadlock rate exceeded #{DEADLOCK_THRESHOLD}/min")
end
end
# Reset counter every minute
Thread.new do
loop do
sleep 60
$deadlock_counter.value = 0
end
end
For teams using StatsD or Prometheus, emit a counter on each ActiveRecord::Deadlocked and configure alerting in your dashboard. The key threshold is not absolute count but rate change — a sudden spike in deadlocks means code shipped with a lock-ordering bug.
Deadlock Diagnostic Checklist
When you find a new deadlock, work through this in order:
- Get the full Postgres log entry — it names the two queries and the rows involved.
DETAILin the error tells you exactly which transactions conflicted. - Identify which code paths generated those queries — trace from the SQL back to the Ruby. Query params in the log plus
pg_stat_activityhistory help. - Check the lock acquisition order — do the two paths acquire locks on the same tables and rows? In what order?
- Look for FK constraints — does either table have a FK to a table locked by the other path? Implicit FK share locks are invisible in the code.
- Fix lock ordering or introduce advisory locks — sort lock acquisitions into a canonical order across all code paths touching those tables.
- Add retry with backoff — as a safety net, even after fixing the root cause.
- Write a regression test — use
threadsin Minitest or RSpec to verify the concurrent scenario no longer deadlocks.
# test/models/account_test.rb
test "concurrent balance updates do not deadlock" do
account = accounts(:main)
errors = []
threads = Array.new(5) do |i|
Thread.new do
PaymentService.new.process_credit(account.id, 100 * (i + 1))
rescue ActiveRecord::Deadlocked => e
errors << e
end
end
threads.each(&:join)
assert_empty errors, "Expected no deadlocks: #{errors.map(&:message)}"
assert_equal 1_500, account.reload.balance_cents
end
This kind of test is slow and occasionally flaky, so tag it appropriately and exclude from the default run. But it catches a category of regression that normal unit tests cannot.
FAQ
How do Rails database deadlocks differ from lock timeouts?
A lock timeout (ActiveRecord::LockWaitTimeout) happens when a single transaction waits longer than your configured lock_timeout for a lock held by another transaction. The other transaction may eventually release the lock — your transaction just gave up before that happened. A deadlock is a circular dependency: Transaction A holds Lock X and waits for Lock Y, while Transaction B holds Lock Y and waits for Lock X. Neither can ever proceed. Postgres detects the cycle and kills one transaction immediately; there is no timeout to tune. In practice, deadlocks are always programming bugs (wrong lock ordering or missing retry). Lock timeouts may also indicate bugs or simply undersized timeouts.
Can I prevent all Rails database deadlocks?
You can prevent the common patterns, but you cannot guarantee complete elimination at the application layer. The root-cause fix is consistent lock ordering and minimal lock duration. The safety net is retry logic on ActiveRecord::Deadlocked. Together, these make deadlocks either impossible (ordering eliminates the cycle) or harmless (retry recovers from the rare one that slips through). The goal is not zero deadlocks in the logs — it is zero user-visible failures and no structural deadlock bugs shipping to production.
Should I use optimistic or pessimistic locking to avoid Rails deadlocks?
Use pessimistic locking (SELECT FOR UPDATE) when you need to guarantee exclusive access during the entire transaction — financial ledgers, inventory counters, any state machine that must not allow concurrent transitions. Use optimistic locking (lock_version) when most operations on a record are non-conflicting and you can tolerate occasional retries on stale reads. Optimistic locking eliminates row locks and therefore cannot deadlock, but it fails loudly under high contention and requires client-side retry handling. For payment processing and concurrent job pipelines, pessimistic locking with correct lock ordering is the safer default.
How do I find which queries caused a deadlock in production?
Enable log_lock_waits = on and log_min_duration_statement = 0 (temporarily, in production, with care) to log every statement with its duration. After a deadlock, the Postgres log will contain the two conflicting queries within the deadlock error’s DETAIL block. For ongoing diagnosis without flooding logs, query pg_locks joined to pg_stat_activity to see current lock state. The pg_stat_statements post covers setting up per-query statistics that can reveal lock-contention patterns over time.
Deadlocks are one of those production problems that look terrifying the first time and are almost always fixable in an afternoon once you understand the lock ordering. TTB Software has untangled concurrent processing bugs in Rails apps for nineteen years — from payment pipelines to inventory systems. If your app is seeing deadlocks under load, we know exactly where to look.
Related Articles
Rails LLM Semantic Cache: Cut AI API Costs with pgvector Similarity Matching
Rails LLM semantic cache with pgvector: cache AI responses by query similarity, cut OpenAI/Claude costs 40-60%, with ...
Rails PDF Generation: Prawn, Grover, and HTML-to-PDF in Production
Rails PDF generation with Prawn, Grover, and HTML-to-PDF via headless Chrome — when to use each, production setup, ba...
Rails ActiveSupport::Notifications: Custom Instrumentation for Metrics and Production Monitoring
Rails ActiveSupport::Notifications powers custom instrumentation, metrics, and APM integration. Subscribe to events, ...