Cosmos DB Mongo Error: MongoServerSelectionError Server selection timed out after 30000ms Error

Ethan Soo Hon 1 Reputation point
2022-05-02T21:53:59.757+00:00

We are currently running multiple environments for our Cosmos DB using MongoDB APIs. In our dev environment we were able to successfully connect to Cosmos through the MongoDB package (mongodb) and successfully perform operations to create collections, add documents etc... but when the exact codebase was attempted to be used in the production environment the following error would propagate after trying to establish the initial connection to Cosmos (sometimes we could establish the initial connection to Cosmos but after a short period of time it would propagate the same error again)

Result: Failure Exception: MongoServerSelectionError: Server selection timed out after 30000 ms Stack: MongoServerSelectionError: Server selection timed out after 30000 ms at Timeout._onTimeout

(*Note: I have never seen this particular error when running Cosmos in our development environment)

To add additional information, we have an Azure functions app (running Node js) running that connects to Cosmos DB (via Mongodb) and performs operations.
We use the "primary connection" string for our Cosmos DB and insert it as appSettings for our Azure functions API.

Both the development and the productions servers are set up in the exact same manner they both have the same settings...

  • Access to all networks (so we know its not a IP whitelist error)
  • SSL is true (option is set in connection string)
  • Same Database/collection names
  • Same maxIdleRetry time setting (120000)

(here are the full connections string settings set ?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000)

Does anyone have any insight into this error? Am I missing a setting/option that needs to be set on the MongoDB connection?

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,263 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Purnot, Bram 11 Reputation points
    2022-05-03T06:13:26.97+00:00

    Hey there!

    I'm actually facing the exact same problem here. One of the recommendations I saw was to not include the username/password in the connection string but rather pass it in the options like this:

    var DATABASE_URL = `mongodb://${process.env.MONGO_ENDPOINT}:${process.env.MONGO_PORT}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@eccosmosdb@&directConnection=true`;
    
    const option = {
      auth: {
        user: process.env.MONGO_USERNAME,
        password: process.env.MONGO_PASSWORD,
     }
    };
    
    mongoose.connect(DATABASE_URL, option);
    

    Have you tried this yet?

    Bram

    2 people found this answer helpful.