Container Creation and Configuration
To store data in Azure Cosmos DB, you programmatically create Azure Cosmos DB containers using the SDK. During creation, you must specify a partition key, which is a JSON property used to distribute data across logical partitions. You also configure throughput measured in Request Units (RUs), which can be managed manually or through autoscale to automatically adjust capacity based on workload demand. Additionally, developers configure the consistency level, time-to-live (TTL) rules for data expiration, and indexing policies to optimize database behavior.
Container and Item Operations
The SDK enables full management of both containers and the items they hold. For containers, you can perform setup and teardown tasks, while for items, you can create, read, update, upsert, and delete records. An upsert operation is a versatile choice because it inserts a new item if it does not exist or updates the existing item using its unique Document ID. To retrieve data, the SDK executes SQL-like queries that benefit from automatic indexing, and it supports bulk methods to process multiple items in fewer network rounds.
Achieving high performance requires choosing a partition key with high cardinality to distribute data evenly and avoid hot partitions. You can scale RUs dynamically via the SDK to respond to real-time traffic spikes without paying for idle resources. For global reach, developers configure geo-replication using the SDK, which copies data across multiple regions to lower latency and handle automatic failovers. The SDK also provides built-in retry logic to automatically resolve transient faults, such as brief network drops or throttling events.
Implement CRUD Operations Using the Cosmos DB SDK
Setting Up the SDK Clients
Interacting with the database begins by instantiating a CosmosClient in your application code. From this client, the application obtains a Database object and subsequently a Container object to perform targeted operations. Developers use helper methods like CreateDatabaseIfNotExistsAsync and CreateContainerIfNotExistsAsync to automatically set up resources. This programmatic setup ensures that the infrastructure matches application expectations without requiring manual configuration in the Azure Portal.
Executing CRUD Actions on Items
Once the container is ready, you can perform basic data operations using specific asynchronous SDK methods. To add data, you call CreateItemAsync, while ReadItemAsync and QueryItemsAsync retrieve documents by their unique identifier or through SQL queries. To modify data, you use ReplaceItemAsync or upsert operations, which can apply optimistic concurrency to prevent overwriting conflicting changes. Finally, when data is no longer needed, DeleteItemAsync removes the document from the physical storage partition.
Every SDK operation interacts with container settings like the partition key, indexing policy, and throughput budget. Choosing an indexing policy allows you to include or exclude specific document paths, which directly balances write speed against query performance. Developers must choose an appropriate consistency level—such as strong, session, or eventual—to balance data freshness against latency. To manage ongoing storage costs and maintain performance, you can enable time-to-live (TTL) settings to automatically purge expired items.
Execute Transactional and Bulk Operations
Transactional Execution with TransactionalBatch
To execute multiple operations as a single unit of work, the SDK provides the TransactionalBatch class. This class guarantees atomicity, meaning either all operations in the batch succeed or the entire batch is rolled back if any single operation fails. Crucially, all actions within a single TransactionalBatch must target the exact same partition key. This restriction ensures that the database can maintain absolute data consistency across multiple items in a single physical partition.
High-Speed Bulk Operations
When migrating large datasets or performing initial loads, you should use bulk execution rather than transactional batches. Bulk execution maximizes throughput by sending many independent requests simultaneously, focusing on high-speed ingestion rather than transaction atomicity. The SDK optimizes network usage by grouping these requests behind the scenes to reduce roundtrips. This approach allows the system to ingest massive amounts of data efficiently without being restricted to a single partition key or transactional boundary.
Managing Request Units and Failures
Executing transactional and bulk operations requires close monitoring of RUs to avoid database throttling. If operations consume more RUs than the provisioned throughput allows, the database will return rate-limiting errors. To prevent this, developers should limit batch sizes to stay under the 2 MB limit, adjust throughput budgets, and write code to handle failures. While the SDK automatically retries transient failures, the application must still capture and handle non-retryable errors like Unauthorized or BadRequest.