Azure Cosmos DB + Functions Cookbook — Connection modes

Matías Quaranta
Microsoft Azure
Published in
3 min readAug 8, 2018

This next Azure Cosmos DB + Azure Functions recipe will show you how to customize the ConnectionMode and Protocol used in the Azure Functions bindings and triggers.

Scenario

You want to use the abstraction provided by the Azure Functions’ Cosmos DB bindings but you need to customize the ConnectionMode and Protocol due to a particular circumstance or to improve performance.

Ingredients

For this recipe, there is no particular ingredient, it will apply to any scenario where you are using the Cosmos DB Input Binding, Cosmos DB Output Binding or the Cosmos DB Trigger.

The bindings hide from you the complexity of creating and maintaining the Cosmos DB clients, but it had the drawback of blocking your ability to customize these two settings, until recently.

Recipe

Customization of the ConnectionMode and Protocol is achieved through the host.json file, present in all Azure Functions projects.

Based on the current JSON schema, if we want to make all DocumentClient instances connect through Direct / TCP mode, we could define it like so, when working on a Functions V1 App:

Configuration for Functions V1

If you work with Functions V2, there is a slight rename:

Configuration for Functions V2

The configuration will then be injected inside the logic that creates and maintains the internal clients.

If we are coding our Azure Functions through the Azure Portal, the host.json file content is available on the Function app settings within Platform features:

Finding Function app settings
Setting the ConnectionMode and Protocol through Azure Portal

Important regarding Consumption Plan: Consumption Plan instances have a limit in the amount of Socket Connections that they can maintain. The Cosmos DB in Direct / TCP mode creates more outbound connections by design and can hit the Consumption Plan limit, in which case you can either use Gateway mode or run your Azure Functions in App Service Mode.

After this change, all instances of DocumentClient used in any of the bindings and in the Cosmos DB Trigger will use the defined ConnectionMode and Protocol.

The full code sample is available in my Serverless Recipes repo.

--

--

Matías Quaranta
Microsoft Azure

Software Engineer @ Microsoft Azure Cosmos DB. Your knowledge is as valuable as your ability to share it.