How to reuse database connection in Azure Functions


Author: Venkat

Originally Sourced from: https://stackoverflow.com/questions/67207199/how-to-reuse-database-connection-in-azure-functions

I am using Azure Cosmos DB service. I have many azure functions which read & write data to this database (Kind of microservices architecture). Depending on the ingest, these functions scale to many instances and try persisting the data in parallel.

Inside these functions, I am connecting to the database and then performing Read/Write MongoClient.connect(url, function (err, client)

My question is, as my current implementation makes a new connection to the database every time (On invoking the function), I think it is not efficient. I heard Connection pool concept, but not sure how I can use this in microservices architecture or when I am writing to the database from Azure functions (Which are stateless). Please suggest

Note: I'm aware that in traditional Web application, We can use 'Singleton' or "Database Connection Pool', So that we can reuse 'mongoClient' objects for any CRUD Operations, However in Serverless architectures, How to reuse mongoClient Objects by many function invocations