Replica Set Read Preferences & MongoDB 2.2

When making the transition from a single server setup to a Replica Set there are many more benefits than just a hot standby. Read preferences are one that should be heavily considered. Benefits vary from reducing system load and/or network throughput on the primary to location based reads that are based on latency from the client. There are several options for configuring read preferences and different reasons why you might choose one over another.

Recent versions MongoDB have included support for sending read operations to the secondary member but with the release of 2.2 three new modes were added. These include primaryPreferred, secondaryPreferred and nearest. As in prior versions these can be applied to per connection, collection or operation.

Read Preference Modes:

primary

The default. Send all read operations to primary even if primary is unavalialbe, thus failing. This would be used when stale results are not a option.

primaryPreferred (NEW)

Similar to the default although when the primary is unavaliable read operations are sent to the secondary. This provides some level of uptime during the transition from secondary -> primary during a failover. Although failovers don’t occur that often one must be prepared.

secondary

Send all read operations to secondary. If secondary is unavailble the operation will fail.

secondaryPreferred (NEW)

Send all read operations to secondary unless secondary is unavailble. When the secondary is unavailable reads are sent to the primary.

nearest

Read operations are sent to the nearst member using the member selection http://docs.mongodb.org/manual/applications/replication/#replica-set-read-preference-behavior-nearest process. Could be used when stale results are acceptable and low latency is a priority.

Driver Examples (Ruby):

per connection

When specifying the read preference in the connection all future objects will inhereit this preference unless specifically set.

db = Mongo::ReplSetConnection.new(['host.m0.mongohq.com:10011','host.m1.mongohq.com:10011'], :read => :secondary_preferred).db("myapp")  

per collection

db = Mongo::ReplSetConnection.new(['host.m0.mongohq.com:10011','host.m1.mongohq.com:10011'], :read => :primary).db("myapp") auth = db.authenticate("user","password") staging = db.collection('staging') staging.find({:customer_name => 'John'}, :read => :secondary_preferred)  

Other driver documentation can be found here: http://api.mongodb.org

As you can see the new modes offer more flexibility to where your reads operation take place. Although most applications perform well without configuring read preference fine tunning for growth may solve future issues.