D2 · Storage

Azure Cosmos DB

Azure's multi-model, globally distributed NoSQL database. The AZ-104 tests consistency concepts, partitioning, RU/s, global distribution, and the available APIs.

Icon-databases-121

What is Azure Cosmos DB

is a fully managed, multi-model NoSQL database service designed to scale globally with . It guarantees comprehensive covering availability, throughput, consistency, and latency.

Unlike relational databases, Cosmos DB is schemaless — documents or entities don't need to follow a fixed schema.

Latency SLA

<10ms read, <10ms write (P99) in the local region

Availability SLA

99.999% for multi-region write. 99.99% single-region

Scalability

From kB to PB. Millions of requests/second with no redesign

Global distribution

Replicate to any Azure region with one click

Cosmos DB resource hierarchy

Cosmos Account

Top-level unit. Defines the API, consistency configuration, and regions.

→

Database

Logical container of containers. Can have shared throughput.

→

Container

Unit of scalability. Defines partition key, throughput, TTL, and indexes.

→

Item

JSON document (NoSQL API), row (Cassandra), node/edge (Gremlin), etc.

APIs and data models

Cosmos DB uses a unified engine with multiple API "fronts." The API defines the data model and the wire protocol. It cannot be changed after the account is created.

APIData modelProtocolMigrate fromBest for
NoSQL (native)JSON documentsHTTP/HTTPS RESTMongoDB, DynamoDB (with changes)New apps, JSON, frequent schema changes
MongoDBBSON documentsMongoDB wire protocolMongoDB on-prem/AtlasLift-and-shift of MongoDB apps without changing driver code
CassandraWide-column rowsCQL (Cassandra Query Language)Apache Cassandra on-premExisting Cassandra apps, time series, IoT
Gremlin (Graph)Graphs (vertices and edges)Gremlin over WebSocketNeo4j, TinkerPopSocial networks, knowledge graphs, fraud detection
TableKey-value (table)OData / RESTAzure Table StorageMigrating from Azure Table Storage with higher throughput
PostgreSQL (distributed)Distributed relationalPostgreSQL wirePostgreSQL on-premRelational apps that need horizontal scale (Citus)

For the AZ-104 exam

The AZ-104 doesn't go deep into every API. Focus on: NoSQL API (the native one, with all of Cosmos's features), MongoDB API (driver compatibility, lift-and-shift). The Table API is the migration path from Azure Table Storage with more scale.

Consistency levels

Cosmos DB's model is one of the most heavily tested topics. It defines the balance between data consistency and latency/availability. It's configured at the account level and can be relaxed per read operation.

Strong

Guarantees always reading the most recent version (linearizability)

Not available on accounts with multi-region writes. The most expensive.

Latency

Higher latency — must read from a majority of replicas

Bounded Staleness

Reads can lag by K versions OR T seconds (you define the limits)

Good for apps that tolerate some lag but need global ordering. Write order is guaranteed.

Latency

High latency for reads outside the region, similar to Strong within the write region

Session (default)

Guaranteed consistency for the client (session) that writes. Other clients may see an earlier version.

The default and recommended for most apps. "Read-your-writes" for the writing client.

Latency

Low — the most-used level

Consistent Prefix

You never see out-of-order reads. If A, B, C are written — you will never see C without B.

Doesn't guarantee reading the most recent, but the order is consistent.

Latency

Low

Eventual

No guarantee of order or of reading the most recent. Only 'will eventually converge'.

For cases where order doesn't matter: approximate counters, like counts, etc.

Latency

Minimum latency, maximum availability

Mnemonic rule

From strongest to most eventual: Strong → Bounded Staleness → Session → Consistent Prefix → Eventual. The stronger the consistency, the higher the read latency and the lower the availability. The default (Session) is the optimal balance for 90% of cases.

Partitioning — Partition Key

How partitioning works

Cosmos DB divides data into logical partitions based on the partition key value. Multiple logical partitions map to physical partitions that Cosmos manages automatically.

Limits per logical partition

Max. 20 GB of data

Max. 10,000 RU/s of throughput

Each physical partition has a max of ~10,000 RU/s and ~50 GB. Cosmos automatically redistributes (repartitions) as data grows.

Good Partition Key

  • ✓High cardinality — many distinct values (UserID, OrderID)
  • ✓Distributes throughput evenly (no "hot" partition)
  • ✓The most frequent queries include the partition key in the filter (avoids cross-partition queries)
  • ✓Items don't exceed 20 GB per PK value

Bad Partition Key

  • ✗Low cardinality — e.g., Boolean (only 2 possible values)
  • ✗Hot partition — e.g., day's timestamp (all activity in one partition)
  • ✗An item exceeds 20 GB (impossible to move it)

Synthetic partition key

If no natural field is a good PK, create one by combining several fields. E.g.: UserId + DateTime → "user123_2024-01"

Throughput — RU/s and provisioning modes

A Request Unit (RU) is Cosmos DB's performance currency. 1 RU = reading a 1 KB item with session consistency. Writes, complex queries, and cross-partition queries consume more RUs. The cost depends on item size, consistency, and operation type.

Provisioned throughput (manual)

You set a fixed number of RU/s (min 400 RU/s per container). You always pay for that throughput whether it is used or not.

When to use

Predictable load, strict latency SLA.

Autoscale (automatic throughput)

You set a maximum RU/s. Cosmos scales between 10% and 100% of that maximum based on demand. You are billed for the highest level reached each hour.

When to use

Variable or unpredictable loads. Ideal for dev/test and production with spikes.

Serverless

No provisioning — you pay only for the RUs consumed. No cost when there is no activity. No latency SLA guarantee at peaks.

When to use

Intermittent workloads, low traffic, early development.

Approximate cost of common operations (1 KB items)

OperationApprox. RUNotes
Point read (id + partition key)1 RUThe cheapest operation. Always use point read when possible.
Write (insert/replace)5 RUMore expensive than a read because it updates all indexes.
Query with partition key2-3+ RUVaries with complexity, number of results, and indexes.
Cross-partition queryMuch higherFans out to all partitions — avoid when possible.

Global distribution

Cosmos DB can replicate data to any Azure region with a single click. Global distribution enables local reads (low latency) and is key to global availability.

Multi-region write modes

Single-write region

Only one region accepts writes. The others are read replicas. Automatic or manual failover if the write region fails.

Multi-region writes (Multi-master)

All configured regions accept writes. Minimal write latency in any region. Requires managing write conflicts.

Conflict resolution (multi-write)

Last-Write-Wins (LWW)

The item with the highest _ts (timestamp) wins. Default. Can use any numeric field in the document.

Custom (Stored Procedure)

A Cosmos stored procedure decides which version prevails. Maximum flexibility for business logic.

Manual (Conflict Feed)

Conflicts are written to the "conflict feed" for the app to resolve manually.

TTL and Change Feed

Time-to-Live (TTL)

Lets items expire automatically after N seconds. Cosmos deletes them in the background without consuming write RUs from the user.

→ TTL on container: applies to all items that don't have their own TTL

→ TTL = -1: immortal (does not expire even if the container has TTL)

→ TTL = 0 or null: inherits the container's TTL

→ TTL on item: overrides the container's TTL for that specific item

Ideal for: user sessions, temporary data caches, expiring messages.

Change Feed

An ordered stream (by partition key) of all inserts and updates in a container. Lets you build event processing pipelines without polling.

Change Feed ProcessorSDK that distributes processing across workers. Maintains checkpoint state automatically.
Azure Functions triggerNative Cosmos trigger — the function fires on every change. Zero-config.
Pull modelThe client reads the change feed manually (more control, more work).

Use cases: materializing views, syncing caches, audit logs, replication to other systems.

Security and access control

Control plane vs Data plane

Control plane (ARM)

Create/delete accounts, databases, containers. Manage configuration. Authorized with standard (Owner, Contributor, Cosmos DB Account Reader).

Data plane

Read/write documents. Two methods: 1) Cosmos DB RBAC (built-in roles: Cosmos DB Built-in Data Reader, Data Contributor) — recommended. 2) Master Keys / Resource Tokens — legacy.

Encryption and networking

• Encryption at rest: automatic AES-256, not user-configurable

• Customer-managed keys (CMK): in . If the key is revoked, data becomes inaccessible

• Encryption in transit: TLS required

• Private Endpoints: same as Storage and SQL — private IP in a VNet

• IP Firewall: list of allowed IPs or CIDR ranges

• Virtual Network ACLs: restrict access to specific subnets

Resource Tokens — granular access

For temporary, granular read/write access (per container or item): the app generates a resource token with specific permissions and hands it to the client. Expires in max. 5 hours. Doesn't expose the master keys to the client.

Did you get this topic?

Test what you just learned

A global application needs users in Europe to read data with the lowest possible latency. The exact consistency of data between regions can tolerate a lag of up to 30 seconds. Which Cosmos DB configuration should you use?

Ready to test "Azure Cosmos DB"?

Put what you learned to the test with original AZ-104 exam questions.

Start AZ-104 mock exam

Unlimited mock exams with the Pro plan

Log in to track your progress.