Lessons in this course (9)

6. Azure Cosmos DB — APIs, partitioning, RU/s and consistency

Intermediate★ Must knowLesson 6 of 9

Cosmos DB is a globally distributed, multi-model NoSQL database with single-digit-millisecond latency and automatic indexing.

APIModel
NoSQL (core)JSON documents queried with a SQL-like language — most common, newest features
MongoDB (RU or vCore)Use MongoDB drivers
Cassandra, Gremlin (graph), TableCompatibility with those ecosystems
PostgreSQL (Citus)Distributed PostgreSQL

Key concepts:

  • Account → database → container → items (JSON documents).
  • Partition key — chooses how data is spread across physical partitions. Pick a property with high cardinality and even access (e.g. /customerId, /tenantId); queries that include the partition key are cheap, cross-partition queries cost more. A hot partition limits throughput.
  • Request Units (RU/s) — the currency of throughput: a 1 KB point read ≈ 1 RU; writes and queries cost more. Provisioned (manual or autoscale) or serverless (pay per RU consumed).
  • Consistency levels (strongest → weakest): Strong, Bounded staleness, Session (default — read-your-own-writes per session), Consistent prefix, Eventual. Weaker = lower latency and cost, higher availability.
  • Global distribution: add regions with one click, optional multi-region writes, automatic failover.
  • Change feed — ordered stream of changes for event-driven processing (Azure Functions trigger), materialised views, sync to search.
csharp
var client = new CosmosClient(endpoint, new DefaultAzureCredential());
var container = client.GetContainer("shop", "orders");                       // partition key /customerId
await container.CreateItemAsync(new { id = Guid.NewGuid().ToString(), customerId = "c42", total = 4500 }, new PartitionKey("c42"));
var order = await container.ReadItemAsync<Order>("order-id", new PartitionKey("c42"));   // point read: cheapest
var query = container.GetItemQueryIterator<Order>(new QueryDefinition("SELECT * FROM o WHERE o.customerId = @c AND o.total > 1000")
    .WithParameter("@c", "c42"));