Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heroku Rails - Turn off Active Record Postgres connection

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)

like image 634
awongh Avatar asked Jun 05 '17 11:06

awongh


1 Answers

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

like image 176
Michael Gorman Avatar answered Nov 20 '22 14:11

Michael Gorman