ruby-on-railsactiverecordruby-on-rails-6unicornruby-on-rails-6.1

How to ensure unicorn disconnects ALL DB connections in rails 6.1?


In unicorn.rb it's common to have clauses like this:

before_fork do |server, worker|
  # Disconnect since the database connection will not carry over
  if defined? ActiveRecord::Base
    ActiveRecord::Base.clear_all_connections!
  end
end

To ensure db connections are closed when reloading the app. Since the introduction of "roles" and "shards" in Rails I am unsure how I would make sure that ALL connections/pools are disconnected, not only the "current role" one?


Solution

  • Ok, so I think I found it...

    before_fork do |server, worker|
      # Disconnect since the database connection will not carry over
      if defined? ActiveRecord::Base
        ActiveRecord::Base.connection_handlers.each do |role, handler|
          Rails.logger.info("Clearing/closing all connections for #{role} role...")
          handler.clear_all_connections!
        end
      end
    end