Skip to content

Cache or Reuse Mongodb connection in AWS lambda using Python

0

I'm building a serverless application using Python and Mongodb. In documentation I found that I need to write db connection outside handler function. I have used Mangum python package as adapter to handle API gateway.

from fastapi import FastAPI
from mangum import Mangum

def get_application() -> FastAPI:
    application= FastAPI()
    #db is creating instance of AsyncioMotorClient #coded in another file
    db.client = AsyncIOMotorClient(str(MONGODB_URL),
                                   maxPoolSize=MAX_CONNECTIONS_COUNT,
                                   minPoolSize=MIN_CONNECTIONS_COUNT, 
                                   waitQueueMultiple = MAX_DB_THREADS_WAIT_COUNT,
                                   waitQueueTimeoutMS = MAX_DB_THREAD_QUEUE_TIMEOUT_COUNT )
    return application

app =get_application()

@app.get("/")
def read_root():
   
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

handler = Mangum(app)

For every API request, new connection is created. How to cache db so that new request uses old connection. Every time new request is created so that lambda compute time is increased dramatically after db hits max connection limit.

asked 4 years ago1.5K views

1 Answer
0

You should just create the DB connection outside of any function, or store it in a global variable if that variables has not been assigned yet.

AWS
EXPERT

answered 4 years ago

EXPERT

reviewed 2 years ago

  • Could you help me with an example? I spend whole day and couldn't solve

  • Do we need to close connection after opening connection?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.