Hamish Anderson
Hamish Anderson

Reputation: 617

Reusing Database Connections With Azure Functions Using Javascript

I cannot find clear information on how to manage database connections (MongoDB in my case) from an Azure function written in Javascript.

The Microsoft document below says to not create a connection for each invocation of the function by using static variables in C# using .NET Framework Data Provider for SQL Server and the pooling is handled by the client connection. It does not describe how to do this in Javascript.

https://learn.microsoft.com/en-us/azure/azure-functions/manage-connections

A solution of creating a global variable to hold the database client between invocations is described here but the author is not confident this is the correct way to do it.

http://thecodebarbarian.com/getting-started-with-azure-functions-and-mongodb.html

Has anyone used this in production or understand if this is the correct approach?

Upvotes: 0

Views: 4861

Answers (1)

MarkXA
MarkXA

Reputation: 4384

Yes, there's a very close equivalence between C#/SQL storing a single SqlConnection instance in a static variable and JS/MongoDB storing a single Db instance in a global variable. The basic pattern for JS/MongoDB in Azure Functions is (assuming you're up to date for async/await - alternatively you can use callbacks as per your linked article):

// getDb.js

let dbInstance;

module.exports = async function() {
    if (!dbInstance) {
        dbInstance = await MongoClient.connect(uri);
    }
    return dbInstance;
};

// function.js

const getDb = require('./getDb.js');

module.exports = async function(context, trigger) {
    let db = await getDb();
    // ... do stuff with db ..
};

This will mean you only instantiate one Db object per host instance. Note this isn't one per Function App - if you're using a dedicated App Service Plan then there will be the number of instances you've specified in the plan, and if you're using a Consumption Plan then it'll vary depending on how busy your app is.

Upvotes: 7

Related Questions