I read on Heroku that for Rails (4+ they say) I should add the following directive to Puma, when I use multiple workers and I preload the app:
on_worker_boot do
ActiveRecord::Base.establish_connection
end
However I have both preload_app!
and multiple workers
without that code... and the app seems to work fine.
Am I missing something? Is that still required? What is the purpose?
This establish_connection
call is no longer needed, assuming you're running Rails 5.2+.
The config code for the Puma-maintained plugin for best practices Puma configuration on Heroku (it lives here) currently includes the following:
# Not necessary in Rails 5.2+, see https://github.com/rails/rails/pull/29807
if defined?(::ActiveRecord) && defined?(::ActiveRecord::Base) && Gem::Version.new(Rails.version) < Gem::Version.new('5.2.0')
c.before_fork { ActiveRecord::Base.connection_pool.disconnect! }
c.on_worker_boot { ActiveRecord::Base.establish_connection }
end
Note the comment here. A little more digging on the linked PR and some PRs it linked me to led to the PR that actually removes the need for this stuff: https://github.com/rails/rails/pull/31241. In this PR, the question is explicitly asked,
Does this mean that if we have existing before_fork and on_worker_boot blocks in our pre-Rails 5.2.0 puma.rb file, we can now simply remove those blocks after upgrading to Rails 5.2.0?
And the answer, my friend, is...
Yes. (Assuming they're doing AR connection management, of course.) They're perfectly safe to leave there, so it's not called out in the upgrade guide, but they should no longer be necessary.