Reputation: 65
I have a simple lambda function which connects to database and find user.
import pymongo
def my_handler(event, context):
client = pymongo.MongoClient('uri') #My db connection here.
db = client.dbName
col = db.users
col.find_one({'email':'[email protected]'})
foundedUser = col.find_one({'hello':'Amazon DocumentDB'})
print(foundedUser)
client.close()
I got a weird problem, sometimes lambda connects and find user like for 100ms or even less. But sometimes there is a timed out error after 30 sec. I have all vpc configs and so on. I've tried to make it using node.js and now trying with python result is the same. Any suggestions ?
Upvotes: 1
Views: 5745
Reputation: 31
So I was running into the same issue. Check these out.
https://blog.cloudboost.io/i-wish-i-knew-how-to-use-mongodb-connection-in-aws-lambda-f91cd2694ae5
https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs
and this
https://hackernoon.com/building-a-serverless-rest-api-with-node-js-and-mongodb-2e0ed0638f47
Apparently, AWS Lambda is "stateless" and the way that I understand it, once the function is called on a cold start it runs your code and connects to your database. After that, any call you make to your Lambda function for a certain time (say 5 minutes) will use that same connection. Afterwards, if the connection is closed and a function is invoked again, the Lamda doesn't reestablish a connection to the database.
The tutorials should hopefully help set it up so that it checks for a connection on each function call.
Upvotes: 1