[MongoDB]: Why we need to set rs.slaveOk() while querying on secondaries.

The reason for issuing rs.slaveOk() or db.getMongo().setSlaveOk() command while querying on secondaries. 

We’ve to set “slave okay” mode to let the mongo shell know that we’re allowing reads from a secondary. This is to protect our applications from performing eventually consistent reads by accident.
We can do this in the shell with:

rs.slaveOk()

After that we can query normally from secondaries.

A note about “eventual consistency”: under normal circumstances, replica set secondaries have all the same data as primaries within a second or less.

What is eventual consistency :

A property of a distributed system that allows changes to the system to propagate gradually. In a database system, this means that readable members are not required to reflect the latest writes at all times. In MongoDB, reads to a primary have strict consistency; reads to secondaries have eventual consistency.

Under very high load, data that we’ve written to the primary may take a while to replicate to the secondaries. This is known as “replica lag”, and reading from a lagging secondary is known as an “eventually consistent” read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Please note that we need to only set slaveok when querying from secondaries, and only once per session.

  • Ask Question