Rails Postgres Reconnect with Failover for RDS

I have a Rails application with a Postgres database under AWS RDS with multi-az architecture. The HA architecture used by RDS is master / slave, and they provide a single endpoint service that points to the current master.

Whenever a switch to another database resource occurs, Active Record will continue to try to connect to the same server, instead of repeating the connection to obtain a new IP address for the wizard.

Is there a way to create a "global" salvation for an ActiveRecord::StatementInvalid: PG::ConnectionBad: PQsocket() can't get socket descriptor that just runs ActiveRecord::Base.connection_pool.disconnect! Which will make the following request work?

+7
ruby-on-rails activerecord postgresql amazon-web-services amazon-rds
source share
1 answer

I was able to activate Active Record after the failover event by applying the monkey patch to postgres_adapter .

lib/core_ext/active_record/postgresql_adapter.rb :

 require 'active_record/connection_adapters/postgresql_adapter' class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter private def exec_no_cache(sql, name, binds) log(sql, name, binds) { @connection.async_exec(sql, []) } rescue ActiveRecord::StatementInvalid => e if e.to_s.include?('PG::ConnectionBad') ActiveRecord::Base.connection_pool.disconnect! end raise e end end 
+2
source share

All Articles