OdeToCode IC Logo

Cosmos DB Request Units and the .NET SDK

Tuesday, October 31, 2017

Platform database services in Azure, like Azure SQL and Cosmos DB, both need to charge each of us according to our utilization.

Azure SQL measures utilization using  a Database Throughput Unit (DTU). A DTU is a relative number we can use to compare pricing tiers. As a relative number, a single DTU remains intangible and mysterious.

Cosmos DB measures utilization using a Request Unit (RU). An RU is well defined, and there is even a calculator available to estimate RU provisioning.

Cosmos includes the resource charge for every operation as an HTTP response header. It is not immediately obvious how to access the request charge when using the .NET SDK, but as the following code shows, you can access a RequestCharge property as part of any IFeedResponse. The following code collects the charges over the course of iterating a paged query. 

var query = client.CreateDocumentQuery<T>(
    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
    new FeedOptions { MaxItemCount = -1 })
    .AsDocumentQuery();
           
var results = new List<T>();
var totalRequestCharge = 0.0;

while (query.HasMoreResults)
{
    var response = await query.ExecuteNextAsync<T>();
    totalRequestCharge += response.RequestCharge;
    results.AddRange(response);
}