Reputation: 12252
We have a master and a slave PostgreSQL databases. For read-only intensive parts (reporting) of the application, we use ActiveRecord::Base.establish_connection(:slave)
in a before_action
controller block to direct request's queries to the slave.
After moving to this setup yesterday, we got a completely new error ActiveRecord::StatementInvalid (PG::ReadOnlySqlTransaction: ERROR: cannot execute SELECT FOR UPDATE in a read-only transaction...
This got us thinking. We are using Phusion Passenger 4.0.45 as the application server. Does the same Ruby/Rails instance re-use connection pools with Passenger?
In other words, if in one of the instances establish_connection(:slave)
gets called, is it possible that this same instance serves another request where establish_connection(:slave)
isn't explicitly called, but still uses the slave because of connection pool re-using or some other form of database connection caching?
Is there a way to avoid this?
Upvotes: 0
Views: 1125
Reputation: 18934
Yes, a Rails process reuses connections instantiated inside the same process. This is a Rails feature, not a Passenger feature. See ActiveRecord::ConnectionAdapters::ConnectionPool for more information.
To solve this, try using a master-slave database gem like octopus.
Upvotes: 1