'Azure Cosmos DB Connection Slow
I am finding connecting to and querying Azure Cosmos DB with C# .Net is very slow. It is taking about 2.5 seconds to connect and 8 seconds to do a simple query returning about 600 rows (no where clause). Is there more efficient way to do this? Or best to use a client side connection pool so connections are re-used so don't have to connect as many times? This will mainly be used as a Azure Web Service (ASP.Net)
Interesting if I don't do the ReadThroughputAsync() method after getting the cosmos container, then the Initialize() only takes 438 ms but the query takes longer (8.9 seconds). Anyone know why this is?
With calling await _container.ReadThroughputAsync(): Initialize() in 2482 ms Found 598 results in 8171 ms Without calling await _container.ReadThroughputAsync(): Initialize() in 438 ms Found 598 results in 8937 ms
private const string ContainerId = "Items";
private const string DatabaseId = "Results";
private const string EndpointUri = "https://myServer.documents.azure.com:443/";
private const string PrimaryKey ="xxxxxxx==";
private Container _container;
private CosmosClient _cosmosClient;
private Database _database;
public async Task Initialize()
{
var tickCount = Environment.TickCount;
_cosmosClient = new CosmosClient(EndpointUri, PrimaryKey,
new CosmosClientOptions {ApplicationName = "DataImporter"});
_database = _cosmosClient.GetDatabase(DatabaseId);
_container = _database.GetContainer(ContainerId);
var throughput = await _container.ReadThroughputAsync();
tickCount = Environment.TickCount - tickCount;
WriteLine($"Initialize() in {tickCount} ms");
var tickCount2 = Environment.TickCount;
var sqlQueryText = $"SELECT * FROM c";
var queryDefinition = new QueryDefinition(sqlQueryText);
var queryResultSetIterator = _container.GetItemQueryIterator<SampleData>(queryDefinition);
var results = new List<SampleData>();
while (queryResultSetIterator.HasMoreResults)
{
var currentResultSet = await queryResultSetIterator.ReadNextAsync();
foreach (var result in currentResultSet)
results.Add(result);
}
tickCount2 = Environment.TickCount - tickCount;
WriteLine($"Found {results.Count} results in {tickCount} ms");
}
Solution 1:[1]
Thank you Gaurav Mantri, David Makogon and Mark Brown. Posting your suggestions as answer to help other community members.
Practices that you can adopt to make the connection faster
- Initialize the cosmos connection at startup. you would need to use
CreateAndInitializeAsyncmethod of the CosmosClient.- Make sure to run the code in the same region as that of cosmos DB.
- Always have the reference to cosmos client and container alive. This will ensure the subsequent calls (after 1st call) will be faster.
Reference:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MadhurajVadde-MT |
