Recently I have been trying multiple ways to optimize CosmosDb SQL.NET SDK integration calls from my web application that sits within a VNET.
After carefully analyzing different options available within Cosmos Db SQL API’s have realized there are different aspects we could optimize in achieving minimal turn around time. In this article I am going to discuss about one such useful find, that is to use Cosmos Db SQL SDK connection policy to use diferent networking options to improve the latency between web application and cosmos db API calls.
Connection Policy:
Performance of an client application has important implication based on – how SQL .NET SDK connects to Azure Cosmos DB , because of expected client-side latency due to networking conditions. There are two key configuration settings available for configuring client Connection Policy – the connection mode and the connection protocol.
There are two connection mode options provides by Cosmos Db SQL.NET SDK:
- Gateway Mode(which is default): This mode is the default option being used and works with all Cosmos DB SDK versions. Since it is only accessible over HTTPS/TCP, it is more secure and best choice for applications that run on a constrained secure corporate network. If you are using the .NET Framework version of the CosmosDb SQL.NET SDK, then proably this is the only connection mode that would work for you.
- Connection Protocol – TCP: 443 is the CosmosDb port, 10255 is the MongoDB API port.
- Connection Protocol – HTTPS: Default 443
- Connection Protocol – TCP: TCP would be more faster when client and db are in same VNET. Since TCP within the same network would be more faster, you would be amazed by the latency improvements by your client application. It would respond faster to you cosmos Db requests. NB In TCP mode apart from 443 and 10255 mentioned in Gateway more, we also need to ensure port range between 10000 and 20000 is open in your firewall configuration, because Azure Cosmos DB uses dynamic TCP ports.
- Connection Protocol – HTTPS: Since client application and cosmosDb are in same network limits, you could see that HTTPS option is also a reliable, secure and faster access channel for you, but not highly performing as TCP.
A simplified diagram below :
Sample Code:
string cosmosDbEndpoint = new Uri("https://mycosmosDbinstance.documents.net"); string authKey ="cosmosDb-apiKey"; DocumentClient client = new DocumentClient(cosmosDbEndpoint, authKey, new ConnectionPolicy { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp });
Refer more :
You can find the completed sample here: AzureContrib/CosmosDB-DotNet-Quickstart-With-ConnectionPolicy
Discover more from Cloud Distilled ~ Nithin Mohan
Subscribe to get the latest posts sent to your email.