Azure Cosmos DB: APIs, Consistency Levels, Partitioning, Request Units, Global Distribution and Change Feed
What Cosmos DB Is
- A fully managed, globally distributed, multi-model NoSQL database with low latency and elastic scale
- Backed by SLAs for availability, latency, throughput and consistency
- Best for IoT, retail catalogs, gaming, personalization and apps that need global reach
Choose an API
| API | Use |
|---|---|
| NoSQL (core) | JSON documents with SQL-like queries. Default for new apps |
| MongoDB | Apps already using MongoDB drivers |
| Cassandra | Wide-column apps built for Cassandra |
| Gremlin | Graph data |
| Table | Upgrade from Table Storage |
| PostgreSQL (distributed) | Sharded relational workloads |
API choice is fixed You choose the API when creating an account and cannot change it later.
The Five Consistency Levels
| Level | Meaning | Trade-off |
|---|---|---|
| Strong | Reads always see the latest committed write | Highest latency, limited with multi-region writes |
| Bounded staleness | Reads lag by at most K versions or T time | Good for global ordering with limits |
| Session (default) | Within one session you read your own writes | Best balance, most common |
| Consistent prefix | Reads never see out-of-order writes | Weaker |
| Eventual | No ordering guarantee | Lowest latency and cost |
Remember the order from strongest to weakest: Strong, Bounded staleness, Session, Consistent prefix, Eventual. Stronger consistency means higher latency and lower availability across regions.
Partitioning
- Each item has a partition key (for example
/customerId). Items with the same key form a logical partition (up to 20 GB) - Cosmos DB spreads logical partitions over physical partitions automatically
- A good key has high cardinality and spreads reads and writes evenly. Avoid keys like
countrythat create a hot partition - Queries that include the partition key are cheap (single partition). Others fan out (cross-partition)
bash
az cosmosdb create -g rg-data -n cosmos-shop-482 --kind GlobalDocumentDB --default-consistency-level Session \
--locations regionName=centralindia failoverPriority=0 isZoneRedundant=true \
--locations regionName=southeastasia failoverPriority=1 --enable-automatic-failover true
az cosmosdb sql database create -g rg-data -a cosmos-shop-482 -n shop
az cosmosdb sql container create -g rg-data -a cosmos-shop-482 -d shop -n orders --partition-key-path /customerId --max-throughput 4000
Request Units (RU/s)
- A request unit is a blended measure of CPU, memory and IO. A 1 KB point read by id and partition key costs about 1 RU. Writes and queries cost more
- Each response returns the RU charge, so you can tune queries
- If you exceed provisioned RU/s you get HTTP 429 (retry after the given delay)
| Capacity mode | Use |
|---|---|
| Provisioned throughput | Steady, predictable traffic. Fixed RU/s |
| Autoscale | Scales between 10% and 100% of a max RU/s. Variable traffic |
| Serverless | Pay per request. Small or sporadic workloads (dev/test, small apps) |
Global Distribution
- Click to add regions. Data replicates automatically
- Single-region write with many read regions, or multi-region writes for local writes everywhere (with conflict resolution policies)
- Automatic failover with priorities. Add availability zones for zone redundancy
Change Feed and Integrations
- The change feed is an ordered log of inserts and updates. Use it with Azure Functions triggers to react to changes, sync other stores or build event-driven systems
- Azure Synapse Link and Fabric mirroring allow analytics on operational data without affecting performance
- Continuous or periodic backups with point-in-time restore
python
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
client = CosmosClient("https://cosmos-shop-482.documents.azure.com:443/", credential=DefaultAzureCredential())
container = client.get_database_client("shop").get_container_client("orders")
container.upsert_item({"id": "o1001", "customerId": "c42", "total": 799.0, "status": "paid"})
for item in container.query_items("SELECT * FROM c WHERE c.customerId = @c", parameters=[{"name": "@c", "value": "c42"}], partition_key="c42"):
print(item["id"], item["total"])
Choosing Cosmos DB or SQL
| Choose Cosmos DB when | Choose Azure SQL when |
|---|---|
| Global low latency and elastic scale | Relational data with joins and transactions across tables |
| Flexible JSON schema | Strict schema and reporting |
| Massive writes (IoT, telemetry) | Existing SQL Server skills and tools |
Practice
- Create a serverless account and a container with
/customerId - Insert items and run a query with and without the partition key, compare RU
- Pick a consistency level for: bank balance, social feed, shopping cart
- Add a second region and test failover
Conclusion
Cosmos DB gives global, low-latency NoSQL. Choose the API first, a good high-cardinality partition key, a consistency level (Session by default) and a capacity mode (provisioned, autoscale or serverless). Use change feed for event-driven designs.
Quick Summary: APIs; consistency; partitioning; RUs; global; change feed; choosing.

