Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in AWS by (19.1k points)

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 the service with a single endpoint that points to the current master.

Whenever there's a database failover, Active Record will continue to try to connect to the same server, instead of retrying the connection in order to pick up the new IP for the master.

Is there a way to create a "global" rescue for the ActiveRecord::StatementInvalid: PG::ConnectionBad: PQsocket() can't get socket descriptor error that simply runs ActiveRecord::Base.connection_pool.disconnect! that will make the next query to work?

1 Answer

0 votes
by (44.4k points)

Using a monkey patch to postgres_adapter, I was able to reconnect the Active Record.


require 'active_record/connection_adapters/postgresql_adapter'


class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter


  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')



    raise e



Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

Browse Categories