PostgreSQL master-slave replication on Heroku with Ruby on Rails

PostgreSQL master-slave replication on Heroku with Ruby on Rails and Octopus gem

Master-slave replication

Octopus gem

gem 'ar-octopus'
octopus:
replicated: true
fully_replicated: true
production:
slave:
adapter: postgresql
host: localhost
database: slave_db

How to configure it on Heroku

$ heroku addons:create heroku-postgresql:standard-0 --follow HEROKU_POSTGRESQL_CHARCOAL_URLAdding heroku-postgresql:standard-0 to sushi... done, v71 ($50/mo)
Attached as HEROKU_POSTGRESQL_WHITE
Follower will become available for read-only queries when up-to-date
Use `heroku pg:wait` to track status
$ heroku pg:wait
Waiting for database HEROKU_POSTGRESQL_WHITE_URL... available
<%
def slave_db_uri
@cached_slave_db_uri ||=
begin
slave_db_env_key = 'HEROKU_POSTGRESQL_WHITE_URL'
if slave_db_env_key.present? && ENV[slave_db_env_key]
URI.parse(ENV[slave_db_env_key])
end
end
end
%>
octopus:
replicated: true
fully_replicated: true
production:
slave:
adapter: postgresql
database: <%= (slave_db_uri.path || "").split("/")[1] %>
username: <%= slave_db_uri.user %>
password: "<%= slave_db_uri.password %>"
host: <%= slave_db_uri.host %>
port: <%= slave_db_uri.port %>

Summary

  • read query will be send to a slave database (WHITE): User.where(name: 'John')
  • write query will be send to a master database (CHARCOAL): User.create(name: 'Molly')
  • copying data between databases has been set up by Heroku and you don’t have to worry about that :)

--

--

Dev and life blog. Thoughts about programming, design patterns, Ruby and life.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store