AlexKogan
AlexKogan

Reputation: 355

AWS Lambda callback being blocked by open mongodb connection?

I have setup an AWS lambda to do some data saving for me to MongoDB. I'd like to reuse the connection so I dont have to create a new connection every time the lambda is invoked. But if I leave the db connection open, the callback for the Lambda handler doesnt work!

Is there something I'm doing wrong thats creating this behavior? Here is my code:

var MongoClient = require('mongodb').MongoClient

exports.handler = (event, context, callback) => {
    MongoClient.connect(process.env.MONGOURL, function (err, database) {
        //database.close();
        callback(null, "Successful db connection")
    });
}

Upvotes: 0

Views: 703

Answers (1)

Michael - sqlbot
Michael - sqlbot

Reputation: 179144

This is caused by not setting context.callbackWaitsForEmptyEventLoop = false. If left at the default true, the callback does not cause Lambda to return the response because your database connection is keeping the event loop from being empty.

http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html

Upvotes: 4

Related Questions