PG::TRDeadlockDetected: ERROR: deadlock detected PG::TRDeadlockDetected: ERROR: deadlock detected ruby-on-rails ruby-on-rails

PG::TRDeadlockDetected: ERROR: deadlock detected


I might have found a solution to my question: I had some queries outside of my controllers (custom middleware), which seem to have caused the problem.

If you have queries outside of controllers (ActiveMailer could also cause this problem), put your code in a ActiveRecord::Base.connection_pool.with_connection block:

ActiveRecord::Base.connection_pool.with_connection do  # codeend

ActiveRecord’s with_connection method yields a database connection from its pool to the block. When the block finishes, the connection is automatically checked back into the pool, avoiding connection leaks.

I hope this helps some of you!


Looks like this may be due to the database connections not getting closed on server shutdown. https://github.com/puma/puma/issues/59 A lot of people in that issue are using ActiveRecord:: ConnectionAdapters::ConnectionManagement to handle this, or you may be able to roll your own by using Puma's on_restart hook.