Introducing the rails_failover gem

Hi everyone :wave: I’ll like to share that we’ve just released GitHub - discourse/rails_failover which was extracted from GitHub - discourse/discourse: A platform for community discussion. Free, open, simple..

The gem provides automatic failover and fallback for a simple primary/replica database or Redis setup. During the extraction, we also reworked the logic used to leverage the new multiple database APIs added in Rails 6.0. To configure failover support, simply add replica_host and replica_port to your database configuration like so

production:
  host: <primary db server host>
  port: <primary db server port>
  replica_host: <replica db server host>
  replica_port: <replica db server port>

On database connection errors, incoming requests will automatically connect to the replica database server to serve read-only requests. The gem also provide hooks during failover and fallback for managing the application’s state.

RailsFailover::ActiveRecord.on_failover do
  # Enable readonly mode
end

RailsFailover::ActiveRecord.on_fallback do
  # Disable readonly mode
end

For Redis failover support, all you have to do is to pass replica_host, replica_port and a custom connector: RailsFailover::Redis::Connector when creating the Redis connection.

Redis.new(host: "127.0.0.1", port: 6379, replica_host: "127.0.0.1", replica_port: 6380, connector: RailsFailover::Redis::Connector))

Similar hooks are provided during failover as well.

RailsFailover::Redis.on_failover_callback do
  # Switch site to read-only mode
end

RailsFailover::Redis.on_fallback_callback do
  # Switch site out of read-only mode
end

Feel free to let us know if you encounter any issues while using the gem.

Thank you!

14 Likes