MongoServerSelectionError - Server selection timed out after xxx ms
When working with mongodb, you may encouter error saying
"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":"Cluster0-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:1186:17)"," at process.emit (node:events:525: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)"]}
[ERROR] [1692698804885] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
RequestId: b4f3e09a-4eb9-4414-b70b-7ef5a5b29fdd Error: Runtime exited with error: exit status 128
Runtime.ExitError
Above error can be caused due to multiple reasons. You can try below solutions.
Solutions
- This must be a temporary network issue.
- In Atlas free tier, big database size may cause this issue
- Whitelist ip from where you are accessing the mongodb
- Add this to the end of connection string - ?directConnection=true
- update mongoose and mongodb packages
- firewall blocking the port
- Check mongodb options as mentioned below
maxIdleTimeMS: 80000,
serverSelectionTimeoutMS: 80000,
socketTimeoutMS: 0,
connectTimeoutMS: 0,
replicaSet option
Published on: Aug 23, 2023, 10:09 AM