0

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?

bipster
  • 404
  • 1
  • 8
  • 20
  • 1
    "connection ... is opened and closed for each function's lifetime" is not quite right. AWS spins up a runtime environment on first call to Lambda and keeps it for some time to re-use if the function is called again soon. IIRC the shut-down time was like 15 min for VPC-based functions and 5 min otherwise. The numbers might change since latest changes and introduction of docker functions. If you create a connection outside of the handler it will be reused on next warm invocation. – Alex Blex Feb 01 '21 at 16:40
  • Ah, and closer to the question itself, the official implementations / bindings of mongo wire protocol in python are all here https://docs.mongodb.com/drivers/python – Alex Blex Feb 01 '21 at 16:45

0 Answers0