So I've been looking for the most efficient way to connect to MongoDB from a python code base on AWS serverless lambda functions.
I understand the most popular (and probably the easiest) way of doing it, that is to use pymongo
.
pymongo
establishes a connection with MongoDB (myclient = pymongo.MongoClient("mongodb:url")
) which needs to be closed myclient.close()
.
This is great for a traditional infrastructure where a connection once made, can be maintained over time.
However, in a serverless infrastructure, each function is triggered by an event (say, API Gateway) and shut down after use. This means the connection to MongoDB is opened and closed for each function's lifetime (which lasts usually a few seconds).
Is there a better alternative to this?