Question

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?

Was it helpful?

Solution 2

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}

OTHER TIPS

Write concern doesn't really work that way. B and C will both process the write, and take the same db-level write lock while they do it, regardless of whether you send a getLastError with any write concern. While the lock is held on C, reads on C will block.

Write concern is really just for the client, it makes the client wait until a condition (in your case, a majority of the replicas have applied the write) is satisfied. It doesn't change how the secondaries prioritize the replication.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top