# Azure Cosmos DB

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/azure-cosmos-db

## Quick definition

Azure Cosmos DB is a cloud database that stores data in a way that lets it be accessed quickly from anywhere on the planet. It automatically spreads your data across multiple regions to protect against outages and provide low latency. You can choose how consistent you need your data to be, which helps balance between speed and accuracy.

## Simple meaning

Think of a library that has branches all over the world. If you live in New York and someone else lives in Tokyo, you both can check the same book at the same time because there are copies in both cities. Azure Cosmos DB is like that library for computer data. It keeps copies of your data in multiple data centers around the globe, so no matter where a user is, they can get the information they need very quickly.

Now, imagine that library also allows you to choose how strictly the copies must be identical across branches. If you need absolute certainty that every branch has the exact same book at the exact same moment, you get strong consistency. But if you can tolerate a tiny delay as changes spread from one branch to another, you can use eventual consistency, which is much faster and more available. Azure Cosmos DB gives you five different levels of consistency to choose from, ranging from very strong to very relaxed.

This database is also very flexible because it accepts many different ways of storing data. It can handle JSON documents, key-value pairs, graphs, and even column-family data, all without forcing you into a rigid table structure like traditional SQL databases. You can use it for powering web apps, mobile backends, gaming leaderboards, Internet of Things (IoT) telemetry, and much more.

Finally, Azure Cosmos DB handles all the hard parts of keeping the database running. It automatically scales storage and throughput up or down based on demand, patches itself, and ensures high availability with a guaranteed uptime of 99.999 percent for multi-region writes. You do not need to manage servers or worry about maintenance windows.

## Technical definition

Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft Azure. It is a fully managed Platform-as-a-Service (PaaS) offering that abstracts away all infrastructure management, including hardware provisioning, replication, patching, and scaling. At its core, Cosmos DB uses a proprietary distributed database engine that supports multiple data models and APIs, including the SQL API (for querying JSON documents using a SQL-like syntax), the MongoDB API, the Cassandra API, the Gremlin API (for graph data), and the Table API.

The fundamental unit of scalability in Cosmos DB is a container. A container holds a set of items, and each item is a schema-agnostic record, typically stored as JSON. Containers are provisioned with a specific throughput measured in Request Units per second (RU/s). A Request Unit is a normalized measure of the computational cost of a database operation, including CPU, memory, and I/O. For example, a simple read of a 1 KB item costs about 1 RU, while a complex multi-document query may cost more. You can provision RU/s at the container level or at the database level, and you can choose between manual (fixed) throughput and autoscale throughput, which automatically adjusts based on traffic.

Cosmos DB achieves global distribution through a feature called multi-region writes. You can associate your Azure Cosmos DB account with any number of Azure regions. When write requests are sent to any of these regions, the data is automatically replicated to all other regions asynchronously or synchronously, depending on the chosen consistency level. The underlying replication mechanism uses a consensus protocol to ensure that all replicas converge without conflict.

The service offers five well-defined consistency models, from Strong (highest consistency, lowest availability and latency) to Eventual (lowest consistency, highest performance). In between are Bounded Staleness, Session, and Consistent Prefix. Session consistency is the default and is the most commonly used because it guarantees monotonic reads, writes, and read-your-writes for a single client session while offering low latency and high availability.

Cosmos DB also provides guaranteed latency at the 99th percentile for reads and writes. For a 1 KB item, reads are typically under 10 milliseconds, and writes under 15 milliseconds, even across regions. This is backed by a service-level agreement (SLA) of 99.999 percent availability for multi-region writes.

From an implementation perspective, developers interact with Cosmos DB through SDKs available for .NET, Java, Python, Node.js, and Go, as well as through REST APIs. Indexing is automatic by default, meaning every property of every item is indexed without requiring manual schema definitions. The indexing engine uses a prefix-compressed, B-tree structure for efficient queries.

Security is built in with encryption at rest and in transit, firewall support, virtual network service endpoints, and private endpoints. Authentication can be done via master keys, resource tokens, or Azure Active Directory (Azure AD) integration for role-based access control.

## Real-life example

Imagine a global chain of coffee shops called "Cosmo Brew" that has thousands of locations all over the world. Each shop needs to know the current inventory of coffee beans, milk, and cups so that baristas can serve customers immediately. The headquarters in Seattle keeps the master inventory list, but if a barista in Sydney had to ask Seattle every time someone ordered a latte, the wait would be too long. So, Cosmo Brew uses a system where every shop gets a copy of the inventory data that is automatically updated.

This system is exactly how Azure Cosmos DB works. The coffee shops are like data centers in different Azure regions. Each shop can quickly look up its own local copy to serve customers instantly, which represents fast read access. When a shop sells a bag of beans, it updates its local copy, and that change is sent to all other shops. If the change takes a few seconds to reach Tokyo, that is an example of eventual consistency. If the chain demands that no shop can sell the last bag of beans until all shops agree it exists, that is strong consistency.

Now, suppose Cosmo Brew wants to run a promotion on oat milk. They need to query all shops to see which ones are low on oat milk. In a traditional SQL database, they would have to write complex queries with joins across multiple tables. But with Cosmos DB, the inventory data is stored as flexible documents, so the company can simply query the container for documents where oatMilkQuantity is less than 10. The query is fast because every property is automatically indexed.

Finally, the company does not need to worry about hiring database administrators to maintain the servers. Azure handles all the hardware, replication, and scaling automatically. If a new shop opens in Dubai, the IT team simply adds a new Azure region to the Cosmos DB account, and the service replicates all existing data to Dubai in the background without downtime.

## Why it matters

Azure Cosmos DB matters because it solves one of the hardest problems in modern application development: providing fast, reliable data access to users all over the world without requiring developers to manage complex distributed database infrastructure. In a global economy, applications like social media platforms, e-commerce sites, gaming services, and IoT systems must handle requests from every continent. Traditional databases that run in a single data center become slow for distant users and are vulnerable to regional outages.

Cosmos DB eliminates these problems by offering plug-and-play global distribution. A developer can write code once and deploy it to multiple Azure regions, and Cosmos DB automatically keeps the data synchronized. This dramatically reduces latency for end users and increases availability. For example, a gaming company can have its game leaderboard updated in real time from players in North America, Europe, and Asia, all using the same database endpoint.

From a cost and operational perspective, the pay-per-request-unit model means you only pay for the throughput you actually use. There are no large upfront costs, and you can scale down during low-traffic periods to save money. The autoscale option is particularly valuable for applications with variable traffic, such as a news site during a major event.

Security and compliance are also critical reasons why Cosmos DB is important. The service meets a wide range of compliance certifications, including HIPAA, GDPR, ISO 27001, and SOC 1/2/3. This makes it suitable for enterprise applications in healthcare, finance, and government.

Azure Cosmos DB is not just another database. It is a purpose-built solution for cloud-native applications that need global reach, elastic scaling, and multiple data models without operational overhead.

## Why it matters in exams

Azure Cosmos DB appears in several Azure certification exams because it is a flagship service that demonstrates core cloud concepts like global distribution, high availability, and elasticity. The most relevant exams include Microsoft Azure Fundamentals (AZ-900), Microsoft Azure Administrator (AZ-104), Microsoft Azure Developer (AZ-204), and the Azure Data Fundamentals (DP-900). In each of these exams, questions often focus on understanding when to choose Cosmos DB over other data services.

For AZ-900, the exam objectives under "Core Azure Services" include describing Azure database services, and Cosmos DB is frequently contrasted with Azure SQL Database and Azure Database for MySQL. You should know that Cosmos DB is the recommended service for globally distributed, low-latency applications and for workloads that require multiple data models or APIs.

In the AZ-104 exam, the topic falls under "Configure and manage Azure storage and databases." Questions may require you to configure Cosmos DB replication across regions, choose the appropriate consistency level based on a given scenario, or troubleshoot throughput issues involving Request Units. You should be comfortable interpreting scenarios where a company has customers in multiple continents and needs a database with read and write latency under 10 milliseconds.

For the DP-900 exam, which is specifically about data fundamentals, candidates must compare various data storage types, including relational, non-relational (NoSQL), and analytical stores. Cosmos DB is the primary NoSQL example on the Azure platform. You will see questions that ask you to identify the correct use case, such as storing JSON documents for a mobile app or implementing a real-time leaderboard.

The AZ-204 developer exam goes deeper into coding with Cosmos DB SDKs, using change feed to trigger functions, and implementing application-level replication. You might be asked to write code snippets in C# or Python that create a container, insert items, and perform queries with partition keys.

Finally, for the DP-420 exam (Designing and Implementing Native Applications Using Microsoft Azure Cosmos DB), Cosmos DB is the only focus. This exam covers advanced topics like partition strategy, indexing policies, conflict resolution, and SDK best practices.

Question types vary from multiple-choice and multiple-select to case studies and drag-and-drop ordering. Expect scenario-based questions where you must choose the optimal consistency model, identify the correct API for a given use case, or troubleshoot slow queries caused by cross-partition operations.

## How it appears in exam questions

Azure Cosmos DB questions in exams typically fall into three main patterns: scenario selection, configuration choices, and troubleshooting.

In scenario selection questions, you are given a business requirement and asked to choose the most appropriate database service. For example, a company wants to build a global e-commerce platform with users in North America, Europe, and Asia. They need maximum availability and the lowest write latency. The correct answer would be Azure Cosmos DB with multi-region writes. Another common scenario involves an IoT application that generates millions of sensor readings per second. You would select Cosmos DB because it can ingest high-velocity data and handle time-series queries with low latency.

Configuration questions test your knowledge of specific service settings. For instance, you might be asked, "A gaming company wants to ensure that a player's score update is immediately visible to that player, but other players can see the score after a few seconds. Which consistency level should you choose?" The correct answer is Session consistency, because it guarantees read-your-writes for the same session while allowing other sessions to have eventual consistency. Another configuration question might ask about partition key selection: "You are designing a container to store customer orders. Which field is the best partition key?" The answer would be customerId, because it evenly distributes reads and writes across partitions.

Troubleshooting questions often revolve around Request Units. For example, "Your application experiences high latency and throttling errors (HTTP 429) during peak hours. What is the most likely cause?" The answer is that the provisioned RU/s is insufficient, and you need to increase throughput or implement retry logic. Another troubleshooting scenario: "You have a single-region Cosmos DB account, and you need automatic failover in case of a regional outage. What should you do?" The answer is to enable automatic failover by adding a second read region and configuring a priority order.

## Example scenario

A company called "TravelNow" is building a mobile app that helps travelers find last-minute hotel deals worldwide. The app must show available rooms in real time and allow users to book instantly from anywhere. The development team decides to use Azure Cosmos DB as the database backend.

The team creates a Cosmos DB account with multi-region writes enabled for three Azure regions: West US (for North America), West Europe (for Europe), and Southeast Asia (for Asia). They create a database called "HotelBookings" and a container named "Hotels" with a partition key of "/city". Each hotel is stored as a JSON document containing fields like hotelName, city, roomType, price, and availableRooms.

The mobile app uses the Cosmos DB SQL API SDK to query for hotels in a specific city. For example, when a user searches for hotels in Paris, the SDK sends a query to the nearest region, which is West Europe. The query is efficient because the partition key filters by city, so the query only hits the partition for Paris. The response comes back in under 10 milliseconds.

When a user books a room, the app decreases the availableRooms field and writes the update to the local region (West Europe). The change is automatically replicated to West US and Southeast Asia within seconds. Because the team chose Session consistency, the booking user immediately sees the updated availableRooms on their next read, while other users may briefly see the old count until replication completes.

During a major travel event, traffic spikes. The provisioned throughput of 10,000 RU/s becomes insufficient, and some requests get throttled. The team quickly enables autoscale, which increases throughput to 20,000 RU/s automatically, and the app continues to work smoothly. This scenario demonstrates the key benefits of Cosmos DB: global reach, low latency, flexible data modeling, and automatic scaling.

## Common mistakes

- **Mistake:** Choosing Strong consistency for all workloads to avoid any data conflicts.
  - Why it is wrong: Strong consistency reduces availability and increases latency because all copies must be synchronized before each write completes. It also consumes more Request Units per operation, increasing costs. Most applications can tolerate milder consistency levels without issues.
  - Fix: Start with Session consistency, which is the default. Only use Strong consistency for scenarios that require strict ordering, such as financial transactions that must be seen in exact sequence across all users.
- **Mistake:** Using a partition key that results in hot partitions, such as a date or region with uneven distribution.
  - Why it is wrong: If a partition key leads to one partition receiving most of the traffic, that partition becomes a bottleneck. For example, using "/year" as the partition key for a current-year-heavy workload means all reads and writes go to the same partition, causing throttling.
  - Fix: Choose a partition key that distributes read and write operations evenly across partitions. Common good choices include user ID, device ID, or order ID. Test with real data to ensure no single partition exceeds the 20 GB storage limit.
- **Mistake:** Assuming Cosmos DB can store unlimited data in a single partition.
  - Why it is wrong: Each logical partition in Cosmos DB has a maximum storage limit of 20 GB. If your data for a single partition key value (e.g., a very large city) exceeds 20 GB, the container will reject writes or you will experience performance degradation.
  - Fix: Design your partition key so that no single value (like a specific key) approaches the 20 GB limit. For large tenants, consider using a composite partition key or splitting data into multiple containers.
- **Mistake:** Not implementing retry logic in the application when encountering HTTP 429 (rate limiting) errors.
  - Why it is wrong: Cosmos DB SDKs have built-in automatic retry logic, but if you use a custom HTTP client or SDK without retry, throttled requests will fail. This leads to data loss or poor user experience.
  - Fix: Always use the official Azure Cosmos DB SDK for your programming language, and configure retry policy options. For custom implementations, implement exponential backoff retry logic for 429 errors.
- **Mistake:** Believing that Cosmos DB supports all SQL features, like JOINs and complex aggregations, with the same performance as traditional SQL databases.
  - Why it is wrong: Cosmos DB is a NoSQL database optimized for fast single-item reads and writes over specific partition keys. While it does support a SQL-like query language, complex JOINs and multi-document aggregations are expensive and slow because they may cross partitions.
  - Fix: Design your data model to avoid the need for complex JOINs. Store related data together in a single document (denormalization). If aggregations are necessary, consider using the change feed with Azure Functions or a separate analytical store.
- **Mistake:** Assuming that enabling multi-region writes guarantees zero data loss during a regional outage.
  - Why it is wrong: Even with multi-region writes, if a region fails, the most recent writes to that region may not be fully replicated to other regions. Cosmos DB uses asynchronous replication by default, so there is a small window for potential data loss (usually within a few seconds).
  - Fix: Understand the difference between RPO (Recovery Point Objective) and RTO (Recovery Time Objective). For zero data loss, consider using multi-region writes with Strong consistency, but be aware of the higher cost and latency trade-offs.
- **Mistake:** Not setting up indexes on frequently queried fields and assuming automatic indexing covers everything.
  - Why it is wrong: Automatic indexing indexes every property of every document, which is fine for most cases. But if you have very large documents or very specific query patterns, the automatic index may be too broad, leading to higher RU costs.
  - Fix: Review the indexing policy and customize it by excluding infrequently queried fields or by using composite indexes for queries that filter on multiple fields. Use the Azure portal or SDK to analyze query execution and optimize indexing.

## Exam trap

{"trap":"An exam scenario describes a company that needs a globally distributed database with the ability to query data using SQL syntax. The first option is Azure SQL Database, and the second is Azure Cosmos DB. Many learners choose Azure SQL Database because it supports SQL.","why_learners_choose_it":"Learners see the word 'SQL' and immediately think of Azure SQL Database, which is a traditional relational database. They forget that Cosmos DB also supports a SQL API for querying JSON documents and is designed for global distribution, whereas Azure SQL Database is not natively multi-region.","how_to_avoid_it":"Read the question carefully for keywords like 'globally distributed,' 'multi-region reads and writes,' or 'low latency across continents.' If those are present, Cosmos DB is almost always the correct choice, even if SQL querying is mentioned. Also remember that Azure SQL Database can be geo-replicated, but it does not offer the same automatic multi-write capabilities as Cosmos DB."}

## Commonly confused with

- **Azure Cosmos DB vs Azure SQL Database:** Azure SQL Database is a fully managed relational database (SQL Server engine) designed for structured data with a fixed schema. Azure Cosmos DB is a NoSQL database with a flexible, schema-agnostic data model. SQL Database is best for transactional relational workloads where schema consistency is critical; Cosmos DB is best for globally distributed, high-throughput, low-latency applications with varying data structures. (Example: If you need to store bank account balances with strict referential integrity and allow SQL joins, use Azure SQL Database. If you need to store user profiles with variable fields for a global social media app, use Cosmos DB.)
- **Azure Cosmos DB vs Azure Table Storage:** Azure Table Storage is a simpler, cheaper NoSQL key-value store that is part of Azure Storage accounts. It has a limited API, no global distribution (only geo-redundant storage), and slower performance compared to Cosmos DB. Cosmos DB's Table API provides higher throughput, lower latency, and global distribution, but at a higher cost. (Example: If you are building a small app with low traffic and need a cheap key-value store, use Table Storage. For a production-grade app requiring global data access and high throughput, use Cosmos DB with the Table API.)
- **Azure Cosmos DB vs Amazon DynamoDB:** DynamoDB is the AWS equivalent of a globally distributed NoSQL database. Both services offer similar features like key-value and document data models, automatic scaling, and low latency. The main difference is ecosystem: Cosmos DB is native to Azure with tight integration with other Azure services, while DynamoDB is tightly integrated with AWS. Cosmos DB also offers multiple API options (MongoDB, Cassandra, Gremlin), which DynamoDB does not. (Example: If your entire cloud infrastructure is in AWS, use DynamoDB. If you are in Azure or need support for multiple data models like graph or Cassandra, choose Cosmos DB.)
- **Azure Cosmos DB vs Azure Cache for Redis:** Azure Cache for Redis is an in-memory data store used primarily for caching to improve application performance by storing frequently accessed data. It is not a durable database by default and does not offer global distribution with automatic replication. Cosmos DB is a fully durable, globally distributed database that stores data persistently and can handle both reads and writes across regions. (Example: Use Redis to cache a Cosmos DB query result to reduce latency for repeated queries. Use Cosmos DB as the authoritative data source for permanent storage.)
- **Azure Cosmos DB vs MongoDB Atlas:** MongoDB Atlas is a managed NoSQL database service from MongoDB, Inc., not from Microsoft. It offers global replication and a document data model similar to Cosmos DB's MongoDB API. However, Cosmos DB is integrated into the Azure ecosystem and allows you to use multiple APIs (SQL, Gremlin, Cassandra) on the same account, which MongoDB Atlas does not. (Example: If you need to run existing MongoDB applications in Azure, you can use Cosmos DB's MongoDB API without changing code. If you prefer the native MongoDB platform and tools, use MongoDB Atlas.)

## Step-by-step breakdown

1. **Create an Azure Cosmos DB Account** — In the Azure portal, you create a new Cosmos DB account. You choose the API (SQL, MongoDB, Cassandra, Gremlin, or Table), the location(s) for initial deployment, and whether to enable multi-region writes. This account is the top-level management unit.
2. **Choose the Consistency Level** — You select a default consistency level for the account, which can be overridden per request. The options are Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual. The default is Session. This choice affects performance, availability, and data staleness.
3. **Create a Database and a Container** — Inside the account, you create a database. Within the database, you create one or more containers. Each container has a partition key (e.g., /userId) and is provisioned with throughput (RU/s). The container is where your data items live.
4. **Partition Key Selection and Data Distribution** — You define the partition key at container creation. Azure Cosmos DB uses this key to distribute data across underlying physical partitions. A good partition key evenly distributes both storage and throughput. Avoid hot partitions by choosing high-cardinality keys like user IDs or order IDs.
5. **undefined** — Through the SDK (e.g., .NET, Java), you create items (JSON documents) and insert them into the container. Queries are written using SQL-like syntax or the API's native query language. The partition key is included in most queries for efficiency.
6. **Configure Global Distribution** — You add new Azure regions to the Cosmos DB account via the portal or CLI. Data is automatically replicated to all added regions. You can enable multi-region writes to allow low-latency writes from any region. Regions can be added or removed without downtime.
7. **Monitor and Scale Throughput** — You monitor RU consumption using Azure Monitor metrics. If throttling occurs (HTTP 429), you increase RU/s manually or enable autoscale. Autoscale adjusts throughput based on demand, but you pay for the last scaled-up level. Monitoring helps optimize costs.
8. **Implement Security and Access Control** — You secure the account using master keys, resource tokens, or RBAC with Azure AD. You configure firewall rules and virtual network service endpoints. All data is encrypted at rest and in transit by default.
9. **Use Change Feed for Event-Driven Architectures** — You can enable the change feed on a container to capture all inserts and updates in the order they occur. This feed can be consumed by Azure Functions, Azure Logic Apps, or custom processors to trigger downstream actions like refreshing a cache or updating an analytic store.
10. **Backup and Restore or Failover Testing** — Active backups are automated with point-in-time restore (within a 30-day window). You can test failover by simulating a regional outage through the Azure portal. Understanding RPO and RTO under different consistency levels is critical for exam success.

## Practical mini-lesson

When working with Azure Cosmos DB in a real enterprise environment, one of the first things professionals must understand is the Request Unit (RU) model. Every database operation consumes a certain number of RUs, which is essentially your budget for database resources. If you exceed your provisioned RU/s, the service throttles your requests with a 429 status code. This is not a bug; it is a deliberate design to protect the service from being overwhelmed. In practice, you must monitor metrics like "Max RU/s consumption per partition" and adjust provisioning accordingly.

A common operational task is selecting the right partition key. One e-commerce company initially chose "category" as the partition key for their product catalog. This caused a hot partition because the "Electronics" category had millions of items and high read/write traffic, while other categories like "Gardening" had very few. The solution was to change the partition key to "productId", which provided a much more even distribution. Partition key selection cannot be changed after container creation, so it must be carefully planned during the design phase.

Another practical consideration is handling cross-region failover. If you have a multi-region account and a region goes down, the service automatically redirects traffic to the next available region based on priority. However, if you are using multiple write regions, you might face conflict resolution issues. Cosmos DB uses last-writer-wins (LWW) by default based on a timestamp, but you can define custom conflict resolution policies, such as using a stored procedure. In mission-critical apps like financial trading, you must test this behavior thoroughly.

SDK best practices include using direct connectivity mode (instead of gateway mode) for lower latency, enabling connection pooling, and only using singleton instances for the SDK client to avoid exhausting resources. Also, always specify the partition key in queries to keep them efficient. Queries without a partition key result in a full scan across all partitions (fan-out), which can be very expensive in terms of RU consumption.

Finally, consider cost management. Cosmos DB pricing is based on provisioned throughput (RU/s) and storage (GB). You can reduce costs by using autoscale to handle spikes without over-provisioning, or by reserving capacity with Reserved Capacity for a 30-60% discount. Also, you can set time-to-live (TTL) on documents to automatically delete stale data, reducing storage costs. Professionals must continuously review query performance using the Azure portal's query insights and adjust indexing or data modeling to reduce RU consumption.

## Commands

```
az cosmosdb create --name mycosmosdbaccount --resource-group myResourceGroup --kind GlobalDocumentDB --default-consistency-level Eventual
```
Creates a new Azure Cosmos DB account with the GlobalDocumentDB API and Eventual consistency. Use for initial account setup.

*Exam note: Tests understanding of consistency levels (Eventual, Strong, Session, etc.) and the --kind parameter. Exam questions often ask which parameter sets the API type.*

```
az cosmosdb sql database create --account-name mycosmosdbaccount --resource-group myResourceGroup --name mydatabase --throughput 400
```
Creates a SQL API database with dedicated throughput of 400 RU/s. Use when provisioning a new database with specific performance needs.

*Exam note: Exams test the concept of throughput (RU/s) at database vs. container level. Also tests the difference between shared and dedicated throughput.*

```
az cosmosdb sql container create --account-name mycosmosdbaccount --resource-group myResourceGroup --database-name mydatabase --name mycontainer --partition-key-path "/id" --throughput 1000
```
Creates a container with a partition key on the 'id' path and 1000 RU/s throughput. Essential for defining data distribution.

*Exam note: Partition key selection is a major exam topic. Questions test why certain paths are chosen (e.g., /id vs. /category) and impact on performance.*

```
az cosmosdb update --name mycosmosdbaccount --resource-group myResourceGroup --default-consistency-level Strong
```
Updates an existing Cosmos DB account to Strong consistency. Use when global consistency is required.

*Exam note: Exams focus on consistency trade-offs: Strong provides highest consistency but increases latency. Often compared with other levels like Bounded Staleness.*

```
az cosmosdb sql container throughput migrate --account-name mycosmosdbaccount --resource-group myResourceGroup --database-name mydatabase --name mycontainer --throughput-type autoscale
```
Migrates container throughput from manual to autoscale. Use to handle variable workloads without manual scaling.

*Exam note: Tests knowledge of autoscale vs. manual throughput. Exam questions ask about cost optimization and automatic scaling scenarios.*

```
az cosmosdb keys list --name mycosmosdbaccount --resource-group myResourceGroup --type primary-readonly
```
Lists the primary read-only key for the Cosmos DB account. Use for application access with read-only permissions.

*Exam note: Exams test understanding of key types (primary, secondary, read-only) and their security implications. Often asked in context of least privilege access.*

```
az cosmosdb sql container show --account-name mycosmosdbaccount --resource-group myResourceGroup --database-name mydatabase --name mycontainer --query 'partitionKey'
```
Displays the partition key configuration of a container. Use for auditing or verifying partition strategy.

*Exam note: Partition key management is critical. Exam questions may ask how to retrieve or verify partition key settings.*

## Troubleshooting clues

- **High request unit consumption** — symptom: Queries return slowly or hit rate limits, even with moderate traffic.. Inefficient queries or lack of proper indexing cause excessive RU consumption. For example, cross-partition scans can consume many RUs. (Exam clue: Exams test diagnosing high RU consumption by asking which indexing policy or query pattern is inefficient.)
- **Partition hot-spotting** — symptom: Some partitions experience high throughput while others are idle, leading to throttling on hot partitions.. Poor partition key selection (e.g., using a date or a value with low cardinality) causes uneven data distribution. (Exam clue: Questions present a scenario with uneven load and ask to identify the partition key issue or recommend a better key.)
- **Consistency level not meeting requirements** — symptom: Read operations return stale data even though Strong consistency was expected.. The account-level consistency may be set lower (e.g., Eventual) and not overridden at the client. Default consistency applies unless client requests higher. (Exam clue: Exams test the interaction between account-level and client-level consistency levels and the effects of not using Strong when needed.)
- **Stale data after multi-region writes** — symptom: Data written in one region is not immediately visible in another region during active conflict.. Cosmos DB uses conflict resolution policies (e.g., last-writer-wins) and asynchronous replication. Conflicts can occur during multi-region writes. (Exam clue: Questions test understanding of conflict resolution modes and how to handle eventual consistency in multi-region setups.)
- **Indexing policy ignored or not applied** — symptom: Queries that should use an index still scan all documents, causing slow performance.. The indexing policy might be set to 'none' for certain paths, or the index is not rebuilt after changes. Default indexing includes all paths but custom exclusions can cause issues. (Exam clue: Exams ask about indexing policy properties (e.g., includedPaths, excludedPaths) and their impact on query performance.)
- **Scalability limits reached** — symptom: Cannot increase throughput beyond 100,000 RU/s per container or 1,000,000 RU/s per account.. Cosmos DB has hard limits per container and account. Exceeding requires partitioning data into multiple accounts or using partition key overrides. (Exam clue: Questions test knowledge of throughput limits and how to architect for high-scale applications.)
- **Duplicate documents in change feed** — symptom: Applications processing change feed see the same document updates multiple times.. Change feed can deliver 'at least once' semantics. Duplicates can occur due to retries or partition splits. It's idempotent processing requirement. (Exam clue: Exams test understanding of change feed guarantees and how to handle duplicates in event-driven architectures.)
- **Write operations fail with 403 error** — symptom: Write attempts return HTTP 403 (Forbidden) on certain partitions.. Often due to throttling at the partition level, or the account is set to read-only mode in that region. Also can be caused by expired auth keys. (Exam clue: Questions present a 403 error and ask to diagnose whether it's throttling, permissions, or consistency issue.)

## Memory tip

Remember "CRUD and Global": Cosmos DB handles Create, Read, Update, Delete operations with global replication and multiple API choices. Also, "5 C's" for consistency: Strong, Bounded Staleness, Session, Consistent Prefix, Eventual.

## FAQ

**What is the difference between Cosmos DB's SQL API and the MongoDB API?**

The SQL API uses a custom SQL-like query language over JSON documents, while the MongoDB API uses the MongoDB wire protocol with native MongoDB query syntax. Both store data as documents, but the SQL API is Microsoft-specific, whereas the MongoDB API is compatible with existing MongoDB applications.

**How many consistency levels does Azure Cosmos DB offer?**

Azure Cosmos DB offers five consistency levels: Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual. Session is the default and the most commonly used for web and mobile apps.

**Can I change the partition key of a container after it is created?**

No, the partition key is specified at container creation time and cannot be changed later. You must create a new container with a different partition key and migrate the data.

**What is a Request Unit (RU) and how is it calculated?**

A Request Unit is a normalized measure of the cost of a database operation. It factors in CPU, memory, and I/O consumption. For example, a 1 KB item read costs 1 RU, while a complex query may cost 10 RU or more. The cost depends on item size, query complexity, and indexing.

**Is Azure Cosmos DB ACID compliant?**

Cosmos DB supports multi-document ACID transactions within a single logical partition (in the SQL API) using stored procedures, but it is not ACID compliant across partitions. For global transactions, you need application-level compensation logic.

**What happens if my throughput exceeds the provisioned RU/s?**

Requests will be throttled, and the service returns HTTP status code 429 (Too Many Requests). The SDKs have built-in retry logic that pauses and retries. To avoid throttling, you can increase RU/s or enable autoscale.

**How does change feed work in Cosmos DB?**

The change feed is a persistent log of document inserts and updates in the order they occur. You can read it using the SDK or Azure Functions. It is useful for triggering post-processing like syncing a cache or updating a search index.

**Can I use Azure Active Directory (AD) to authenticate with Cosmos DB?**

Yes, Cosmos DB supports RBAC via Azure AD for the control plane and data plane. You can assign roles like Cosmos DB Account Reader or Cosmos DB Data Contributor to users and service principals.

## Summary

Azure Cosmos DB is a globally distributed, multi-model NoSQL database service from Microsoft Azure that is designed for modern cloud applications that require low latency, high availability, and elastic scaling. It abstracts away the complexity of managing a distributed database system, allowing developers to focus on building features rather than infrastructure. The service supports multiple APIs, including SQL, MongoDB, Cassandra, Gremlin, and Table, which means you can bring existing code and skills without needing to learn a completely new query language.

One of the most powerful aspects of Cosmos DB is its flexible consistency model, with five options that let you balance between data accuracy and performance. Session consistency is the sensible default for most applications, guaranteeing read-your-writes within a user's session while keeping latency low. For scenarios that demand absolute correctness, Strong consistency provides it at the cost of higher latency and reduced availability.

For certification exams, you must understand the core concepts: global replication, partition keys, Request Units, and when to choose Cosmos DB over other data services such as Azure SQL Database, Table Storage, or Redis. Recognize the typical scenario patterns: global applications with users distributed worldwide, IoT ingestion, real-time leaderboards, and mobile backends. Avoid common mistakes like choosing a poor partition key, over-provisioning consistency, or ignoring throttling issues.

In practice, professionals must plan capacity carefully, monitor RU consumption, and design data models that minimize cross-partition queries. Security features like encryption, firewall, and RBAC must be configured according to enterprise standards. Ultimately, Azure Cosmos DB is a cornerstone of the Azure data ecosystem, and mastering it will serve you well in both exams and real-world cloud development.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/azure-cosmos-db
