I know that if I create a connection to MongoDB in Java to a replica set using a list of ServerAddresses (using this function) with ReadPreference.SECONDARY
, the client will balance the reads across the replica set, preferring nodes with shorter round-trip times (the same colo, for example).
But when I create a MongoDB client to a bunch of MongoS servers with ReadPreference.SECONDARY
, all reads/writes go to the first server in the list, even when the access is cross-colo and a MongoS exists in the same colo.
For example, if I have three MongoS servers - SF1, SF2, and NYC1 (in that order) - my clients only talk to SF1, regardless of whether they're in SF or NYC.
Is there something I have to configure or a different way to set up the client when talking to MongoS servers? What am I missing?
This is unintentional behavior in the driver. The driver code is not detecting that you're passing a list of mongos servers, and is treating them as a replica set. ReadPreference.SECONDARY will send queries to a primary if no secondaries are detected, and that's what's happening here: the first "primary" it detects is the first mongos server in the list. None of the mongos servers identify as secondary, so they are ignored.
So currently the only way to load balance across multiple mongos servers is to create an instance of Mongo for each one, and handle the distribution of queries to each one in application code.
Also note that the next release of the Java driver will contain a fix for https://jira.mongodb.org/browse/JAVA-381, which adds support for mongos failover (though not load balancing as yet)