Thursday, October 31, 2013

MongoDB replication


Replication is for non-other than making several copies of data for future/other references.
This may be used for backup, reporting, recovery.
MongoDB no exceptions replication can be used for any of the above cases.

Secondary will replicate its oplog and execute changes on data sets.
So secondary will reflect primary’s data.
Clients can either configure to read from secondary or can read from primary
In case of configured following will check,

primary                  This is the default. All operations read from the current replica set primary.
primaryPreferred   Mostly operations read from the primary but if it is unavailable, operations read from secondary members.
secondary              All operations read from the secondary members of the replica set.
secondaryPreferred         Mostly operations read from secondary members but if no secondary members are available, operations read from the primary.
nearest                  Read from the nearest member of the replica set, irrespective of the member’s type

Member selection in case primary disconnect, step down and in the initialization of replica set is as below,
First list suitable list of available servers (primary, secondary or all members). Then check which the absolute is nearest.

secondaryAcceptableLatencyMS can be used to override.

Default acceptable latency is 15 milliseconds (It will ping and check).

For mongos - localThreshold or localThreshold runtime option to change the value.

Once above criteria is met randomly choose which can be used for read operation.

Read association - which is something to think about as your secondary may lag, which will result with different results on same queries. So you can use this as it’s provide you below functionality,
Application may associate with specific server so the results will be consistence. But until,
Application may read with different read preference, thread terminates or socket exception.

If you are interested enough its quite easy to setup a replica set.

port = 47017
bind_ip = localhost
dbpath = D:\mongodb\mongodb-win32-x86_64-2008plus-2.4.7-3\data
replSet = rs0
rest = true




These are the basic configs. Make sure to change port, dbpath accordingly (at least). Enabling rest is important as you can use the built-in admin to view the status.

Then log into one mongodb and execute below.

rs.initiate();
rs.add(“server1:port”);
rs.addArb(“server2:port”);
rs.status();




below will useful in case try to read from secondary

rs.slaveOk