Intermittently getting MongoServerSelectionError error on my Next.js Vercel deployment

Is there any particular reason why I am intermittently getting this error in my Next.js Vercel deployment when connected to MongoDB? This isn’t happening too often but I would like to understand what the issue is and fix it. I’m passing the options { useNewUrlParser: true, useUnifiedTopology: true } to the MongoClient. It appears this is a somewhat common problem on Vercel, but I haven’t found any solutions. Any ideas? Thanks.

ERROR	Unhandled Promise Rejection 

{
   "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-j7739j-shard-0",
         "maxElectionId":null,
         "maxSetVersion":null,
         "commonWireVersion":0,
         "logicalSessionTimeoutMinutes":null
      },
      "stack":[
         "MongoServerSelectionError: Server selection timed out after 30000 ms",
         "    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/sdam/topology.js:278:38)",
         "    at listOnTimeout (node:internal/timers:569:17)",
         "    at process.processTimers (node:internal/timers:512:7)"
      ]
   },
   "promise":{
      
   },
   "stack":[
      "Runtime.UnhandledPromiseRejection: MongoServerSelectionError: Server selection timed out after 30000 ms",
      "    at process.<anonymous> (file:///var/runtime/index.mjs:1250:17)",
      "    at process.emit (node:events:526:35)",
      "    at emit (node:internal/process/promises:149:20)",
      "    at processPromiseRejections (node:internal/process/promises:283:27)",
      "    at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"
   ]
}

"LAMBDA_RUNTIME Failed to post handler success response. Http response code":"400.

Hi @Adam_Romero,

Difficult to decisively say at the moment what the issue could be. To confirm from the Atlas perspective, have you checked your cluster at the time of these errors to see if there were any possible issues (restarts, resource exhaustion, etc)?

You could also try having another application outside of Vercel connecting to the same cluster to see if it generates the same error and the same time for troubleshooting purposes. This might help narrow down where / what the issue could be.

Regards,
Jason

1 Like