Rails: ActiveRecord::Deadlocked: PG::TRDeadlockDetected: ERROR: deadlock detected
Two transactions locked rows in opposite orders, so PostgreSQL aborted one.
ActiveRecord::Deadlocked: PG::TRDeadlockDetected: ERROR: deadlock detectedMysql2::Error: Deadlock found when trying to get lock; try restarting transactionActiveRecord::Deadlocked: Mysql2::Errordeadlock detected DETAIL: Process 123 waits for ShareLock on transaction Meaning
Keep transactions short, update rows in a consistent order (sort ids before update), use lock! consistently, avoid mixing row locks and table scans, and retry on ActiveRecord::Deadlocked (Rails 5.2+ raises it for MySQL/PostgreSQL). Background jobs that update the same rows concurrently are typical.
Common causes
- Concurrent jobs updating rows in different orders
- Long transactions
update_all/bulk updates overlapping- Foreign key locks (parent/child updates)
- Unordered
IN (...)updates
⚡ Quick fix
- Sort ids and lock in a consistent order
- Shorten transactions
- Rescue
ActiveRecord::Deadlockedand retry
Detailed fix by platform
Rails
Order.where(id: ids.sort).order(:id).lock.each { |o| o.update!(...) }
How to diagnose
- Order — Consistent?
- Duration — Short?
- Retry — Handled?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- A server is already running. Check /tmp/pids/server.pid Rails: A server is already running (pid: 12345, file: /app/tmp/pids/server.pid). Exiting
- AbstractController::DoubleRenderError Rails: AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action)
- ActionController::InvalidAuthenticityToken Rails: ActionController::InvalidAuthenticityToken (Can't verify CSRF token authenticity)
Most viewed in Ruby / Rails
- ActiveRecord::PendingMigrationError Rails: ActiveRecord::PendingMigrationError — Migrations are pending. To resolve this issue, run: bin/rails db:migrate
- undefined method for nil Ruby: NoMethodError: undefined method `x' for nil (nil:NilClass)
- Bundler could not find compatible versions for gem Bundler: Bundler could not find compatible versions for gem "activesupport": In Gemfile: rails (= 7.1.0) depends on activesupport (= 7.1.0)
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 5 Nov 2026