Skip to main content

Server Selection in Mongoose

Server Selection in Mongoose | Rustcode

Understanding Server Selection in Mongoose

When your MongoDB deployment includes a Replica Set or Sharded Cluster, the MongoDB Node.js driver (and by extension, Mongoose) must choose an appropriate server to send operations to. This process is called server selection. Selecting the right server is important for maintaining performance, consistency, and failover handling.


Default Server Selection

By default, Mongoose relies on the MongoDB driver's server selection rules. These rules involve factors like:

  • Server type (primary or secondary).
  • Read preference (where read operations are sent).
  • Topology type (single server, replica set, or sharded cluster).

serverSelectionTimeoutMS

One of the most important options is serverSelectionTimeoutMS. This controls how long the driver will wait when trying to find a suitable server before throwing an error.

mongoose.connect('mongodb://localhost:27017/mydb', {
  serverSelectionTimeoutMS: 5000, // default is 30,000 (30s)
  useNewUrlParser: true,
  useUnifiedTopology: true
});
  

Tip: Lowering this value can make your app fail fast if MongoDB is unavailable, which is useful in APIs and microservices where latency matters.


Factors Influencing Selection

The driver considers:

  • Replica set role (primary vs secondary).
  • Application readPreference (e.g., nearest, primaryPreferred, secondary).
  • Network latency and server availability.

For example, if you specify readPreference: 'secondary', reads will go to secondaries by default, while writes always go to the primary.


Error Handling

If Mongoose cannot connect to any suitable server within the defined serverSelectionTimeoutMS, it throws a MongooseServerSelectionError.

try {
  await mongoose.connect('mongodb://replicaSetUri', {
    serverSelectionTimeoutMS: 3000
  });
} catch (err) {
  console.error('Server selection error:', err);
}
  

Summary Table

Option Purpose Notes
serverSelectionTimeoutMS Max time to wait for a suitable server Default: 30,000 ms (30s)
readPreference Where reads are directed (primary/secondary/nearest) Writes always go to the primary

Best Practices

  • Lower serverSelectionTimeoutMS in latency-sensitive services.
  • Use readPreference strategically for load balancing.
  • Monitor logs for MongooseServerSelectionError to detect failover issues.

Conclusion

Server selection is a critical part of connection management in Mongoose. By tuning serverSelectionTimeoutMS and understanding readPreference, you can make your applications more resilient and performant in replica set and sharded environments.

Comments