Azure Cosmos DB + Functions Cookbook — Multi master & preferred region

Matías Quaranta
Microsoft Azure
Published in
3 min readNov 12, 2018

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:

Connecting each Function to its closest Cosmos DB

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.

Adding more regions in the Azure Portal

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.
Example of an Input Binding
Example of an Output Binding

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.

--

--

Matías Quaranta
Microsoft Azure

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