Search code examples
mongodbconcurrencyreplicationreplicaset

Will MongoDb lock read operations on secondary when inserting with write-concern: majority?


The current configuration of MongoDb is:

  • one primary(A), two secondaries(B and C), all part of one replica set
  • inserts to the primary are done with write-concern: majority
  • read preference is set to "nearest" when reading from the replica set

Scenario:

  • an insert is triggered, which means that it will be successful only after it propagates to the majority of the replica set members
  • the application cannot read from the primary until the write operation returns (reference)
  • since the write concern is set to "majority", the write operation will return only after it propagates to at least one secondary (B) instance, in our case with the setup of 3 members
  • this means that the secondary (B) is also locked for reading, as it is replicating (according to this)

The question is, since the application is set to read from the nearest instance, and let's say the nearest instance is the other secondary (C), if a read request comes through while the write operation is still in progress on the other 2 instances, would the read be allowed or blocked. If it will be allowed, how can I prevent it?


Solution

  • if a read request comes through while the write operation is still in progress on the other 2 instances, would the read be allowed or blocked

    Well, you sort of figured it out yourself. You can read (a stale data) from 'C' if it's in the nearest group

    how can I prevent it?

    Read preference can be applied globally by your driver, database level, collection level or operation level (same can be applied more or less for write concern). If for that certain operation you can't suffer stale data, you can override your read preference for that specific query to primary after you had issued the insert (note that in that scenario the insert operation can be set with a write concern of {w:1}