9

I have a rails 4 app I am hosting on heroku. They give some specific advice about how to manage your DB connection pool when using a multi-threaded server (puma)https://devcenter.heroku.com/articles/concurrency-and-database-connections

When I ran load testing for my app I got an error- can't connect to the db. when each page was being hit, rails initializes active record, even if I'm not making any queries on that page, or referencing any models.

My question is:

How can I make a sort of whitelist (or blacklist) so that active record is not initialized with a db connection for these specific controller actions? In an initializer?

Ideally I would run the cheaper postgres service on heroku (40 connections) because I know my app doesnt use the db very often. If traffic hits higher that the 40 connections things will start to error, which seems silly for an app that wasn't going to use the db on those requests.

I read about how to disable active record for an entire app: Disable ActiveRecord for Rails 4

But how do I selectively enable it? Are there any other different performance considerations here (by not eager loading these things or any other gotchas)

1

1 Answer 1

1

In you application_controller.rb

before_filter :maybe_disconnect_db

def maybe_disconnect_db
  ActiveRecord::Base.remove_connection() if ActiveRecord::Base.connected?
end

def maybe_connect_db
  ActiveRecord::Base.establish_connection() unless ActiveRecord::Base.connected?
end

Then for each controller/action that needs the db connection add

skip_before_filter :maybe_disconnect_db, #only or unless filter here
before_filter      :maybe_connect_db,    #only or unless filter here

This should establish the connection for any specific db request, and disconnect for any request that doesn't need it, while also handling multiple db requests in a row without action, and multiple non db requests in a row without action.

ActiveRecord::Base.remove_connection

ActiveRecord::Base.establish_connection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.