Saturday, April 14, 2007

ActsAsWithReadonly to support read-only DB slave databases

Update: Released as ActsAsReadonlyable

In his latest post, DHH comments on scaling issues Twitter's team had with their rails application. One of the frequent mentioned problems with ActiveRecord is a weak support of multiple read-only slave databases. We were told by our DBAs some time ago that we needed to think how our rails application would utilize slaves DBs after the official release of our portal . Back then our teammate, Jeffrey Damick, came up with an idea of having an 'acts_as' plugin to support that. We have not yet started using slave DBs but some code has been written. We are releasing it on Rubyforge as soon as the project is approved.

The basic idea behind the plugin is that when an ActiveRecord model is marked with acts_as_with_readonly, most of AR finders are overloaded to run against a slave DB. It allows to do all reads from a read-only farm while saving updates to the read-write DB.

An example of usage:

*** database.yml


production:

database: master_db
host: master-host

read_only:
database: slave_db
host: slave-host


*** Sample Model

class ReadWriteModel < ActiveRecord::Base
acts_as_with_readonly :read_only
end


*** Code

record = ReadWriteModel.find(:first) # against slave_db
record.field = 'new value'
record.save! # against master_db