Search code examples
mysqlruby-on-railsactiverecordmaster-slave

Handle MySQL Failover(master/slave role switch) with activerecord in rails application


I'm new to Rails and I have built an application connecting to MySQL using activerecord. I've setup read replica of master node. The problem is when my slave becomes master, I get following error in the application:

MySQL server is running with the --read-only option so it cannot execute this statement

which I guess is acceptable.

But my application keeps failing forever and doesn't recover until I restart the application. Is there any acitverecord config or MySQL connection property which I can use to recover from this scenario?

I'm using following config in my database.yml.

adapter: mysql2
encoding: utf8
url: <'DATABASE_URL'>
pool: 10
database: <'DATABASE_NAME'>
username: <'DATABASE_USER'>
password: <'DATABASE_PASS'>
reconnect: true 

Is there any configuration which I can add to handle the failover? Any suggestion to handle the scenario?

Thanks in advance.


Solution

  • I fixed the issue following this blog. Putting it here for reference so that anyone facing the issue can use it.

    As per the blog, you'll override the ActiveRecord::ConnectionAdapters::ConnectionManagement adapter and write your own connection handling in case of errors.