Intermittent MongoServerSelectionError when connecting from NodeJS using Google Cloud Run + MongoDB Atlas

Hey folks,

Hi, I’m having problems with connecting to MongoDB Atlas from a Google Cloud Run instance. I’m intermittently (a few times per day) getting a MongoServerSelectionError when my server is initializing and trying to connect. This is my current setup:

  • Using M10 tier cluster on MongoDB 4.4.
  • Connecting using NodeJS driver version 3.6.0.
  • useUnifiedTopology set to true.
  • Whitelisted all IP addresses in MongoDB atlas for the cluster.

I’m not seeing any alerts in MongoDB atlas. Please note that this is an intermittent issue. Sometimes it connects sometimes it doesn’t. Because my app currently has very low traffic there is never more than one instance running so the 30-second timeout + time to restart of the container makes this problem critical.

Here’s the stack trace:

MongoServerSelectionError: connection timed out at Timeout._onTimeout (/usr/src/app/node_modules/mongodb/lib/core/sdam/topology.js:438:30) at listOnTimeout (internal/timers.js:549:17) at processTimers (internal/timers.js:492:7) {
reason: TopologyDescription {
type: ‘ReplicaSetNoPrimary’,
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
xxx-00-00-0qvnm.gcp.mongodb.net:27017’ => [ServerDescription],
xxx-00-01-0qvnm.gcp.mongodb.net:27017’ => [ServerDescription],
xxx-00-02-0qvnm.gcp.mongodb.net:27017’ => [ServerDescription]
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}

Can anybody assist with troubleshooting this?

Regards,
Stefan

1 Like

Sorry I’m on MongoDB version 4.2 not 4.4

Has this issue been resolved for you? I’m having the same issue, of intermittent connectivity due to a timeout, but mine is happening from a DigitalOcean droplet. I’ve tried almost everything, except use Mongoose.

For my setup:

  • using MongoDB Atlas M0, 4.2.11
  • mongodb native driver 3.6.3

I resolved it by setting useUnifiedTopology: false, works great now.

1 Like