Inconsistent MongoServerSelectionError: Server selection timed out after 30000 ms

We have an API working with MongoDB Atlas, connection works 99% of the time, but we occasionally get a MongoServerSelectionError: Server selection timed out after 30000 ms on a specific endpoint for some reason. Like I said, it fails 2/3 times out of 100.

We are connecting like so:

const { MongoClient} = require('mongodb');
const client = new MongoClient(
  process.env.MONGODB_CONNECTION_STRING,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }
);
module.exports = client.connect();

This is running on Netlify Functions, and whenever the function needs to use Mongo, it just awaits the connection promise.

Full error:

{
   "errorType":"Runtime.UnhandledPromiseRejection",
   "errorMessage":"MongoServerSelectionError: Server selection timed out after 30000 ms",
   "reason":{
      "errorType":"MongoServerSelectionError",
      "errorMessage":"Server selection timed out after 30000 ms",
      "reason":{
         "type":"ReplicaSetNoPrimary",
         "servers":{
            
         },
         "stale":false,
         "compatible":true,
         "heartbeatFrequencyMS":10000,
         "localThresholdMS":15,
         "setName":"atlas-13tibr-shard-0"
      },
      "stack":[
         "MongoServerSelectionError: Server selection timed out after 30000 ms",
         "    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:330:38)",
         "    at listOnTimeout (internal/timers.js:557:17)",
         "    at processTimers (internal/timers.js:500:7)"
      ]
   },
   "promise":{
      
   },
   "stack":[
      "Runtime.UnhandledPromiseRejection: MongoServerSelectionError: Server selection timed out after 30000 ms",
      "    at process.<anonymous> (/var/runtime/index.js:35:15)",
      "    at process.emit (events.js:400:28)",
      "    at processPromiseRejections (internal/process/promises.js:245:33)",
      "    at processTicksAndRejections (internal/process/task_queues.js:96:32)"
   ]
}
1 Like

We have the exact same issue. Were you able to resolve it?

What’s really annoying is this didn’t happen to us in the free tier. It only started happening in the paid tier

1 Like

Did you manage to solve it somehow?

This is a serious issue for our small startup. We are hosting on Vercel and are seeing roughly the same failure rates.

Has anyone solved this? We need this fixed ASAP

Any solution to this?