The Aspire.Microsoft.Azure.Cosmos component registers a CosmosClient as a singleton in your dependency injection container for connecting to Azure Cosmos DB. It automatically enables logging and distributed tracing.
public async Task<List<Product>> GetExpensiveProductsAsync(){ var queryable = _container.GetItemLinqQueryable<Product>(); var query = queryable .Where(p => p.Price > 100) .OrderByDescending(p => p.Price) .Take(10); using var iterator = query.ToFeedIterator(); var results = new List<Product>(); while (iterator.HasMoreResults) { var response = await iterator.ReadNextAsync(); results.AddRange(response); } return results;}
public async Task BulkCreateAsync(List<Product> products){ var tasks = new List<Task>(); foreach (var product in products) { tasks.Add(_container.CreateItemAsync( product, new PartitionKey(product.Category))); } await Task.WhenAll(tasks);}
public async Task TransactionalUpdateAsync( string partitionKey, List<Product> products){ var batch = _container.CreateTransactionalBatch( new PartitionKey(partitionKey)); foreach (var product in products) { batch.UpsertItem(product); } using var response = await batch.ExecuteAsync(); if (!response.IsSuccessStatusCode) { throw new Exception($"Batch failed: {response.StatusCode}"); }}
Select partition keys that evenly distribute your data and align with your query patterns:
// Good: Evenly distributedpublic class Product{ public string Id { get; set; } public string Category { get; set; } // Partition key}// Avoid: Skewed distributionpublic class Order{ public string Id { get; set; } public bool IsActive { get; set; } // Only two possible values!}
Use point reads when possible
Point reads (by ID and partition key) are the most efficient:
// Most efficientvar product = await _container.ReadItemAsync<Product>( id, new PartitionKey(category));// Less efficientvar products = await QueryAsync("SELECT * FROM c WHERE c.id = @id");
Implement retry logic
Handle rate limiting (429) and transient errors:
try{ await _container.CreateItemAsync(product, new PartitionKey(product.Category));}catch (CosmosException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests){ await Task.Delay(ex.RetryAfter ?? TimeSpan.FromSeconds(1)); // Retry the operation}
Monitor request charges
Track RU consumption to optimize costs:
var response = await _container.ReadItemAsync<Product>( id, new PartitionKey(category));Console.WriteLine($"Request charge: {response.RequestCharge} RU/s");
Use bulk execution for large operations
Enable bulk execution mode for better performance: