Client not reading from Mongo secondary database

Posted on

Question :

I’ve implemented a replica set that I’m using globally. I have my master in Oregon, US and 4 secondaries. California and Virginia, Frankfurt and Sydney. I also have web servers in those same regions as well. Those web servers connect to mongo using mongoose:

var mongoose = require("mongoose");
var dbUrl = "mongodb://***.***.***.***:27017,***.***.***.***:27017,***.***.***.***:27017,***.***.***.***:27017,***.***.***.***:27017/exampleDb";
var dbOptions : {
   "replSet": {
      "rs_name": "exampleRepSet",
      "readPreference": "ReadPreference.SECONDARY_PREFERRED",
      "read_preference": "ReadPreference.SECONDARY_PREFERRED",
      "w":0,
      "slaveOk": true
    }
}
mongoose.connect(dbUrl, dbOptions);

My problem is that my client’s have higher latency to the database depending on how far away they are from the master. California get 40ms while Sydney gets 400ms. I don’t understand why this is happening since they should be reading off of the secondary database in their region.

I understand that writes must be done to the primary but even if I perform a find then shouldn’t it be done on the regional secondary and return pretty quick?

I realize there are some redundant options in that config but I’m getting desperate. I’ve also tried the option "ReadPreference.NEAREST" to no avail.

Answer :

Using “ReadPreference.SECONDARY_PREFERRED” does not provide any such guarantee to read from a node in the same region.

I’m not familiar with Mongoose but the first thing I would do is prove this via the Mongo shell first. Second I would remove the redundancy you acknowledged above. If it shouldn’t be there, get rid of it. Via the shell; try using a read preference of “secondaryPreferred” but really what I think you want is “nearest” which will read from a node with the least network latency.
Again; I cannot speak towards Mongoose specifically but there are some non Mongoose related to resolve first per what you shared.

The best this will do is confirm for you if you have a Mongoose issue or not.

Also; using a WriteConcern of 0 and reading from Secondary nodes is not a terrific practice if you rely on the data being on the secondary. If you are okay with the eventual consistency, then a write concern of 0 and reading from secondaries is fine.

Leave a Reply

Your email address will not be published. Required fields are marked *