# Cosmos DB API

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

## Quick definition

Cosmos DB API is how your application talks to Azure Cosmos DB, a cloud database that spreads data around the world for fast access. It lets you use familiar tools like SQL, MongoDB, or Cassandra to work with your data, without learning a completely new system. Think of it as a translator that converts your requests into commands the database understands.

## Simple meaning

Imagine you want to order food from a restaurant that serves many cuisines. You can speak English to the waiter, but the kitchen staff might speak Italian, Japanese, or French. The waiter (the API) translates your order into the language the kitchen understands, then brings back your food. In the same way, Cosmos DB API translates the requests from your application-like “find all users older than 30”-into a language that Azure Cosmos DB can process. The magic is that this database can store data in many formats, like documents, key-value pairs, or graphs, and the API helps you pick the right format for your project.

Azure Cosmos DB is a special cloud database that can copy your data to servers all over the world. If your app has users in New York, London, and Tokyo, each user gets fast responses because the data is close to them. The API is the tool that makes all of this possible without you having to manage the complexity. It provides different “versions” of itself, each matching a popular database style: SQL (for structured queries), MongoDB (for flexible documents), Cassandra (for wide-column data), Gremlin (for graphs), and Table (for simple key-value storage). This means if you already know MongoDB, you can use that API and Cosmos DB will behave just like MongoDB but with added global distribution.

When you use the SQL API, you write queries like “SELECT * FROM Users WHERE age > 30” and get results back in JSON format. The API handles authentication, routing your request to the nearest data center, and even adjusting for failures. If you use the MongoDB API, your code using MongoDB drivers works almost unchanged, but behind the scenes, Cosmos DB is managing the data across continents. This flexibility is why Cosmos DB is popular for apps that need to scale globally, like social media platforms or IoT systems that collect data from devices worldwide.

A key idea is that the API does not just pass messages; it also manages consistency. Cosmos DB lets you choose how strongly your data is synchronized across regions. You can wait for every copy to agree (strong consistency) or accept a tiny delay for faster performance (eventual consistency). The API makes these settings available through configuration, so your application gets exactly the behavior it needs.

Cosmos DB API is the intermediary that lets you talk to a powerful, globally distributed database using the language and tools you already know. It hides the complexity of replication, routing, and consistency, so you can focus on building your application.

## Technical definition

Azure Cosmos DB API refers to the set of protocol-level interfaces and SDKs that enable client applications to interact with the Azure Cosmos DB service. Cosmos DB is a fully managed, globally distributed, multi-model database service designed for low-latency, high-throughput scenarios. The API abstraction layer allows developers to use one of several supported data models and query interfaces: SQL (core API), MongoDB API, Cassandra API, Gremlin API, Table API, and the recently added PostgreSQL API (via CockroachDB compatibility). Each API maps the Cosmos DB storage engine, which uses a schema-agnostic, index-optimized structure called the “Atom-Record-Sequence” (ARS) format, to the wire protocol and query syntax of the target database system.

At the core, all API implementations translate requests into the Cosmos DB SQL query dialect or direct point-read/write operations on the underlying partition-based storage engine. The storage engine organizes data into logical partitions, each replicated across a set of physical replicas within a region and across regions for geo-redundancy. The API layer handles authentication via either master keys (primary/secondary) or Azure Active Directory tokens, resource tokens for fine-grained access, and connection management through direct mode or gateway mode. In direct mode, the client opens TCP connections directly to backend replicas, bypassing the gateway for lower latency. In gateway mode, all requests go through a front-end gateway that routes them, which is simpler but may add latency.

For the SQL API, the query language is a subset of T-SQL with extensions for JSON documents. Queries support joins, subqueries, arrays, and user-defined functions (UDFs). The SQL API is the native interface and supports stored procedures, triggers, and user-defined functions written in JavaScript, executed within the transactional engine. The MongoDB API implements the MongoDB wire protocol (version 4.0 at parity, with 5.0 features in preview), allowing existing MongoDB drivers to connect with minimal changes. It translates MongoDB query operators (like $match, $group) into Cosmos DB internal operations. The Cassandra API provides a CQL (Cassandra Query Language) interface, supporting partition keys, clustering columns, and Cassandra-specific features like lightweight transactions (using QUORUM consistency). The Gremlin API supports the Apache TinkerPop graph traversal language for graph data. The Table API provides a REST-based interface compatible with Azure Table Storage, for key-value data.

Cosmos DB offers five well-defined consistency levels: strong, bounded staleness, session, consistent prefix, and eventual. The API includes headers or client options to specify the desired consistency for each request. The global distribution model means each write operation is replicated to all configured regions, and the API automatically routes read requests to the nearest region based on the client’s location, using geo-routing logic. The API also supports multi-region writes (multi-master), where conflicts are resolved via last-writer-wins or custom conflict resolution policies.

The SDKs (available for .NET, Java, Python, Node.js, Go, and others) wrap the API with higher-level constructs like containers, items, and change feed. The change feed is a persistent log of changes that enables event-driven architectures, accessible via the API. The API ensures that operations are atomic at the document level, and throughput is provisioned at the container or database level using Request Units per second (RU/s). When a request exceeds provisioned throughput, the API returns a 429 status code (rate limiting), and the SDK can automatically retry with exponential backoff.

In enterprise IT implementations, Cosmos DB API is used for real-time analytics, IoT telemetry ingestion, e-commerce catalogs, gaming state management, and AI-driven applications. The API’s multi-model capability reduces the need for multiple database systems, and its global distribution simplifies disaster recovery and data residency compliance. Understanding how the API translates between the wire protocol and the internal engine is essential for designing cost-effective, high-performance solutions.

## Real-life example

Think of Cosmos DB API like a universal power adapter you take when traveling abroad. You have a laptop with a standard plug, but every country has different wall sockets: two round pins in Europe, three flat pins in the UK, two flat pins in the US, and so on. The adapter changes the physical shape of your plug so it fits the local socket. But the adapter does not change the electricity itself-the voltage and frequency are handled separately by your laptop’s power supply.

In this analogy, your laptop application is the client, and the local electric socket is Azure Cosmos DB. The API (the adapter) converts your application’s specific database language into the format that Cosmos DB accepts. If your app speaks MongoDB, the MongoDB API acts like a plug adapter that makes the MongoDB connection fit into Cosmos DB. If your app speaks SQL, the SQL API is the adapter for that. The beauty is that you do not need to replace your laptop or the wall socket; you just change the adapter.

Now, imagine you travel to multiple countries in one day. Instead of carrying a separate adapter for each country, you have a universal adapter that works everywhere. Cosmos DB is that universal adapter: it has multiple APIs built in, so your app can use any supported protocol without changing the underlying database. The database stores data in its native format, and the API translates on the fly.

But there is more. Cosmos DB also acts like a high-speed rail network for data. If you have users in many countries, the rail system (the global distribution layer) makes sure copies of your data are stored in each country. The API (the ticket office) knows where the nearest copy of your data is, and it directs your request to that location. If the rail line to one city is down, the ticket office automatically sends your request to another city, so you still get your data quickly. This happens in milliseconds, and you do not even notice.

Finally, think about how consistency works. If you order a coffee in Paris and then fly to Tokyo, you want to see the same order history on your phone. The API ensures that the coffee shop in Paris and Tokyo agree on the order. Depending on the consistency level you choose, you might wait a few seconds for all shops to agree (strong consistency) or accept that Tokyo might show the order a bit later (eventual consistency). The API gives you control over this balance between speed and accuracy.

## Why it matters

Cosmos DB API matters because it determines how you architect, develop, and maintain applications that require global scale and low latency. In modern IT, businesses expect applications to serve users across the world with consistent performance. Cosmos DB provides that global distribution, but without the API, developers would need to write custom code to handle replication, geo-routing, and consistency. The API abstracts all of that complexity, enabling you to focus on business logic.

From an operational perspective, the API influences cost. Provisioned throughput is measured in Request Units (RU), and different API operations consume different numbers of RUs. For example, a point read (retrieving a single document by ID and partition key) costs far fewer RUs than a complex query that scans multiple partitions. Choosing the right API and writing efficient queries directly impacts your monthly bill. Professionals must understand how each API translates query operations into RU consumption to optimize costs.

the API choice affects portability. If you use the MongoDB API, you can later move your application to a real MongoDB instance with minimal code changes. Similarly, the Cassandra API offers compatibility with open-source Cassandra. This flexibility reduces vendor lock-in and allows hybrid cloud strategies. In enterprise environments, this can be a critical factor when evaluating cloud services.

Security also ties to the API. Authentication methods differ per API, with master keys, resource tokens, and AAD integration. The API exposes these security mechanisms, and misconfiguration can lead to data breaches. For example, hardcoding master keys in source code is insecure; the API allows using managed identities for secure access.

Finally, the API enables advanced features like change feed (for event-driven architectures) and multi-region writes. These features power real-time data pipelines, caching invalidation, and global active-active deployments. Without the API, you cannot use these capabilities. In short, the API is not just a communication layer; it is the gateway to Cosmos DB’s full power.

## Why it matters in exams

Cosmos DB API appears across several Azure certification exams, including AZ-900 (Azure Fundamentals), DP-900 (Azure Data Fundamentals), and AZ-104 (Azure Administrator). For AZ-900 and DP-900, you need to know the different APIs available, what data models they support, and basic scenarios for when to use each. You should be able to identify that the SQL API is for document data with SQL queries, the MongoDB API is for migrating existing MongoDB apps, the Cassandra API is for wide-column data, the Gremlin API is for graphs, and the Table API is for key-value storage. Expect multiple-choice questions that ask, “Which API should you use for a graph database application?” or “Which API provides compatibility with MongoDB?”

For AZ-104, the exam might cover the API in the context of configuring Cosmos DB accounts, choosing consistency levels, and understanding throughput provisioning. You may need to know how the API affects replication settings, such as multi-region writes requiring the SQL or MongoDB APIs. Questions may present a scenario where a company needs global distribution with strong consistency and ask which API supports that. You also need to know that only the SQL API supports stored procedures, triggers, and UDFs.

For DP-900 specifically, the exam objectives include describing the capabilities of Cosmos DB APIs. You should understand that each API uses a different wire protocol and that the choice of API is made when creating the Cosmos DB account and cannot be changed later. Questions often compare APIs: “You need to store time-series sensor data with a partition key. Which API and consistency level?” The exam also tests knowledge of the change feed and which APIs support it (SQL and MongoDB APIs).

In higher-level exams like DP-420 (Azure Cosmos DB Developer Specialty), the API is deeply tested. You are expected to code against the SDK, understand request unit (RU) charges for different API operations, implement change feed processors, and configure multi-region writes. However, for the foundational and associate-level exams, the focus is on selection and basic understanding.

Common question types include: definition matching (match API to data model), scenario-based (choose the API for a given workload), and true/false about API capabilities (e.g., “The Cassandra API supports stored procedures” is false). The exams also ask about consistency levels available for each API (all APIs support all five levels). Mastering these points can secure easy points on the test.

## How it appears in exam questions

Exam questions test Cosmos DB API through multiple patterns. The first pattern is definition-based. For example: “Which Cosmos DB API supports a graph data model?” The answer is Gremlin API. Another: “Which API provides compatibility with the MongoDB wire protocol?” That is the MongoDB API. These are straightforward if you memorize the mapping.

The second pattern is scenario-based. A typical question: “A company wants to migrate an existing MongoDB application to Azure without changing the application code. Which Cosmos DB API should they use?” The answer is the MongoDB API. Another: “You are building an IoT solution that stores simple key-value pairs with high throughput. Which API is most cost-effective?” That is the Table API, because it offers lower RU costs per operation compared to the SQL API for simple lookups.

The third pattern is configuration and limitations. For instance: “You need to use stored procedures in Cosmos DB. Which API must you use?” The SQL API is the only one that supports server-side programming. Another: “You are creating a new Cosmos DB account. Can you change the API after creation?” No, the API is chosen at creation and is immutable.

The fourth pattern is performance and cost. Questions may give a scenario with a specific query and ask how many RU/s to provision. For example: “A container has 10,000 documents and a query filters on a non-indexed field. How does the API handle this?” The API will perform a full scan, consuming more RUs. The exam tests understanding of indexing and query efficiency.

The fifth pattern is consistency levels. Questions might ask: “You need all reads to return the latest write, but with lower latency. Which consistency level?” Bounded staleness. Or: “You are using multi-region writes with the MongoDB API. Which conflict resolution modes are available?” Last-writer-wins and custom.

Finally, troubleshooting questions appear in administrator exams (AZ-104). Example: “Users report slow reads from a Cosmos DB account with global distribution. Which API settings should you check?” Geo-routing configuration, consistency level, and whether the client SDK is using direct mode or gateway mode.

## Example scenario

A retail company runs an e-commerce website with customers in North America, Europe, and Asia. They need a product catalog that loads quickly for all users. The catalog contains product names, descriptions, prices, and images, stored as JSON documents. The development team decides to use Azure Cosmos DB with the SQL API because they are familiar with SQL queries and need to support complex searches like “find all electronics under $50 with at least 4-star ratings.”

They create a Cosmos DB account with the SQL API and one container called “Products.” Each product document has an ID, category, price, and rating. They set the partition key to “/category” to evenly distribute data across partitions. They configure two read regions: West US and West Europe, and one write region in East US.

When a customer in Germany searches for “electronics,” their browser sends a request to the API. The Cosmos DB SDK automatically routes the request to the West Europe region because it is closest. The API translates the query “SELECT * FROM Products WHERE category = ‘electronics’ AND price < 50 AND rating > 4" into internal operations. It retrieves the matching documents, and the response is sent back in milliseconds. The customer sees the results instantly.

Meanwhile, a new product is added by an admin in the US. The write goes to East US, and the API replicates the new document to the West US and West Europe regions. Because they chose session consistency, the admin sees the new product immediately, but the German customer might see it a few seconds later. This trade-off ensures fast write throughput.

If the East US region experiences an outage, the API automatically fails over the write operations to the West US region, ensuring the catalog remains writable. The API handles all of this complexity, allowing the retail team to focus on building the storefront rather than managing infrastructure.

## Azure Cosmos DB API Request Units (RU/s) and Throughput Provisioning

Azure Cosmos DB is a fully managed NoSQL database service that provides turnkey global distribution, elastic scaling of throughput and storage, and single-digit millisecond latencies at the 99th percentile. At the heart of Cosmos DB's performance and cost model lies the concept of Request Units (RUs). A Request Unit is a normalized measure of the computational resources required to perform a database operation, including CPU, memory, and IOPS. Each operation – whether a read, write, query, or stored procedure execution – consumes a certain number of RUs. Understanding RU consumption is critical for optimizing performance and controlling costs.

When you provision throughput on a Cosmos DB container (or database), you specify a number of RU per second (RU/s). Cosmos DB guarantees that the provisioned throughput will be available for your operations. For example, if you set 10,000 RU/s on a container, Cosmos DB will ensure that up to 10,000 RUs of operations per second can be executed without throttling. If you attempt to exceed the provisioned throughput, Cosmos DB will return HTTP 429 (Too Many Requests) errors. This throttling mechanism protects the service's performance guarantees for all customers, but it requires careful capacity planning.

The actual RU cost of an operation depends on several factors: the size of the item (document), the number of properties accessed, the complexity of the query (especially index usage), and the consistency level. A point read (fetching a single item by its partition key and ID) is the cheapest operation, typically costing 1 RU for a 1KB item. Queries that scan multiple partitions or perform cross-document joins can cost hundreds or thousands of RUs. Indexing every property by default (the Cosmos DB default) increases RU costs for write operations but reduces RU costs for read queries, as the index is used to serve the query.

Exam-relevant considerations include: the difference between manual and autoscale throughput (autoscale allows a range 10% to 100% of max RU/s and is cost-effective for variable workloads); the fact that you can provision throughput at the database level (shared among containers) or container level (dedicated); and the impact of choosing a partition key. A bad partition key (e.g., one that leads to hot partitions) causes uneven RU consumption and can throttle the entire container even if total RU/s is adequate. Microsoft exams such as DP-900 and AZ-104 frequently test the RU model, throttling behavior, and the need to monitor normalized RU consumption metrics.

Finally, cost optimization in Cosmos DB is heavily tied to RU provisioning. Over-provisioning leads to wasted spend, while under-provisioning degrades performance. The recommended approach is to start with autoscale for most workloads, monitor the max consumed RU/s via Azure Monitor metrics, and adjust manually once the pattern is clear. Using Azure Cosmos DB free tier (1000 RU/s and 25 GB storage free) is a common exam scenario for small-scale solutions.

## Cosmos DB API Consistency Levels and Trade-offs for Global Distribution

Azure Cosmos DB offers five well-defined consistency levels that allow developers to balance between data consistency, availability, and latency. These levels are Strong, Bounded Staleness, Session, Consistent Prefix, and Eventual. Understanding when to choose each level is a key topic in Azure certification exams, especially the DP-900 and AZ-104.

Strong consistency guarantees that a read operation always returns the most recent write. This means that after a write is acknowledged, any subsequent read will see that write, regardless of the region from which the read is performed. However, Strong consistency requires quorum confirmation from replicas across multiple regions, which increases latency and reduces availability in the event of a regional outage. It also imposes a performance cost because all replicas must commit before the write is acknowledged. This level is appropriate for financial transactions or inventory systems where absolute correctness is required.

Bounded Staleness offers a middle ground: reads are guaranteed to be within a configurable window of staleness, either a certain number of operations (K) or a time interval (T). For example, you can configure staleness to be at most 100 operations or 5 seconds, whichever comes first. This ensures that the data you read is almost up to date, while providing better performance and availability than Strong. This is commonly used in leaderboard or analytics applications where slightly stale data is acceptable.

Session consistency is the default level for Cosmos DB and is scoped to a user session (identified by a session token). It guarantees monotonic reads, monotonic writes, read-your-writes, and write-follows-reads within a single session. This means that if a user writes a document, their subsequent reads will see that write. However, other users or sessions may see older versions until the session token is shared. Session is ideal for applications where each user has a consistent view of their own data, such as a shopping cart or user profile.

Consistent Prefix guarantees that reads never see out-of-order writes – if writes occur in sequence A, B, C, a read will see A, then A and B, then A, B, and C, but never B without A or C without B. This is useful for feed or event sourcing systems. Eventual consistency offers no ordering guarantees and is the weakest level, but provides the highest performance and lowest latency. It is suitable for product recommendations, social media feeds, or any scenario where staleness is tolerable.

From an exam perspective, you must understand that each level has a trade-off against the SLA: Cosmos DB offers 99.999% read availability for all consistency levels weaker than Strong, and 99.99% for Strong. Also, consistency level can be set at the account level and overridden per request using headers. The DP-900 exam specifically tests the ability to recommend the appropriate consistency level based on business requirements.

## Cosmos DB API Multi-Region Writes and Conflict Resolution

Azure Cosmos DB supports global distribution, allowing you to replicate your data across any number of Azure regions with just a few clicks or configuration lines. One of the most powerful features is the ability to enable multi-region writes, meaning you can write to any region and those writes are automatically replicated to all other regions. This is ideal for globally distributed applications that require low-latency writes everywhere.

When multi-region writes are enabled, Cosmos DB uses a conflict resolution protocol. Since writes can happen concurrently in different regions, conflicts can arise when two writes modify the same document simultaneously. Cosmos DB provides automatic conflict resolution via two built-in policies: Last Writer Wins (LWW) and Custom (using a stored procedure). LWW uses a timestamp (or a custom property you define) to accept the most recent write and discard the older one. The custom policy allows you to run a stored procedure that merges conflicts based on your application logic; for example, merging two different property updates into a single document.

To configure multi-region writes, you must enable it on the Cosmos DB account (this cannot be undone after enabling). You also need to set the account to 'multi-master' mode, which changes the behavior of write acknowledgments. With multi-master, a write to any region is considered committed locally and then asynchronously replicated. This means there is no single master that can become a bottleneck. However, consistency levels become more nuanced – Strong consistency is not supported with multi-region writes because the coordination across regions would be too slow.

From a cost and performance perspective, multi-region writes increase write throughput costs because each write is replicated to all other regions (consuming RUs in each region). But it provides the best possible write latency for users worldwide. This is commonly tested in the AZ-104 and AWS cloud practitioner exams when comparing against Amazon DynamoDB global tables.

Troubleshooting issues: Common symptoms include high conflict rates when using LWW with non-ideal timestamp attributes, or unexpected write conflicts when using stored procedures that have bugs. Also, enabling multi-master requires careful planning around partition keys that might cause hot spots across regions. Exam questions often ask which scenario demands multi-region writes (e.g., a social media platform with users on every continent) versus single-master with read replicas (e.g., a reporting application with writes only from headquarters).

## Common mistakes

- **Mistake:** Thinking you can change the API after creating the Cosmos DB account.
  - Why it is wrong: The API type (SQL, MongoDB, etc.) is fixed when the account is provisioned. The underlying storage format differs per API, and the service does not allow conversion.
  - Fix: Choose the API carefully before creating the account. If you need a different API, create a new account and migrate the data.
- **Mistake:** Assuming all APIs support stored procedures and triggers.
  - Why it is wrong: Only the SQL API supports server-side JavaScript-based stored procedures, triggers, and UDFs. Other APIs like MongoDB, Cassandra, and Gremlin do not support these features.
  - Fix: If you need stored procedures, use the SQL API or implement the logic in the application layer for other APIs.
- **Mistake:** Believing that the MongoDB API is 100% compatible with MongoDB.
  - Why it is wrong: The Cosmos DB MongoDB API implements version 4.0 of the wire protocol and does not support all MongoDB features (e.g., multi-document transactions, some aggregation stages).
  - Fix: Review the feature parity documentation. For advanced MongoDB features, consider using native MongoDB Atlas.
- **Mistake:** Setting very high RU/s without understanding that all API operations consume RUs differently.
  - Why it is wrong: The API charges based on RUs consumed. Over-provisioning wastes money, while under-provisioning causes throttling (429 errors). Each API has different RU costs for similar operations.
  - Fix: Estimate RU consumption using the Cosmos DB capacity calculator or run test queries in the Azure portal. Monitor with Azure Monitor metrics.
- **Mistake:** Confusing the Table API with Azure Table Storage.
  - Why it is wrong: While both use a similar SDK and wire protocol, Cosmos DB Table API offers global distribution, lower latency, and different consistency levels. Azure Table Storage is a separate service that is not globally distributed by default.
  - Fix: Use Cosmos DB Table API when you need global distribution and low latency. Use Azure Table Storage for simple, cheaper storage when global reach is not required.
- **Mistake:** Thinking that the consistency level can be set per request for all APIs in the same way.
  - Why it is wrong: While all APIs support the five consistency levels, the way to specify consistency at the request level differs. For the SQL API, it’s a header; for the MongoDB API, it’s a read preference setting.
  - Fix: Consult the SDK documentation for the specific API to set consistency per request correctly.

## Exam trap

{"trap":"The exam presents a scenario where an application uses MongoDB API and asks which consistency level supports multi-region writes. Many learners choose strong consistency because it seems safest.","why_learners_choose_it":"They associate “strong” with reliability and assume multi-region writes require strong consistency to avoid conflicts.","how_to_avoid_it":"Know that multi-region writes (multi-master) are only supported with eventual, consistent prefix, session, or bounded staleness consistency. Strong consistency is not available for multi-master because it would require all regions to agree before a write is confirmed, creating high latency and conflict issues. For multi-region writes, you need to use conflict resolution policies."}

## Commonly confused with

- **Cosmos DB API vs Azure Table Storage:** Azure Table Storage is a separate NoSQL key-value store without global distribution, lower throughput, and a single consistency level (eventual). Cosmos DB Table API is a fully managed, globally distributed service with the same key-value model but with configurable consistency, lower latency, and higher throughput. (Example: You use Azure Table Storage for simple logging that stays in one region. You use Cosmos DB Table API for a user session store that must be fast globally.)
- **Cosmos DB API vs Azure Cosmos DB SQL API vs. SQL Database:** Azure Cosmos DB SQL API is a NoSQL database with a SQL-like query language for JSON documents, schema-agnostic, and horizontally partitioned. Azure SQL Database is a relational database with a fixed schema, full T-SQL support, joins, and ACID transactions across multiple rows. (Example: You use Cosmos DB SQL API for product catalog data that evolves often. You use Azure SQL Database for financial transactions that require strict relational integrity.)
- **Cosmos DB API vs MongoDB Atlas:** MongoDB Atlas is the official cloud service from MongoDB Inc., offering full MongoDB functionality including multi-document ACID transactions and aggregation pipeline. Cosmos DB MongoDB API is a compatibility layer that supports a subset of MongoDB 4.0 features. (Example: You use MongoDB Atlas if you need advanced MongoDB features like change streams with full resume tokens. You use Cosmos DB MongoDB API if you need global distribution and integration with other Azure services.)
- **Cosmos DB API vs Cassandra API vs. Apache Cassandra:** Cosmos DB Cassandra API implements the CQL wire protocol but uses Cosmos DB’s underlying storage engine. Some Cassandra features (like materialized views, triggers, secondary indexes on clustering columns) are not supported or behave differently. (Example: You migrate an existing Cassandra workload to Cosmos DB Cassandra API to get global distribution and managed service, but you must drop unsupported features.)

## Step-by-step breakdown

1. **Choose an API** — When creating a Cosmos DB account, you select one of the APIs: SQL, MongoDB, Cassandra, Gremlin, Table, or PostgreSQL (preview). This choice is permanent and determines the wire protocol, query language, client libraries, and data model. Your existing tooling and skill set guide this decision.
2. **Provision the account** — Using the Azure portal, CLI, or ARM template, you create the Cosmos DB account. You specify regions, consistency level, network security settings (firewall, private endpoints), and backup policy. The account is the top-level resource.
3. **Create a database and container** — Under the account, you create a database, and within that, one or more containers. A container (equivalent to a table, collection, or graph depending on the API) holds your items. You define a partition key to distribute data across physical partitions. The partition key is critical for performance and scalability.
4. **Configure throughput** — You set provisioned throughput at the container or database level in Request Units per second (RU/s). This determines the capacity for reads and writes. You can also use autoscale mode, which adjusts RU/s based on traffic. The API monitors consumption and throttles requests if exceeded.
5. **Connect your application via SDK** — You install the appropriate client SDK for your programming language (e.g., Microsoft.Azure.Cosmos for .NET, com.azure.cosmos for Java). The SDK handles connection pooling, retry logic, and geo-routing. You provide the account endpoint and key, and the SDK communicates with the API endpoint.
6. **Perform CRUD operations** — Using the SDK, you create, read, update, and delete items. For the SQL API, you use SQL queries with SELECT, WHERE, JOIN, etc. For MongoDB, you use MongoDB driver methods. Each operation consumes RUs, which you can measure in the SDK response headers.
7. **Leverage advanced features** — The API gives access to features like change feed (read a log of changes), multi-region writes (enable writes from multiple regions), and stored procedures (SQL API only). You configure these through the SDK or portal, and they are executed through the API.
8. **Monitor and optimize** — Use Azure Monitor to track RU consumption, request latency, throttling events, and geo-replication lag. Based on metrics, you adjust indexing policies, partition key design, or consistency level to reduce cost and improve performance. The API provides telemetry through its responses.

## Practical mini-lesson

To truly understand Cosmos DB API, you should walk through a practical implementation scenario. Assume you are building a social media application that stores user profiles and posts. You choose the SQL API because you need rich queries: “Find all posts by users in a specific city with more than 100 likes.” You create a Cosmos DB account named “socialdb” with a single write region in East US and read replicas in West Europe and Southeast Asia.

First, you define a container called “Posts” with partition key “/userId”. This ensures that all posts from the same user are stored together, enabling efficient queries for a user’s timeline. You set provisioned throughput to 4000 RU/s with autoscale enabled to handle traffic spikes. You choose session consistency because it balances performance with a guarantee that you can read your own writes.

Your application uses the .NET SDK. When a user creates a post, you call container.CreateItemAsync(post, new PartitionKey(userId)). The SDK serializes the post object into JSON, sends an HTTP (or TCP) request to the API endpoint, and the API routes it to the write region. The API authenticates using the master key stored in Azure Key Vault. Behind the scenes, the API writes to the storage engine, indexes all fields by default (unless you specify a custom indexing policy), and returns the created document with a new timestamp.

When a user fetches their timeline, you run a SQL query: “SELECT * FROM Posts p WHERE p.userId = @userId ORDER BY p.createdAt DESC OFFSET 0 LIMIT 20”. The SDK sends this query to the nearest read region (determined by the endpoint routing). The API parses the query, pushes the filter down to the partition containing that userId, scans the index, and returns results. The query consumes RUs based on the number of documents read and the index usage. You monitor this using the x-ms-request-charge header.

Now, consider what can go wrong. If you choose a poorly distributed partition key, some partitions become hot, causing throttling (429 errors). The API returns these errors, and the SDK can retry up to a default of 9 times. If you do not set up indexing correctly, queries that filter on fields without index will cause full scans, increasing RU consumption and latency. You can adjust the indexing policy through the API by calling container.ReplaceContainerAsync with a new indexing policy.

Another practical aspect is security. You should use Azure Active Directory (AAD) with a managed identity for authentication instead of keys. The API supports AAD tokens through the .NET SDK. You also set firewall rules to restrict access to your application’s IP range.

Finally, cost management. You can reduce costs by using reserved capacity (committing to 1 or 3 years) for predictable workloads. The API does not charge for this directly, but the pricing model is tied to RU/s and storage. You can reduce RU consumption by returning only needed fields in queries, using stored procedures for batch operations, and enabling TTL (time-to-live) to automatically delete old data. The API supports TTL at the container and item level.

the API is the interface through which every configuration, operation, and optimization happens. Professionals who understand the API’s behavior can build performant, cost-effective, and secure applications.

## Commands

```
az cosmosdb create --name mycosmosaccount --resource-group myrg --locations regionName=eastus --capabilities EnableCassandra
```
Creates a new Cosmos DB account with Cassandra API enabled in the East US region.

*Exam note: Tests knowledge of the --capabilities parameter for API selection; also tests understanding of location specification for global distribution.*

```
az cosmosdb sql container create --resource-group myrg --account-name mycosmos --database-name mydb --name mycontainer --partition-key-path '/userId'
```
Creates a SQL API container with a partition key path of '/userId'.

*Exam note: Essential for understanding how to set partition key at container creation; exam questions often ask which command parameter defines partition key.*

```
az cosmosdb sql database throughput update --resource-group myrg --account-name mycosmos --name mydb --throughput 1000
```
Updates the provisioned throughput of a database to 1000 RU/s, shared across containers.

*Exam note: Tests understanding of database-level throughput vs container-level; common scenario in DP-900 for shared throughput.*

```
az cosmosdb sql container throughput show --resource-group myrg --account-name mycosmos --database-name mydb --name mycontainer | jq '.resource.minimumThroughput'
```
Shows the minimum RU/s for a container, which is the amount you must provision if you want to decrease throughput.

*Exam note: Important for cost management questions; the minimum throughput is 10 RU/s per GB of storage or the current average RU/s, whichever is higher.*

```
az cosmosdb keys list --resource-group myrg --name mycosmos --type primary-readonly
```
Lists the read-only primary key for the Cosmos DB account.

*Exam note: Tests understanding of key types (primary, secondary, read-only) and their security implications; read-only keys should be used for query-only workloads.*

```
az cosmosdb sql container conflict list --resource-group myrg --account-name mycosmos --database-name mydb --name mycontainer
```
Lists all unresolved conflicts in a container with multi-region writes.

*Exam note: Critical for troubleshooting multi-master scenarios; exam may ask how to identify conflicts and which policies resolve them.*

```
az cosmosdb sql container create --resource-group myrg --account-name mycosmos --database-name mydb --name mycontainer --partition-key-path '/ordertype' --throughput 5000 --indexing-policy Off
```
Creates a container with a specified indexing policy turned off for testing purposes.

*Exam note: Tests understanding that indexing can be controlled; exam questions often warn that disabling indexing prevents queries using the index, making them RU-expensive.*

## Troubleshooting clues

- **HTTP 429 Too Many Requests (Throttling)** — symptom: Application returns 429 errors under load, latency spikes.. Client is exceeding the provisioned RU/s. This can be due to hot partition (uneven load) or overall throughput being too low. Cosmos DB returns 429 when the sum of RU consumption exceeds RU/s in a second. (Exam clue: Exam questions test that 429 errors indicate throttling; solutions include increasing RU/s, using retry-after header, or fixing partition key imbalance.)
- **High request unit consumption for simple point reads** — symptom: A point read that should cost 1 RU is costing 10+ RUs.. Possible causes: indexing on all properties causing high write RU but low read RU, or using a query instead of a point read. Also, if the item is >1KB, RU cost scales linearly. (Exam clue: Tests understanding of point read vs query cost; exam asks how to reduce RU consumption for known item reads.)
- **Cross-partition queries timing out or failing** — symptom: Queries without partition key filter return incomplete results or time out.. Cross-partition queries fan out to all physical partitions, each potentially hitting RU limits or request size limits. Without partition key, the query cannot be restricted to one partition. (Exam clue: Essential topic in DP-900: design queries to include partition key to avoid cross-partition overhead.)
- **Write operations failing with HTTP 403 Forbidden** — symptom: Writes fail with 'Access forbidden due to firewall rules' or 'Authorization token expired'.. Cosmos DB account firewall is blocking the client IP, the key used is read-only, or the token (for resource tokens) has expired. (Exam clue: Tests security configurations: ensure client IP is allowed, use primary key for writes, and manage token expiry for user-based access.)
- **Data not visible after write in another region** — symptom: User writes to US East, then reads from US West and sees old data.. Consistency level is set to Eventual, so replication delay may exist. The write might not have propagated to the West region yet. If using Session consistency, the session token must be passed. (Exam clue: Common scenario when designing global apps; exam tests understanding that Eventual consistency has finite lag and that session tokens ensure read-your-writes.)
- **Large logical partition exceeding 20 GB** — symptom: Container cannot store more data for a specific partition key value.. Each logical partition has a 20 GB limit. If a single user's data (e.g., all orders for one customer) exceeds 20 GB, no more items can be added for that partition key value. (Exam clue: Important design constraint; exam asks to identify the limit and suggests using a composite partition key or sub-partitioning.)
- **Multi-region writes conflict resolution not working as expected** — symptom: Two different region writes result in unexpected data loss or inconsistency.. Conflict resolution policy mismatch – if using LWW, might discard wanted updates. If using custom stored procedure, the procedure might be buggy. (Exam clue: Tests knowledge of conflict resolution options; exam presents scenario where you need to pick the correct policy based on business requirements.)

## Memory tip

Remember: “Each API is a separate Cup”, SQL, MongoDB, Cassandra, Gremlin, Table, and you can only fill one cup when you brew the account.

## FAQ

**Can I use multiple APIs with the same Cosmos DB account?**

No, each Cosmos DB account is created with a single API. However, you can have separate accounts with different APIs, and you can reference the same data across accounts using data replication tools like Azure Data Factory.

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

The SQL API uses a SQL-like query language over JSON documents and supports stored procedures. The MongoDB API implements the MongoDB wire protocol, so existing MongoDB applications can connect with minimal changes, but it does not support stored procedures.

**Does the Cosmos DB API support transactions across multiple items?**

Only the SQL API supports transactional batch operations (using transactional batch or stored procedures) within the same partition key. The MongoDB API does not support multi-document ACID transactions like native MongoDB.

**How do I choose the right API for my application?**

Consider your team’s existing expertise, the data model you need (document, key-value, graph, column-family), the query patterns, and any existing code. If you need SQL queries and server-side logic, use SQL API. If you are migrating from MongoDB, use MongoDB API.

**Can I change the partition key after creating the container?**

The partition key is defined at container creation and cannot be changed. To change it, you must create a new container with the desired partition key and migrate the data using the change feed or bulk executor library.

**What are the different consistency levels available through the API?**

All APIs support five levels: strong, bounded staleness, session, consistent prefix, and eventual. The level can be set at the account level and overridden per request for some APIs.

**What is the change feed and which APIs support it?**

The change feed is a persistent log of item changes in the order they occur. It is supported by the SQL API and the MongoDB API. You use it to trigger Azure Functions or stream data to other systems.

## Summary

Cosmos DB API is the essential interface for interacting with Azure Cosmos DB, a globally distributed NoSQL database. It provides multiple protocol-compatible options (SQL, MongoDB, Cassandra, Gremlin, Table) so developers can use familiar tools and query languages. The API handles authentication, geo-routing, consistency enforcement, and throughput management, making global-scale application development accessible.

For IT professionals, understanding the API is crucial for cost management, security configuration, and performance tuning. Each API consumes Request Units differently, and choosing the wrong one can lead to high costs or throttling. The API also determines advanced capabilities: only the SQL API supports stored procedures, while only the SQL and MongoDB APIs support the change feed. Global distribution and multi-region writes are available across APIs, but with different consistency restrictions.

For exams like AZ-900, DP-900, and AZ-104, focus on memorizing the mapping between API and data model, the immutability of API choice, and the consistency level specifics. Remember that the API is chosen at account creation and cannot be changed later. Also, recall that strong consistency is not compatible with multi-region writes. By mastering these points, you can confidently answer scenario-based questions and configurations.

Ultimately, Cosmos DB API is a gateway to building high-performance, globally scalable applications. Whether you are a developer, architect, or administrator, the API is the key to unlocking Cosmos DB’s full potential.

---

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