Skip to main content

serverSelectionTimeoutMS in Mongoose

serverSelectionTimeoutMS in Mongoose | Rustcode

serverSelectionTimeoutMS in Mongoose

The serverSelectionTimeoutMS option in Mongoose controls how long the MongoDB Node.js driver will try to select a suitable server for operations before throwing an error. It affects both the initial connection attempt and subsequent database operations. Understanding and configuring this timeout is crucial for managing connection failures and improving responsiveness.


What is serverSelectionTimeoutMS?

The serverSelectionTimeoutMS setting tells the MongoDB driver how long it should keep trying to select a server for read or write operations before it declares failure and returns an error.


Default Value

By default, serverSelectionTimeoutMS is set to 30000 milliseconds (30 seconds). This means Mongoose will attempt server selection for up to 30 seconds before timing out.


Impact on Connection and Operations

This timeout applies to:

  • The initial connection attempt via mongoose.connect().
  • Any operations that require sending requests to the database like queries, inserts, updates, etc.

If the driver cannot find an available server within this time, it throws a MongoTimeoutError.


How to Set the Timeout

Set this option in the connection options object passed to mongoose.connect():

mongoose.connect('mongodb://localhost:27017/mydb', {
  serverSelectionTimeoutMS: 5000 // 5 seconds timeout
});

Error Handling with Timeout

If the timeout is reached, Mongoose throws a MongoTimeoutError which includes a reason property describing why selection failed (e.g., DNS error, authentication failure).

mongoose.connect('mongodb://badhost:27017/mydb', {
  serverSelectionTimeoutMS: 5000
}).catch(err => console.error('Connection failed:', err.reason));

Best Practices

  • Adjust serverSelectionTimeoutMS depending on network reliability and environment.
  • For serverless environments (like AWS Lambda), consider reducing timeout for faster failure detection.
  • For replica sets, use a higher timeout to accommodate elections and failovers.
  • Always handle MongoTimeoutError in your application for graceful failures.

Example Usage

const mongoose = require('mongoose');

async function connectWithTimeout() {
  try {
    await mongoose.connect('mongodb://localhost:27017/mydb', {
      serverSelectionTimeoutMS: 5000
    });
    console.log('Connected to MongoDB');
  } catch (err) {
    if (err instanceof mongoose.MongoTimeoutError) {
      console.error('Server selection timed out:', err.reason);
    } else {
      console.error('Other connection error:', err);
    }
  }
}

connectWithTimeout();

Conclusion

The serverSelectionTimeoutMS option is crucial to controlling MongoDB server selection retry behavior in Mongoose. Properly tuning and handling this timeout helps improve application responsiveness and robustness when MongoDB servers are unavailable or slow to respond.

Comments