Ruby Sequel multiple database issues

123 Views Asked by At

I have a rails application (with puma) and few postgresql databases. As a DB driver gem Sequel is used. Here is the code for multiple DB connections when application starting:

require "sequel"

module MyApp
  class Databases
   class << self
     attr_accessor :first_db, :second_db

     def start_connections
       @first_db = Sequel.connect(ENV.fetch("FIRST_DB_CREDENTIONALS"))
       @second_db = Sequel.connect(ENV.fetch("SECOND_DB_CREDENTIONALS"))
     end

     def disconnect_all
       first_db.disconnect
       second_db.disconnect
     end
   end
  end
end

MyApp::Databases.start_connections

But, from time to time, some requests (which fetches records from first or second DB) to application fails with error: "PG::ConnectionBad: PQconsumeInput() server closed the connection unexpectedly. This probably means the server terminated abnormally before or while processing the request: ..."

How to fix this error? Is there a problem with connection timeout settings or what?

After lookup at documentation, I found this moment and add following code to my puma config:

before_fork do
  MyApp::Databases.disconnect_all
end

But problem still persists. Also tried to close connection manually on end of each request, but the error, mentioned above, raises from time to time.

0

There are 0 best solutions below