AWS Lambda - Mongoose connection timeout AWS Lambda - Mongoose connection timeout mongoose mongoose

AWS Lambda - Mongoose connection timeout


Well, I came here looking for an answer to this myself.. anyway, the ONLY answer we have found so far is to open and close the DB connection each time the lambda is invoked.

Apparently, when the lambda isn't working, AWS suspends the process which means the socket looks dead to the mongodb server, so it drops the connection because it thinks it's a dead client. Thus trying to keep the socket around between lambda invokes leads to this timeout quite often.


The problem is when the lambda function is trigger from AWS Fargate.

When AWS uses IAMRole:PassRole it brakes the VPC/Subnet configuration, thus making the lambda function not able to connect to the mongo database.


We have experienced the same issue. it turns out our problem was mainly with making the connection outside the handler function .connection was being opened without the handler function being actually called and only by requiring lambda.js file.

The issue has vanished when we moved the connection code inside handler function:

// lambda.js// DO NOT open mongodb connection hereexports.handler = async (event, context) => {    // open the mongo connection here    // openMongodbConnection()}

I am not exactly sure how could this cause an issue but it is probably has something to do with the sequence to which subnet configuration will be applied.