Azure Cosmos DB + Functions Cookbook — Multi master & preferred region
This next Azure Cosmos DB + Azure Functions recipe will show you how to define a preferred connection region, and take advantage of the new Multi-master capabilities.
Scenario
You have a globally distributed Functions architecture and you want to take advantage of Azure Cosmos DB’s globally distributed endpoints by connecting Functions to the closest database replica to optimize latency.
Ingredients
For this recipe we’ll be using the Cosmos DB Input Binding, as we’ve seen in one of our previous recipes, and two Cosmos DB features: UseMultipleWriteLocations, and PreferredLocations.
If you found this post you are probably building a globally distributed Azure Functions architecture like so:
And you want each Function to have the lowest connection latency possible, based on some routing logic defined in an Azure Traffic Manager or simply some other balancing rule.
Recipe
The first step is obviously making sure your Azure Cosmos DB database is replicated in all the regions where you have deployed your Azure Functions. You can achieve this through the Azure Portal or through Azure CLI.
Now, the second step is to add the new attributes to your Cosmos DB Bindings:
- PreferredLocations: Comma-separated list of regions you want the binding or trigger to connect to. Applicable to Bindings and Trigger.
- UseMultipleWriteLocations: If your account has Multi Master enabled, you can make your writes go to the closest regions and reduce write latency. Only applicable to Bindings.
And that’s it! Just by adding those two attributes you can optimize your globally distributed Functions architecture. You can see full code samples in the Serverless Recipes repo.
Can I use this recipe even if my account is not Multi Master?
Yes! You should definitively take advantage of PreferredLocations
as it will make all your Read operations faster, while your Write operations will always go to your main Cosmos DB region.
Closing notes
Thanks to the configuration support in Azure Functions, you can make the value of PreferredLocations
bound to an environment configuration attribute. That way you can deploy the same bits to multiple regions and use a configuration to define the region to connect to.
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 — Connection modes
- Azure Cosmos DB + Functions Cookbook — Shared throughput and new health logs
- Azure Cosmos DB + Functions Cookbook — monitoring Trigger pending work