Zane Claes
Zane Claes

Reputation: 14954

How to properly load-balance with Node.js / Mongoose / MongoDB + ConnectSet?

I'm using Node.js+Express+Mongoose to connect to my MongoDB replica set (3x instances). I was under the impression that when I used Mongoose's "connectSet" command, thereby connecting to the replica set, my queries would be load-balanced between my replica set.

However, using nodetime, I can see that all queries (including find() queries) are going to the PRIMARY instance in the replica set.

Am I misunderstanding something here? Is there some practice I am missing, or a setting in the replica set? I thought the purpose of a replica set was to balance read-only queries with the SECONDARY MongoDB servers in the set...

Thanks.

Upvotes: 3

Views: 2291

Answers (1)

Gates VP
Gates VP

Reputation: 45287

I was under the impression that when I used Mongoose's "connectSet" command, thereby connecting to the replica set, my queries would be load-balanced between my replica set.

This impression is incorrect.

By default, MongoDB reads & writes are sent to the Primary member of a Replica Set. The primary purpose of a Replica Set is to provide high availability (HA). When the primary node goes down, the driver will throw an exception on existing connections and then auto-reconnect to whatever node is elected the new primary.

The idea here being that the driver will find the new primary with no intervention and no configuration changes.

Is there some practice I am missing, or a setting in the replica set?

If you really want to send queries to a secondary you can configure a flag on the query that states "this query can be sent to a secondary". Implementation of this will vary, here's a version for Mongoose.

Please note that sending queries to Secondary nodes is not the default behaviour and there are many pitfalls here. Most implementations of MongoDB are limited by the single write lock, so load-balancing the reads is not necessary. Spreading the reads is not guaranteed to increase performance and it can easily result in dirty reads.

Before undertaking such a load balancing, please be sure that you absolutely need it. Sharding may be a better option.

Upvotes: 5

Related Questions