AWS Lambda unable to connect (intermittently) to MongoDB inside an AWS VPC

Viewed 757

I am working with some AWS Lambda functions running inside VPC that needs to connect to a backend Mongo Atlas database for data storage/retrieval.

I am coding with Javascript, so i naturally used the official MongoDB Node JS client to establish the connection. The issue i am facing is that whenever i made a few concurrent lambda invocations, a few of them are unable to successfully establish a connection and basically hangs until Lambda timeout. For example, if 5 different functions were to be invoked, 2 might hang at connection attempt until Lamdba timeout. The connection is saved outside of the handler function for reuse in subsequent function invocation and the code is based on best practices specified here: https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/

I have read through all the online resources and mongo documentations available as well but i am unable to find any solution. Has anyone ever encountered such issue with Lambda in VPC connection to Mongo and getting timeout? How did you resolve it? Thanks.

1 Answers

I was having exactly the same issue.

Resolved it by explicitly NOT following the best-practices, and instead opening (and closing) a new connection for every lambda request that requires one.

In my setup, the connect() method takes between 20 and 70 milliseconds to complete, which I suppose I will more eagerly suffer than having intermittent and unreproducible hanging connections.

For good measure, I added { poolSize: 1 } to the MongoClient connection opts.

Related