Azure Cosmos DB + Functions Cookbook — Connection modes
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:
If you work with Functions V2, there is a slight rename:
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:
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.
Stay tuned for more recipes!
Other posts in this series:
- Azure Cosmos DB + Functions Cookbook — static client
- Azure Cosmos DB + Functions Cookbook — HTTP querying
- Azure Cosmos DB + Functions Cookbook — output collector
- Azure Cosmos DB + Functions Cookbook — live migration
- Azure Cosmos DB + Functions Cookbook — search indexing
- Azure Cosmos DB + Functions Cookbook — secure client
- Azure Cosmos DB + Functions Cookbook — multi trigger
- Azure Cosmos DB + Functions Cookbook — Shared throughput and new health logs
- Azure Cosmos DB + Functions Cookbook — monitoring Trigger pending work