简体   繁体   中英

Aws lambda function connect to mongodb

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':'example@gmail.com'})
    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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM