Tag: Azure Cosmos DB

Store and retrieve embeddings and execute vector similarity search for semantic retrieval (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Store and retrieve embeddings and execute vector similarity search for semantic retrieval


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Modern AI applications frequently need to retrieve information based on meaning, rather than simply matching exact words.

For example, suppose a user asks:

“What options are available for taking my dog on vacation?”

A traditional keyword search might look for documents containing the words dog, vacation, or travel. A semantic search system can instead identify documents discussing pet-friendly hotels, even if those documents never use the exact words in the user’s question.

This is accomplished using vector embeddings and vector similarity search.

Azure Cosmos DB for NoSQL provides integrated vector storage, indexing, and search capabilities. Applications can store embeddings directly alongside their source documents and use the VectorDistance() system function to find documents whose vectors are closest to a query vector.

For the AI-200 exam, you should understand:

  • What embeddings are
  • How embeddings are generated
  • How embeddings are stored in Cosmos DB
  • Vector embedding policies
  • Vector indexing policies
  • flat, quantizedFlat, and diskANN
  • The VectorDistance() function
  • k-nearest-neighbor (kNN) searches
  • Semantic retrieval
  • Filtering vector searches
  • Why TOP N is important
  • How vector search fits into RAG applications
  • Important vector-search limitations

1. What Is a Vector Embedding?

A vector embedding is a numerical representation of information.

An embedding model converts content such as:

  • Text
  • Documents
  • Images
  • Audio
  • Other supported data

into an array of numerical values.

For example, a simplified embedding might look like:

[0.12, -0.43, 0.87, 0.21, -0.09]

Real-world embedding models generally produce vectors with many more dimensions.

The important concept is that the position of an embedding in a high-dimensional mathematical space represents characteristics of the original content.

Content with similar meanings tends to have vectors that are close together.

For example:

"How can I travel with my dog?"

might be semantically close to:

"Hotels that allow pets"

even though the two sentences don’t contain the same words.


2. Embeddings Are Generated Outside Cosmos DB

Azure Cosmos DB stores and searches embeddings, but the embedding itself is typically generated by an embedding model.

For example, an application might use an embedding API such as an Azure OpenAI embedding model.

The general workflow is:

Source content
|
v
Embedding model
|
v
Vector embedding
|
v
Azure Cosmos DB

For a search request:

User query
|
v
Embedding model
|
v
Query embedding
|
v
Cosmos DB vector search
|
v
Most semantically similar documents

The stored document embedding and query embedding need to be compatible. In practice, applications should generate both using the same embedding model or a compatible embedding space.


3. Storing Embeddings in Cosmos DB

One of the major advantages of the integrated vector capabilities in Azure Cosmos DB for NoSQL is that the embedding can be stored alongside the original document.

For example:

{
"id": "doc001",
"category": "travel",
"title": "Pet-Friendly Hotels",
"content": "Hotels that welcome dogs and cats...",
"embedding": [
0.123,
-0.456,
0.789,
0.234
]
}

The application therefore doesn’t need to maintain a completely separate database containing the vector and another database containing the associated document.

The vector and its source data can be colocated.

This is particularly useful for AI applications because the application can retrieve both:

  1. The similarity result
  2. The original content needed to answer the user’s question

from the same Cosmos DB item.


4. What Is Semantic Retrieval?

Semantic retrieval means finding information based on its meaning rather than simply matching keywords.

Consider these two documents:

Document A

“Our resort provides accommodations for guests traveling with pets.”

Document B

“Our resort has a swimming pool and fitness center.”

A user searches:

“Where can I stay with my dog?”

Document A is likely to have a much closer semantic relationship to the query.

A vector search system identifies that relationship by comparing embeddings.

The basic process is:

  1. Generate embeddings for documents.
  2. Store the embeddings with the documents.
  3. Generate an embedding for the user’s query.
  4. Compare the query vector with document vectors.
  5. Rank documents according to similarity.
  6. Return the most relevant documents.

This is the foundation of many retrieval-augmented generation (RAG) applications.


5. Vector Search in Azure Cosmos DB

Azure Cosmos DB for NoSQL provides vector search capabilities through:

  • Vector embedding policies
  • Vector indexing policies
  • The VectorDistance() system function

Vector indexes improve vector-search efficiency by reducing latency and RU consumption compared with an unindexed/full-scan approach.

At a conceptual level:

                  Azure Cosmos DB
+---------------------+
| |
Document ---> | Original content |
| |
Embedding --> | Vector embedding |
| |
| Vector index |
| |
+----------+----------+
^
|
VectorDistance()
|
Query embedding

6. Vector Embedding Policies

A vector embedding policy describes the vector properties that Cosmos DB should treat as embeddings.

The policy can specify characteristics such as:

  • The vector property path
  • Number of dimensions
  • Distance function
  • Data type

The policy establishes how Cosmos DB should interpret the vector data.

A simplified conceptual configuration might look like:

{
"vectorEmbeddings": [
{
"path": "/embedding",
"dataType": "float32",
"dimensions": 1536,
"distanceFunction": "cosine"
}
]
}

The exact configuration supported depends on the current Cosmos DB capabilities and account configuration, but the important exam concept is:

The vector embedding policy describes the characteristics of the vector data.

Don’t confuse this with the vector indexing policy.


7. Vector Indexing Policies

The vector indexing policy determines how Cosmos DB indexes the vectors for vector search.

Azure Cosmos DB for NoSQL currently provides three primary vector index types:

IndexGeneral purpose
flatExact/brute-force vector search
quantizedFlatQuantized vector search for smaller/scoped workloads
diskANNEfficient approximate vector search for larger workloads

Choosing the appropriate index is an important architectural decision.


8. The flat Vector Index

The flat index performs a brute-force comparison of vectors.

Its major advantage is accuracy.

A flat search can provide exact nearest-neighbor results.

However, it has a maximum vector dimensionality of 505 dimensions, which makes it unsuitable for many modern high-dimensional embedding models.

It can be appropriate for relatively small vector datasets or situations where exact recall is particularly important.

Key exam concept

Flat = exact/brute-force search.


9. The quantizedFlat Vector Index

quantizedFlat compresses vectors before storing them in the vector index.

This can provide:

  • Lower latency
  • Higher throughput
  • Lower RU consumption

compared with an ordinary flat index.

The trade-off is that quantization can result in some loss of accuracy.

quantizedFlat supports vectors up to 4,096 dimensions.

Microsoft currently describes quantizedFlat as particularly appropriate for smaller or more narrowly scoped searches, with 50,000 vectors or fewer in the search scope being a useful general guideline—not an absolute limit. Actual workloads should be benchmarked.

Key exam concept

quantizedFlat = compressed/brute-force search with improved efficiency and a possible small accuracy trade-off.


10. The diskANN Vector Index

diskANN is designed for efficient approximate vector search, particularly for larger workloads.

It can provide:

  • Low latency
  • High throughput
  • Efficient RU consumption
  • High retrieval accuracy

It supports vectors up to 4,096 dimensions.

Microsoft describes DiskANN as generally the most performant option when the search scope exceeds approximately 50,000 vectors, although actual workload testing remains important.

Key exam concept

diskANN = approximate vector search optimized for larger datasets/search scopes.


11. Vector Index Comparison

For exam preparation, remember the following:

CharacteristicflatquantizedFlatdiskANN
Search typeExact/brute forceQuantized brute forceApproximate
Maximum dimensions5054,0964,096
AccuracyExactSlight possible lossHigh, configurable trade-offs
Large datasetsPoor fitBetter for smaller/scoped dataExcellent
Latency at scaleHigherModerateLower
RU efficiency at scaleLowerBetterBetter
Typical useSmall/exact searchesSmaller/scoped searchesLarge-scale vector search

12. Important Requirement: Vector Index Configuration

A vector index must be configured for the vector property that will be searched.

For example:

"vectorIndexes": [
{
"path": "/embedding",
"type": "diskANN"
}
]

The vector embedding policy and vector index work together.

A useful way to remember the distinction is:

Embedding policy = What is my vector?

Vector index = How should I search my vector?


13. Performing Vector Similarity Search

The primary Cosmos DB function used for vector similarity search is:

VectorDistance()

A basic query might look like:

SELECT TOP 10
c.title,
VectorDistance(c.embedding, @queryVector) AS SimilarityScore
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

This query:

  1. Takes the query vector.
  2. Compares it with c.embedding.
  3. Calculates a vector distance.
  4. Sorts the results.
  5. Returns the top 10 results.

Microsoft specifically recommends using TOP N for vector searches because returning unnecessary results increases RU consumption and latency.


14. Understanding VectorDistance()

The function conceptually compares:

Document vector
|
v
VectorDistance()
^
|
Query vector

The result represents the distance between the vectors.

The exact interpretation depends on the configured distance function.

Common distance concepts include:

  • Cosine
  • Euclidean
  • Dot product

The application should use the distance function appropriate for the embedding model and workload.


15. Why Distance Matters

Suppose the query embedding is:

Q = [0.2, 0.3, 0.5]

and the database contains:

A = [0.2, 0.3, 0.5]
B = [0.8, 0.1, 0.2]
C = [-0.4, 0.7, 0.1]

The vector closest to the query is likely the most semantically similar.

The search engine can therefore rank results:

1. Document A
2. Document B
3. Document C

The application doesn’t have to know the meaning represented by every dimension.

The embedding model and vector-distance calculation handle that mathematical representation.


16. Always Use TOP N

A particularly important exam and practical-development point is:

Use TOP N with vector searches.

For example:

SELECT TOP 5
c.id,
c.title,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

If the application only needs the five most relevant documents, there’s little reason to retrieve thousands of results.

Returning unnecessary results can increase:

  • RU consumption
  • Latency
  • Network traffic
  • Application processing

Microsoft explicitly recommends TOP N for vector searches.


17. Filtering Vector Searches

Vector search can also be combined with traditional query filtering.

For example:

SELECT TOP 10
c.title,
c.category,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
WHERE c.category = "travel"
ORDER BY VectorDistance(c.embedding, @queryVector)

This means:

Find the most semantically similar documents within the travel category.

This is extremely useful in real applications.

Examples include:

  • Search products within a specific department.
  • Search documents belonging to a specific tenant.
  • Search hotel information within a particular region.
  • Search only documents that a user is authorized to access.

Azure Cosmos DB supports combining vector search with other query filtering capabilities.


18. Vector Search and Partitioning

Azure Cosmos DB applications should always consider partitioning.

For example, a multi-tenant application might have:

{
"id": "doc123",
"tenantId": "tenantA",
"title": "Company policy",
"embedding": [...]
}

A query could restrict retrieval to a particular tenant:

SELECT TOP 10
c.title,
VectorDistance(c.embedding, @queryVector) AS score
FROM c
WHERE c.tenantId = @tenantId
ORDER BY VectorDistance(c.embedding, @queryVector)

This can narrow the search scope and can be important for both performance and data isolation.


19. Semantic Search vs. Keyword Search

It is important to understand the difference.

Keyword search

A keyword search primarily asks:

Does this document contain the requested word or phrase?

For example:

"automobile"

might fail to find a document that only says:

"car"

Semantic search

Semantic search asks:

Which documents are mathematically closest in meaning to this query?

Therefore:

"automobile"

may retrieve documents discussing:

cars
vehicles
motor vehicles
transportation

depending on how the embedding model represents the concepts.


20. Hybrid Search

Vector search doesn’t have to replace traditional search.

Many AI applications use hybrid search, combining:

  • Keyword/full-text search
  • Vector similarity
  • Metadata filtering

For example:

User query
|
+--------------------+
| |
v v
Keyword search Vector search
| |
+---------+----------+
|
v
Combined ranking
|
v
Relevant results

This can provide better retrieval than relying exclusively on either keyword or vector search.

For example, vector search is good at identifying semantic similarity, while keyword search can be valuable when an exact product ID, name, or technical term matters.


21. Vector Search and RAG

One of the most important practical applications of vector search is Retrieval-Augmented Generation (RAG).

A simplified RAG architecture looks like this:

              DOCUMENT INGESTION
|
v
Generate embeddings
|
v
Azure Cosmos DB
+----------------------+
| Documents |
| Embeddings |
| Vector index |
+----------------------+

^
|
Vector retrieval
|
|
User question --> Generate embedding
|
v
Vector similarity search
|
v
Relevant documents
|
v
LLM
|
v
Generated answer

The vector database is responsible for retrieving relevant information.

The LLM is responsible for generating the final response using that retrieved information.

This distinction is important.

Vector search retrieves information; the LLM generates the response.


22. Keeping Embeddings Synchronized

Suppose the source document changes:

Original document
|
v
Embedding A

The document is updated:

Updated document
|
v
Embedding A <-- stale!

The embedding may no longer accurately represent the document.

Therefore, applications should have a mechanism to regenerate embeddings when source content changes.

Azure Cosmos DB’s change feed can be used as part of an architecture that detects changes and triggers embedding regeneration. The current AI-200 training material specifically includes change-feed processing for keeping embeddings synchronized.

A common architecture is:

Document updated
|
v
Cosmos DB change feed
|
v
Processing component
|
v
Generate new embedding
|
v
Update Cosmos DB item

23. Vector Index Limitations You Should Know

Several limitations are particularly relevant for the AI-200 exam.

Maximum dimensions

Current limits include:

  • flat: 505 dimensions
  • quantizedFlat: 4,096 dimensions
  • diskANN: 4,096 dimensions

Minimum vectors for quantizedFlat and diskANN

quantizedFlat and diskANN require at least 1,000 vectors for indexed vector searching. If fewer than 1,000 vectors are present, a full scan can be performed instead.

Shared throughput

Vector indexing and search currently aren’t supported on accounts using shared throughput.

Vector policy changes

Vector embedding and vector indexing policy settings aren’t simply modified in place. Depending on the specific configuration, the existing policy/index must be removed and recreated, or a new container may be required.

Vector search cannot simply be disabled

Once vector indexing and search are enabled on a container, it cannot simply be disabled.


24. Common Exam Traps

Trap 1: Confusing embeddings with indexes

An embedding is the numerical representation of content.

An index is the structure used to efficiently search those vectors.


Trap 2: Thinking Cosmos DB generates the embedding

Cosmos DB stores and searches embeddings.

An embedding model, such as an embedding API, generates the embedding.


Trap 3: Assuming diskANN is exact

diskANN is an approximate nearest-neighbor approach.

It is designed to provide excellent performance while maintaining high retrieval quality.


Trap 4: Assuming quantizedFlat is exact

Quantization can introduce a small loss of accuracy.


Trap 5: Forgetting TOP N

A vector search should generally use TOP N to avoid unnecessarily expensive retrieval.


Trap 6: Using flat for a 1,536-dimensional embedding

The current flat limit is 505 dimensions.

A 1,536-dimensional embedding requires a vector index type supporting that dimensionality, such as quantizedFlat or diskANN.


Trap 7: Treating vector search as keyword search

Vector search is based on semantic similarity, not exact text matching.


25. Exam-Focused Summary

For AI-200, remember this chain:

Source data
|
v
Embedding model
|
v
Vector embedding
|
v
Cosmos DB document
|
v
Vector embedding policy
|
v
Vector index
|
v
VectorDistance()
|
v
TOP N results
|
v
Semantic retrieval

The most important concepts are:

ConceptRemember
EmbeddingNumerical representation of content
Vector storeStores and retrieves embeddings
Vector embedding policyDefines characteristics of vectors
Vector indexMakes vector searches more efficient
flatExact/brute-force; max 505 dimensions
quantizedFlatQuantized; max 4,096 dimensions
diskANNApproximate, efficient large-scale search; max 4,096 dimensions
VectorDistance()Performs vector distance calculation
TOP NLimits results and helps control RU/latency
Semantic searchFinds content by meaning
Metadata filteringNarrows the search space
Hybrid searchCombines lexical and vector retrieval
RAGUses retrieved context to augment LLM generation
Change feedCan trigger embedding refresh when data changes

Practice Exam Questions

Question 1

An AI application stores product descriptions in Azure Cosmos DB for NoSQL. The application needs to find products that are semantically similar to a user’s natural-language query.

What should the application do?

A. Store the product descriptions as strings and use CONTAINS() exclusively.

B. Generate embeddings for the product descriptions and store the vectors with the documents.

C. Convert each product description to a partition key.

D. Store each word as a separate Cosmos DB item.

Answer: B

Explanation:
Semantic retrieval requires converting content into vector embeddings. The embeddings can then be stored alongside the original documents in Cosmos DB and compared with a query embedding. Keyword functions such as CONTAINS() don’t provide semantic similarity.


Question 2

An application uses a 1,536-dimensional embedding model and needs an efficient vector index for a large production dataset.

Which vector index type is the most appropriate choice?

A. flat

B. hash

C. range

D. diskANN

Answer: D

Explanation:
diskANN supports vectors up to 4,096 dimensions and is designed for efficient approximate vector search at larger scales. flat is limited to 505 dimensions and therefore cannot index a 1,536-dimensional vector.


Question 3

An application needs the five most semantically similar documents to a query vector.

Which query pattern should be used?

A.

SELECT *
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

B.

SELECT TOP 5 *
FROM c
ORDER BY c.embedding

C.

SELECT TOP 5 *
FROM c
ORDER BY VectorDistance(c.embedding, @queryVector)

D.

SELECT *
FROM c
WHERE c.embedding = @queryVector

Answer: C

Explanation:
VectorDistance() calculates the distance between the stored embedding and query vector. TOP 5 limits the results to the five most relevant documents and helps avoid unnecessary RU consumption and latency.


Question 4

Which statement best describes the purpose of a vector embedding?

A. It is a Cosmos DB authentication token.

B. It is the partition key automatically generated by Cosmos DB.

C. It is a numerical representation of the semantic characteristics of content.

D. It is an index containing document metadata.

Answer: C

Explanation:
An embedding is a numerical representation generated by an embedding model. Semantically related content tends to produce vectors that are close together in vector space.


Question 5

A company has a relatively small vector search workload and wants to use a vector index that compresses vectors to improve efficiency while accepting a possible small loss in accuracy.

Which index should it consider?

A. flat

B. quantizedFlat

C. diskANN

D. NoSQL range indexing

Answer: B

Explanation:
quantizedFlat compresses vectors before indexing. This can improve latency, throughput, and RU efficiency compared with flat, at the potential cost of some accuracy. It is particularly suited to smaller or more narrowly scoped searches.


Question 6

An application has documents containing both an embedding and a category property. It needs to find the most semantically similar documents, but only within the "finance" category.

Which approach is appropriate?

A. Perform a vector search without filtering and discard non-finance results afterward.

B. Store each category in a separate Cosmos DB account.

C. Use VectorDistance() together with a WHERE filter for the category.

D. Replace the embeddings with category names.

Answer: C

Explanation:
Vector search can be combined with traditional Cosmos DB query filters. The application can use a WHERE clause to restrict the search to documents matching the required metadata.


Question 7

A developer changes the text of a document but continues using the embedding that was generated from the old version.

What is the primary problem?

A. The partition key automatically changes.

B. The vector index is deleted.

C. The document becomes unreadable.

D. The embedding may no longer accurately represent the document.

Answer: D

Explanation:
An embedding represents the content used to generate it. If the source content changes substantially, the old embedding can become stale. Applications can use mechanisms such as the Cosmos DB change feed to detect changes and trigger embedding regeneration.


Question 8

Which statement correctly describes the flat vector index in Azure Cosmos DB for NoSQL?

A. It performs exact/brute-force vector search and supports vectors up to 505 dimensions.

B. It performs approximate DiskANN search and supports 4,096 dimensions.

C. It compresses vectors and always produces approximate results.

D. It is used only for keyword searches.

Answer: A

Explanation:
The flat index performs brute-force vector search and can provide exact nearest-neighbor results. Its current maximum vector dimensionality is 505.


Question 9

An AI application uses vector search as part of a RAG architecture.

What is the primary purpose of the vector search portion of the architecture?

A. Generate the final natural-language response.

B. Retrieve content that is semantically relevant to the user’s query.

C. Train the large language model.

D. Replace the embedding model.

Answer: B

Explanation:
Vector search retrieves relevant information based on semantic similarity. The retrieved content can then be supplied to an LLM as context for generating the final answer. Vector retrieval and LLM generation are separate responsibilities.


Question 10

A developer creates a vector search query that returns every matching document instead of limiting the result set. The application only needs the top 10 results.

What should the developer change?

A. Remove the vector index.

B. Increase the embedding dimensionality.

C. Add a TOP 10 clause to the query.

D. Replace VectorDistance() with CONTAINS().

Answer: C

Explanation:
Vector searches should generally use TOP N to limit the number of returned results. Returning more results than the application needs can increase RU consumption and latency.


Final Exam Takeaways

If you remember only a handful of things from this topic, remember these:

  1. Embeddings represent the semantic characteristics of content numerically.
  2. An embedding model generates the embedding; Cosmos DB stores and searches it.
  3. Embeddings can be stored alongside the original Cosmos DB document.
  4. VectorDistance() is the key function for vector similarity searches.
  5. Use TOP N when performing vector retrieval.
  6. flat provides exact/brute-force search but is limited to 505 dimensions.
  7. quantizedFlat provides a more efficient quantized approach for smaller/scoped searches.
  8. diskANN is designed for efficient approximate search at larger scales and supports up to 4,096 dimensions.
  9. Vector search can be combined with metadata filters and hybrid search.
  10. Vector retrieval is a fundamental building block for RAG applications.
  11. When source content changes, embeddings may need to be regenerated.
  12. For AI-200 scenario questions, pay close attention to the dataset size, vector dimensionality, accuracy requirements, RU consumption, and latency requirements when selecting a vector index.

Go to the AI-200 Exam Prep Hub main page

Optimize query performance and Request Units (RUs) consumption by using indexing policies and consistency levels (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Optimize query performance and Request Units (RUs) consumption by using indexing policies and consistency levels


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Azure Cosmos DB for NoSQL is designed to provide globally distributed, low-latency access to JSON data at scale. A key part of developing efficient Cosmos DB solutions is understanding how queries consume Request Units (RUs) and how indexing policies and consistency levels affect query performance, throughput, latency, and cost.

For the AI-200 exam, you should understand how to:

  • Explain what RUs represent.
  • Identify factors that increase or decrease RU consumption.
  • Understand how indexes improve query performance.
  • Configure indexing policies.
  • Include or exclude property paths from indexing.
  • Understand range and composite indexes.
  • Recognize when a query is likely to require a full scan.
  • Understand the relationship between partition keys and query performance.
  • Understand the five Cosmos DB consistency levels.
  • Choose an appropriate consistency level based on application requirements.
  • Understand how consistency affects read throughput.
  • Use query metrics to investigate expensive queries.

A useful way to think about optimization is:

Efficient Cosmos DB queries minimize the amount of data that must be examined and returned while using an indexing and consistency strategy appropriate for the application’s requirements.


1. Understanding Request Units (RUs)

Azure Cosmos DB uses Request Units (RUs) as a normalized measure of the resources required to perform database operations.

Instead of pricing or throttling individual operations according to CPU time, disk operations, memory, and other implementation details, Cosmos DB abstracts those resources into RUs.

For example, operations such as:

  • Creating an item
  • Reading an item
  • Updating an item
  • Deleting an item
  • Running a query

consume RUs.

The amount of RU consumption depends on the work required to perform the operation.

Important exam concept

The number of items returned is not the only factor determining RU consumption.

A query can return a small number of items while still consuming significant RUs if Cosmos DB has to examine a large amount of data.

Conversely, an efficiently indexed query may examine a relatively small amount of data and consume fewer RUs.


2. What Determines RU Consumption?

Several factors influence the RU charge of a request.

Common factors include:

  • Size of the items being read or written
  • Number of items involved
  • Number of properties being indexed
  • Query complexity
  • Whether indexes can be used efficiently
  • Whether the query is single-partition or cross-partition
  • Number of partitions involved
  • Amount of data returned
  • Consistency level
  • Type of operation

For example, consider:

SELECT *
FROM c
WHERE c.customerId = "C1001"

If customerId is efficiently indexed and the query can target the appropriate partition, the query can be relatively inexpensive.

A query such as:

SELECT *
FROM c
WHERE c.description = "some value"

may be considerably more expensive if the query requires examining many partitions or cannot efficiently use an appropriate index.


3. Why Indexing Matters

Azure Cosmos DB for NoSQL automatically indexes properties by default.

This means developers generally don’t have to create indexes manually before executing common queries.

The default indexing policy indexes every property of every item, using range indexes for string and numeric values.

This default behavior provides good general-purpose query performance.

However, an application may benefit from a custom indexing policy.

For example, suppose documents contain:

{
"id": "1001",
"customerId": "C1001",
"name": "Norm",
"description": "...",
"largeMetadata": {
"property1": "...",
"property2": "...",
"property3": "..."
}
}

If the application frequently queries:

WHERE c.customerId = "C1001"

but never queries largeMetadata, indexing every property may provide little benefit while increasing index storage and indexing work.

A custom indexing policy can exclude paths that aren’t needed for queries.


4. Indexing and Write Costs

Indexes aren’t free.

When an item is created or modified, Cosmos DB must maintain the indexes associated with that item.

Therefore, extensive indexing can increase:

  • Write RU consumption
  • Index storage
  • Index maintenance work

This creates an important optimization tradeoff:

StrategyPotential benefitPotential cost
Index many propertiesBetter query flexibilityMore index storage and write overhead
Index fewer propertiesLower indexing overheadSome queries may require scans
Use composite indexesEfficient supported multi-property queriesAdditional index maintenance
Use default policySimple and broadly effectiveMay index properties the application never queries

The goal isn’t to minimize indexes at all costs.

The goal is to index the paths required by the application’s query workload.


5. Indexing Modes

Azure Cosmos DB for NoSQL supports indexing modes that determine how indexes are maintained.

The important mode for normal querying is:

Consistent

The index is updated synchronously as items are created, updated, or deleted.

This provides predictable query behavior and is the normal indexing mode for queryable containers.

A container can also have indexing disabled by setting the indexing mode to none.

This can be useful for workloads where secondary indexing isn’t needed, such as certain key-value-style scenarios or some bulk-loading scenarios.

However, queries against a container without the necessary indexes may require scans and can therefore consume significantly more RUs.


6. Included and Excluded Paths

One of the most important ways to customize an indexing policy is through included paths and excluded paths.

An indexing policy can essentially answer:

Which JSON properties should Cosmos DB index?

For example:

{
"indexingMode": "consistent",
"includedPaths": [
{
"path": "/*"
}
],
"excludedPaths": [
{
"path": "/largeMetadata/*"
}
]
}

This approach indexes the document generally while excluding a portion that isn’t queried.

A useful rule is:

Exclude properties that don’t need to participate in queries, especially large or frequently changing properties, when doing so is appropriate for the workload.

The indexing-policy documentation recommends using an include-root/exclude-specific-path strategy when you want new properties added to the data model to be indexed automatically unless explicitly excluded.


7. The Partition Key Is Critical to Query Performance

Indexing alone does not guarantee an inexpensive query.

The partition key is also extremely important.

Consider a container partitioned by:

/customerId

A query such as:

SELECT *
FROM c
WHERE c.customerId = "C1001"

can potentially be targeted to a single logical partition.

Compare that with:

SELECT *
FROM c
WHERE c.city = "Orlando"

If city isn’t the partition key, Cosmos DB may need to execute the query across multiple partitions.

This is called a cross-partition query.

Cross-partition queries can consume more RUs because multiple partitions may need to participate.

Exam takeaway

When analyzing a query, don’t ask only:

“Is the property indexed?”

Also ask:

“Can the query be directed to the appropriate partition?”

A well-designed partition key and appropriate indexing policy work together.


8. Partition Key Indexing

There is an important detail that can appear in exam questions.

A partition key property isn’t automatically indexed merely because it is the partition key.

If the partition key isn’t /id, it should generally be included in the indexing policy when queries filter on it. Otherwise, queries using that property can be forced into full scans, increasing RU consumption.

For example, if the partition key is:

/customerId

and the application frequently queries:

WHERE c.customerId = "C1001"

the indexing policy should support that path.


9. Types of Indexes

Azure Cosmos DB supports several index types.

For AI-200, you should understand at least the major concepts surrounding:

  • Range indexes
  • Composite indexes
  • Spatial indexes
  • Vector indexes

The most important indexes for traditional query optimization are range and composite indexes.


10. Range Indexes

Range indexes are based on an ordered structure and can support many common query operations.

They can support operations such as:

=
>
<
>=
<=

as well as certain ORDER BY, JOIN, and string-function scenarios.

For example:

SELECT *
FROM c
WHERE c.price > 100

can benefit from an appropriate range index on price.

Similarly:

SELECT *
FROM c
ORDER BY c.price

requires a range index on the ordered property.


11. Composite Indexes

A composite index indexes multiple properties together.

Composite indexes are particularly useful for queries involving multiple properties and certain combinations of filtering and sorting.

For example:

SELECT *
FROM c
WHERE c.category = "AI"
ORDER BY c.timestamp DESC

may benefit from an appropriate composite index involving:

/category
/timestamp

The order of properties in a composite index matters.

For example, these are not necessarily interchangeable:

(category ASC, timestamp DESC)

and:

(timestamp DESC, category ASC)

The appropriate ordering depends on the query workload.

Exam tip

If a question describes a query using multiple properties with filtering and/or ordering, think:

Could a composite index make this query more efficient?


12. Index Utilization

Cosmos DB’s query engine can use indexes in different ways.

The query engine can perform operations ranging from highly efficient index seeks to full scans.

Generally, the progression is:

  1. Index seek
  2. Precise index scan
  3. Expanded index scan
  4. Full index scan
  5. Full scan

An index seek is particularly efficient because the query engine can identify the relevant index entries without examining the entire dataset.

A full scan is considerably more expensive because Cosmos DB must inspect the underlying data rather than efficiently locating matching records through an appropriate index.


13. Why SELECT * Can Cost More

The amount of data returned affects RU consumption.

Consider:

SELECT *
FROM c
WHERE c.customerId = "C1001"

versus:

SELECT c.id, c.name
FROM c
WHERE c.customerId = "C1001"

The second query may consume fewer RUs because it returns less data.

This leads to an important optimization principle:

Return only the properties your application needs.

Avoid retrieving large documents when only a few properties are required.


14. Avoid Unnecessary Cross-Partition Queries

Suppose a container has:

Partition key: /customerId

This query can potentially target a partition:

SELECT c.id, c.name
FROM c
WHERE c.customerId = "C1001"

But this query may involve many partitions:

SELECT c.id, c.name
FROM c
WHERE c.status = "Active"

If status isn’t the partition key, Cosmos DB may need to query multiple partitions.

Cross-partition queries aren’t inherently bad.

They are sometimes necessary.

The important point is:

Don’t accidentally create expensive cross-partition queries when the application can supply the partition key.


15. Measuring Query RU Consumption

The Cosmos DB SDKs provide information about the RU charge associated with operations.

For example, application code can inspect the response from a query and determine how many RUs were consumed.

This is valuable because optimization should be based on actual workload measurements rather than assumptions.

When troubleshooting an expensive query, examine:

  • RU charge
  • Query execution time
  • Number of returned documents
  • Index utilization
  • Number of partitions involved
  • Query predicates
  • Requested properties
  • Partition-key usage

16. Index Transformation

Changing an indexing policy can cause Cosmos DB to perform an index transformation.

For example, adding an indexed path requires Cosmos DB to build the new index for existing data.

Index transformation is asynchronous and consumes RUs. Queries begin using a newly added indexed path after the index transformation has completed.

This is important operationally.

If you replace one index with another, a good strategy is generally:

  1. Add the new index.
  2. Wait for the transformation to complete.
  3. Verify the workload.
  4. Remove the old index if it is no longer required.

Removing an indexed path takes effect immediately, so removing an index before the replacement is ready can temporarily cause queries to fall back to scans.


17. Understanding Consistency Levels

Indexing affects how efficiently data can be located.

Consistency affects what version of the data a read is allowed to return.

Azure Cosmos DB provides five consistency levels, ordered from strongest to weakest:

  1. Strong
  2. Bounded staleness
  3. Session
  4. Consistent prefix
  5. Eventual

Choosing the consistency level is a business and application decision.

You should not automatically select the strongest consistency level.


18. Strong Consistency

Strong consistency guarantees that reads return the latest committed version of the data.

This provides the strongest read guarantee.

The tradeoff is that strong consistency can increase write latency and reduce availability in some globally distributed scenarios because replicas must satisfy the stronger synchronization requirements.

Appropriate scenarios

Strong consistency may be appropriate for scenarios where stale data is unacceptable, such as:

  • Certain financial transactions
  • Critical inventory decisions
  • Applications requiring immediate globally consistent reads

Exam clue

If a question says:

“The application must always read the most recently committed value.”

Think:

Strong consistency.


19. Bounded Staleness

Bounded staleness guarantees that reads aren’t allowed to become older than a configured limit based on:

  • Time
  • Number of versions/operations

This is useful when the application can tolerate a controlled amount of replication lag but needs a stronger guarantee than eventual consistency.

For example:

“Data can be up to a few seconds old, but never older than that.”

This points toward bounded staleness.

Bounded staleness is particularly relevant to globally distributed applications that need near-strong consistency without the full cost of strong consistency.


20. Session Consistency

Session consistency is commonly useful for interactive applications.

It provides guarantees such as:

  • Read-your-writes
  • Monotonic reads
  • Monotonic writes

In practical terms, a user who writes data should be able to read that data within the same session.

For example:

  1. User updates their profile.
  2. User immediately refreshes the profile.
  3. The application should see the user’s update.

Session consistency is often a good balance between strong consistency and scalability.


21. Consistent Prefix

Consistent prefix guarantees that reads see writes in the order they occurred, without observing them out of sequence.

The application may not immediately see every write, but it won’t see writes in an inconsistent order.

For example, suppose writes occur in this order:

A → B → C → D

A reader might see:

A
A, B
A, B, C
A, B, C, D

but shouldn’t see:

A, C

while missing B.


22. Eventual Consistency

Eventual consistency provides the weakest consistency guarantee.

Different replicas may temporarily return different values, but replicas eventually converge.

The major advantages include:

  • Lower coordination requirements
  • High availability
  • Good performance
  • Lower latency in many distributed scenarios

Eventual consistency may be appropriate for:

  • Social feeds
  • Recommendation systems
  • Analytics dashboards
  • Non-critical status information
  • Content where temporary staleness is acceptable

23. Consistency and Read Throughput

Consistency isn’t simply about correctness.

It can also affect read throughput.

For strong and bounded staleness consistency, reads are performed against two replicas in a four-replica set to satisfy the consistency guarantees.

Session, consistent prefix, and eventual consistency use single-replica reads.

Consequently, for the same number of provisioned RUs, strong and bounded staleness consistency provide approximately half the read throughput of the weaker consistency levels.

This is a very important AI-200 exam concept.

Remember:

Stronger consistency can consume more read capacity.

Therefore, if an application does not require strong consistency, relaxing the consistency requirement can improve read scalability.


24. Consistency Does Not Change Write RU Charges

For the same type of write operation, write RU consumption is generally identical across consistency levels.

However, stronger consistency can have other performance implications, particularly around replication and latency.

Therefore, don’t confuse:

Consistency → read behavior and read throughput

with:

Indexing → query efficiency and index maintenance

Both affect application performance, but in different ways.


25. Choosing the Right Consistency Level

A useful decision framework is:

RequirementRecommended consideration
Must always see the latest committed valueStrong
Can tolerate a precisely bounded amount of stalenessBounded staleness
Users need read-your-writes behaviorSession
Writes must appear in order but can be delayedConsistent prefix
Temporary inconsistency is acceptableEventual

The key is to choose the weakest consistency level that still satisfies the application’s requirements.

This can improve scalability and reduce unnecessary coordination.


26. Combining Indexing and Consistency Optimization

Indexing and consistency should be considered separately.

Suppose an application has an expensive query.

You might investigate:

Indexing

  • Is the filtered property indexed?
  • Is an appropriate range index available?
  • Is a composite index appropriate?
  • Is the partition key included in the indexing policy?
  • Is the query performing a full scan?
  • Are unnecessary properties being indexed?

Query design

  • Is the partition key supplied?
  • Is the query unnecessarily cross-partition?
  • Is SELECT * returning unnecessary data?
  • Can the query be simplified?

Consistency

  • Does the application actually require strong consistency?
  • Could session consistency satisfy the requirement?
  • Could eventual consistency satisfy the requirement?

This distinction is important:

Don’t try to solve every RU problem by changing the indexing policy.

Likewise:

Don’t weaken consistency when the application actually requires stronger guarantees.


27. A Practical Optimization Example

Imagine an AI-powered customer-support application.

The container contains millions of support conversations.

The partition key is:

/customerId

The application runs:

SELECT *
FROM c
WHERE c.customerId = "C1001"
AND c.status = "Open"
ORDER BY c.createdDate DESC

Several optimization questions should be considered.

Question 1: Can the query target a partition?

Yes.

It specifies:

customerId = C1001

which is the partition key.

Question 2: Are the relevant properties indexed?

The query uses:

customerId
status
createdDate

The indexing policy should support the query.

Question 3: Would a composite index help?

Potentially.

The query combines filtering and sorting across multiple properties, so a composite index may be appropriate depending on the exact query workload and index requirements.

Question 4: Does the application need every property?

Perhaps not.

Instead of:

SELECT *

the application could retrieve only:

SELECT c.id, c.status, c.createdDate, c.subject

Question 5: Does the application need strong consistency?

If the support application can tolerate some temporary staleness, a weaker consistency level may provide better read scalability.

This illustrates an important principle:

Query performance is usually the result of several design decisions working together.


28. Common AI-200 Exam Traps

Trap 1: “Indexes always reduce RU consumption.”

Not necessarily.

Indexes can reduce the amount of data that must be examined for queries, but maintaining indexes also adds write and storage overhead.


Trap 2: “The partition key automatically makes the property indexed.”

Not necessarily.

The partition key should be considered separately from the indexing policy. A partition key property should be included in the indexing policy when queries need to efficiently filter on it.


Trap 3: “Strong consistency is always better.”

Strong consistency provides stronger guarantees, but it can reduce read throughput and increase latency/availability tradeoffs.

Choose it only when required.


Trap 4: “Eventual consistency means data is permanently inconsistent.”

No.

Eventual consistency means replicas may temporarily disagree, but they eventually converge.


Trap 5: “A query returning one item must be inexpensive.”

Not necessarily.

Cosmos DB may have to examine many items or partitions to discover that single matching item.


Trap 6: “Cross-partition queries are always wrong.”

No.

Cross-partition queries are sometimes necessary.

The goal is to avoid unnecessary cross-partition queries and design the partition key appropriately for the workload.


Trap 7: “Removing an index is harmless.”

Removing an index can cause queries that depended on it to fall back to less efficient execution, potentially increasing RU consumption.


29. AI-200 Exam Quick Reference

ConceptRemember
RUNormalized unit of Cosmos DB resource consumption
IndexHelps locate matching data efficiently
Default indexingAutomatically indexes properties by default
Custom indexingCan include/exclude paths
Range indexEquality, range, ordering, and other supported operations
Composite indexMultiple-property query patterns
Full scanPotentially expensive; examines underlying data broadly
Partition keyDetermines data distribution and can enable targeted queries
Cross-partition queryMay require querying multiple partitions
SELECT *Can return more data and increase RU consumption
Strong consistencyLatest committed value
Bounded stalenessControlled maximum staleness
SessionRead-your-writes and session guarantees
Consistent prefixWrites observed in order
EventualTemporary inconsistency allowed
Strong/bounded read throughputLower than weaker levels for same RU allocation
Index transformationAsynchronous and consumes RUs
Best practiceChoose indexes and consistency based on workload requirements

Practice Exam Questions

Question 1

An application stores customer records in Azure Cosmos DB for NoSQL. The container is partitioned by /customerId. The application frequently executes the following query:

SELECT *
FROM c
WHERE c.customerId = "C1005"

The developer wants to minimize RU consumption.

Which approach is most appropriate?

A. Add a spatial index to the customerId property.

B. Disable indexing so the query engine can scan the container faster.

C. Change the consistency level to Strong regardless of the application’s requirements.

D. Ensure the customerId path is appropriately indexed and provide the partition key value when executing the query.

Answer: D

Explanation

The query uses the partition key, allowing Cosmos DB to target the appropriate logical partition. The property should also be appropriately indexed when queries filter on it. This combination can significantly improve query efficiency.

Disabling indexing would generally make query execution less efficient. Spatial indexes are intended for geospatial data, not customer identifiers. Strong consistency does not inherently optimize this query.


Question 2

A globally distributed application displays product recommendations. Recommendations can be temporarily stale as long as replicas eventually converge.

Which consistency level is generally the most appropriate?

A. Strong

B. Bounded staleness

C. Session

D. Eventual

Answer: D

Explanation

The application explicitly permits temporary staleness and does not require read-your-writes or strict ordering guarantees. Eventual consistency is therefore appropriate.

Strong consistency provides stronger guarantees than necessary. Bounded staleness provides a specific staleness guarantee that isn’t required by the scenario. Session consistency would provide stronger session-level guarantees than needed.


Question 3

A Cosmos DB container contains documents with hundreds of properties. An application queries only /customerId, /status, and /createdDate. Many large metadata properties are never queried.

The development team wants to reduce indexing overhead and index storage.

What should they consider?

A. Enable strong consistency.

B. Customize the indexing policy to exclude properties that don’t need to be queried.

C. Remove the partition key.

D. Replace all range indexes with spatial indexes.

Answer: B

Explanation

A custom indexing policy can exclude properties that don’t participate in queries. This can reduce index size and indexing maintenance overhead.

Changing consistency doesn’t address unnecessary indexes. Removing the partition key is not an appropriate optimization, and spatial indexes aren’t appropriate for ordinary scalar properties such as customer IDs and status values.


Question 4

An application requires that a user immediately see an item after the user creates it, but the application does not require globally strong consistency for every user.

Which consistency level is generally the best fit?

A. Eventual

B. Consistent prefix

C. Session

D. Strong

Answer: C

Explanation

Session consistency provides read-your-writes behavior and is well suited to interactive applications where a user expects to see their own changes.

Eventual consistency doesn’t provide the same session guarantees. Consistent prefix guarantees write ordering but doesn’t provide the same read-your-writes behavior. Strong consistency is stronger than necessary for the stated requirement.


Question 5

A query returns only one document but consumes a surprisingly large number of RUs. The query doesn’t specify the partition key and runs against a container with many physical partitions.

What is the most likely explanation?

A. Cosmos DB charges a fixed RU amount for every returned document.

B. The query must always use a spatial index.

C. The query may be executing across multiple partitions and examining significant amounts of data before finding the matching document.

D. Returning one document always requires Strong consistency.

Answer: C

Explanation

The number of returned documents isn’t the only determinant of RU consumption. A cross-partition query can require Cosmos DB to examine multiple partitions, potentially consuming significant RUs even if only one document ultimately matches.

There is no fixed RU charge per returned document, spatial indexing is unrelated, and consistency doesn’t automatically become Strong because one document is returned.


Question 6

A query uses:

SELECT *
FROM c
WHERE c.category = "AI"
ORDER BY c.timestamp DESC

The application frequently executes this query and wants to optimize its performance.

Which index type should the developer investigate first?

A. Composite index

B. Spatial index

C. Vector index

D. No index; ORDER BY queries cannot use indexes

Answer: A

Explanation

The query uses multiple properties in filtering and ordering. A composite index can be useful for query patterns involving multiple properties and sorting.

Spatial indexes are designed for geospatial operations. Vector indexes are designed for vector search. Cosmos DB can use indexes for ORDER BY operations.


Question 7

An application currently uses Strong consistency. Performance testing shows that read throughput is insufficient. The application requirements state that users only need read-your-writes behavior within their own sessions.

What should the developer consider?

A. Add a spatial index.

B. Change the partition key to /id without analyzing the workload.

C. Disable all indexes.

D. Use Session consistency if it satisfies the application’s requirements.

Answer: D

Explanation

Session consistency provides read-your-writes behavior and other session-level guarantees while avoiding the stronger coordination requirements of Strong consistency.

Changing the partition key or disabling indexes doesn’t directly address the stated consistency requirement. Spatial indexing is unrelated.


Question 8

A developer removes an indexed path from a Cosmos DB indexing policy because the property is no longer queried. An existing query unexpectedly begins consuming substantially more RUs.

What is the most likely explanation?

A. Removing an indexed path causes all writes to become strongly consistent.

B. The query may no longer be able to use the removed index and may fall back to a less efficient scan.

C. Removing an index automatically converts the container into a different API.

D. Cosmos DB stops supporting partitioning when an index is removed.

Answer: B

Explanation

When an indexed path is removed, queries that relied on that index may no longer be able to use it and can fall back to a full scan or another less efficient execution strategy. This can substantially increase RU consumption.

The other options describe behaviors that don’t occur as a result of removing an indexed path.


Question 9

A company wants to ensure that reads never return a value older than a configured amount of time or number of updates, but it doesn’t require Strong consistency.

Which consistency level should the developer select?

A. Eventual

B. Session

C. Bounded staleness

D. Consistent prefix

Answer: C

Explanation

Bounded staleness is specifically designed for scenarios where the application can tolerate a controlled amount of staleness based on time or the number of versions/operations.

Eventual consistency provides no such bounded staleness guarantee. Session consistency focuses on session-level guarantees, while consistent prefix guarantees write ordering rather than a specific staleness bound.


Question 10

A Cosmos DB account has a workload dominated by read operations. The application doesn’t require Strong or Bounded Staleness consistency. The team wants to maximize read throughput for the same provisioned RU capacity.

Which approach is most appropriate?

A. Use Session, Consistent Prefix, or Eventual consistency according to the application’s requirements.

B. Increase indexing on every possible property.

C. Change every query to SELECT *.

D. Use Strong consistency for all queries.

Answer: A

Explanation

Strong and Bounded Staleness consistency use more replicas for reads and therefore provide approximately half the read throughput of Session, Consistent Prefix, and Eventual consistency for the same RU allocation.

If the application doesn’t require the stronger guarantees, using an appropriate weaker consistency level can improve read scalability.

Increasing indexes can help particular queries but doesn’t address the consistency-related read-throughput issue. SELECT * can actually increase data returned and RU consumption, while Strong consistency would move in the opposite direction from the desired optimization.


Final Exam Takeaways

For AI-200, the most important concepts to remember are:

  1. RUs represent the resources consumed by Cosmos DB operations.
  2. Indexes can make queries substantially more efficient, but maintaining indexes has a cost.
  3. The default indexing policy indexes properties automatically.
  4. Custom indexing policies can include or exclude property paths.
  5. Range indexes support many common equality, range, and ordering operations.
  6. Composite indexes are important for appropriate multi-property query patterns.
  7. A partition-key-aware query is generally more efficient than an unnecessary cross-partition query.
  8. The partition key should be considered separately from indexing.
  9. Returning unnecessary data, such as with SELECT *, can increase RU consumption.
  10. Strong consistency provides the strongest read guarantee but has performance and availability tradeoffs.
  11. Bounded staleness provides a controlled staleness guarantee.
  12. Session consistency provides important read-your-writes behavior for interactive applications.
  13. Consistent prefix preserves write ordering.
  14. Eventual consistency provides the weakest guarantees but can maximize scalability and availability.
  15. Strong and bounded staleness provide lower read throughput for the same RU allocation than Session, Consistent Prefix, and Eventual consistency.
  16. Index transformations consume RUs and occur asynchronously.
  17. When optimizing Cosmos DB, consider the combination of partitioning, indexing, query design, returned data, and consistency—not any one factor in isolation.

Go to the AI-200 Exam Prep Hub main page

Connect to Azure Cosmos DB for NoSQL by using the SDK and run queries (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Connect to Azure Cosmos DB for NoSQL by using the SDK and run queries


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Azure Cosmos DB for NoSQL is a globally distributed, fully managed NoSQL database service designed for applications that require flexible schemas, low-latency access, and elastic scalability.

For the AI-200 exam, developers should understand how to:

  • Connect applications to Azure Cosmos DB for NoSQL.
  • Use the Azure Cosmos DB SDK.
  • Authenticate securely.
  • Create and access databases and containers.
  • Define partition keys.
  • Insert, read, update, and delete items.
  • Construct SQL queries for Cosmos DB.
  • Execute queries through the SDK.
  • Work with query parameters.
  • Understand partition-aware querying.
  • Process query results efficiently.
  • Recognize common performance considerations.

The key concept is that Azure Cosmos DB for NoSQL exposes a SQL-like query language, while the SDK provides the programming interface through which an application connects to the service and executes those queries.


1. Understanding the Azure Cosmos DB for NoSQL Data Model

Before connecting with an SDK, it is important to understand the hierarchy used by Azure Cosmos DB.

The basic structure is:

Cosmos DB account → Database → Container → Item

Cosmos DB account

The account is the top-level Azure resource. It provides the endpoint through which applications communicate with Cosmos DB.

An account contains one or more databases.

Database

A database provides a logical grouping of containers.

For example:

AI200CosmosAccount
└── CustomerDatabase

Container

A container is where items are stored.

A container is roughly analogous to a table in a relational database, although it is much more flexible because Cosmos DB items can have different structures.

CustomerDatabase
├── Customers
├── Orders
└── Products

A container also defines the partition key path, which is extremely important for scalability and query performance.

Item

An item is a JSON document.

For example:

{
"id": "customer-1001",
"customerName": "John Smith",
"country": "US",
"email": "john@example.com",
"loyaltyLevel": "Gold"
}

Unlike a relational table, another item in the same container could contain additional properties.


2. Connecting to Azure Cosmos DB

An application needs two primary pieces of information to connect to a Cosmos DB account:

  1. The Cosmos DB account endpoint.
  2. A supported authentication mechanism.

A typical endpoint looks conceptually like:

https://<account-name>.documents.azure.com:443/

The SDK uses this endpoint to communicate with the Cosmos DB service.


3. Authentication

Authentication is an important exam topic because applications should avoid embedding long-lived credentials directly in source code.

Several authentication approaches are available, including:

  • Microsoft Entra ID-based authentication.
  • Managed identities.
  • Account keys.
  • Connection strings.

For production Azure applications, Microsoft Entra ID with managed identity is generally preferable when supported by the application’s architecture because credentials do not need to be stored in application configuration or source code.

For example, an application running on an Azure service can use its managed identity to authenticate to Cosmos DB.

The conceptual flow is:

Application
│ Managed identity
Microsoft Entra ID
│ Token
Azure Cosmos DB

Exam point

If a question asks for the most secure way for an Azure-hosted application to authenticate to Cosmos DB without storing credentials, look for an answer involving:

Microsoft Entra ID + managed identity + appropriate Cosmos DB data-plane permissions.


4. Using the Azure Cosmos DB SDK

Microsoft provides SDKs for several programming languages, including:

  • .NET
  • Java
  • JavaScript/TypeScript
  • Python

The SDK provides classes and methods for interacting with Cosmos DB.

For example, a .NET application can use the Azure Cosmos DB SDK package.

A simplified connection looks like:

var client = new CosmosClient(
endpoint,
credential);

The CosmosClient represents the client connection to the Cosmos DB account.

Applications can then access databases and containers through the client.

Conceptually:

CosmosClient
└── Database
└── Container
├── Create item
├── Read item
├── Replace item
├── Delete item
└── Query items

5. Reuse the CosmosClient

A common application-design mistake is creating a new CosmosClient for every database operation.

Instead, applications should generally create and reuse a single CosmosClient instance for the lifetime of the application.

For example:

private static CosmosClient client = new CosmosClient(
endpoint,
credential);

The SDK manages connections internally.

Creating clients repeatedly can cause unnecessary connection overhead and negatively affect performance.

Exam tip

If a question presents code that creates a new CosmosClient for every request, consider whether the question is testing your knowledge of client reuse.

Reuse the client rather than repeatedly creating new instances.


6. Accessing a Database

Once the client has been created, the application can obtain a reference to a database.

For example:

Database database = client.GetDatabase("CustomerDatabase");

This does not necessarily mean that the database has been created.

It obtains a client-side reference to the database.

If the database needs to be created, the SDK provides methods such as:

DatabaseResponse response =
await client.CreateDatabaseIfNotExistsAsync("CustomerDatabase");

The CreateIfNotExists pattern is useful when an application should create the resource only when necessary.


7. Accessing a Container

After obtaining a database reference, the application can access a container:

Container container =
database.GetContainer("Customers");

As with GetDatabase(), obtaining a container reference does not mean that the container has been created.

A container can be created when necessary:

ContainerResponse response =
await database.CreateContainerIfNotExistsAsync(
"Customers",
"/country");

The second parameter specifies the partition key path.

In this example:

/country

is the partition key path.


8. Partition Keys

Partitioning is fundamental to Cosmos DB.

A container distributes its items across physical partitions based on the configured partition key.

For example:

{
"id": "customer-1001",
"country": "US",
"name": "John Smith"
}

If /country is the partition key path, the value:

US

determines the logical partition to which the item belongs.

A good partition key should generally provide:

  • High cardinality.
  • Even distribution.
  • Sufficient request-volume distribution.
  • Values that match common access patterns.

Why this matters for queries

If a query includes the partition key value, Cosmos DB can often limit the query to the relevant partition rather than querying every partition.

This is called a single-partition query or targeted query, depending on the scenario.

A query that does not provide a partition key value may require a cross-partition query.


9. Creating Items

Items are JSON documents.

A .NET application can create an item using the SDK:

var customer = new
{
id = "customer-1001",
country = "US",
name = "John Smith",
loyaltyLevel = "Gold"
};
ItemResponse<dynamic> response =
await container.CreateItemAsync(
customer,
new PartitionKey("US"));

The partition key value supplied to the SDK should correspond to the item’s partition key.

For a container partitioned on:

/country

the request should specify:

new PartitionKey("US")

10. Reading an Item

When the application’s partition key and item ID are known, the SDK can directly retrieve an item.

For example:

ItemResponse<Customer> response =
await container.ReadItemAsync<Customer>(
"customer-1001",
new PartitionKey("US"));

This is generally much more efficient than querying for the item because Cosmos DB can directly address the item using its ID and partition key.

Important distinction

Consider these two operations:

ReadItem(id, partitionKey)

versus:

SELECT * FROM c WHERE c.id = "customer-1001"

The point read supplies both the item ID and partition key and is the preferred operation when those values are known.

Exam tip

If a question asks how to retrieve one known item as efficiently as possible, look for:

Point read using the item’s ID and partition key.


11. Updating Items

The SDK supports updating existing items.

Depending on the required behavior, developers can use operations such as:

  • Replace
  • Upsert
  • Patch

Replace

Replace generally replaces the entire item.

Upsert

Upsert means:

Update the item if it exists; otherwise create it.

For example:

await container.UpsertItemAsync(
customer,
new PartitionKey("US"));

Patch

Patch modifies selected properties without requiring the application to replace the entire document.

For example, an application might update only:

loyaltyLevel

rather than sending the entire customer document.

This can reduce the amount of data transmitted and simplify partial updates.


12. Deleting Items

An item can be deleted using its ID and partition key:

await container.DeleteItemAsync<Customer>(
"customer-1001",
new PartitionKey("US"));

Again, knowing both the ID and partition key allows Cosmos DB to directly identify the item.


13. Querying Azure Cosmos DB for NoSQL

Cosmos DB for NoSQL uses a SQL-like query language.

A simple query is:

SELECT * FROM c

The c represents each item being queried.

For example:

SELECT *
FROM c
WHERE c.country = "US"

This returns items whose country property is US.


14. Selecting Specific Properties

Applications don’t always need the entire document.

Instead of:

SELECT *
FROM c

you can select specific properties:

SELECT
c.id,
c.name,
c.email
FROM c

This can reduce the amount of data returned to the application.

It can also make the application’s intent clearer.


15. Filtering Results

The WHERE clause filters documents.

For example:

SELECT *
FROM c
WHERE c.loyaltyLevel = "Gold"

Multiple conditions can be combined:

SELECT *
FROM c
WHERE c.country = "US"
AND c.loyaltyLevel = "Gold"

Other operators include:

=
!=
<
>
<=
>=
AND
OR

16. Parameterized Queries

Applications should avoid constructing queries by concatenating user input into SQL strings.

For example, this pattern should be avoided:

string query =
"SELECT * FROM c WHERE c.name = '" + userName + "'";

Instead, use parameterized queries.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.name = @name")
.WithParameter("@name", userName);

This approach:

  • Separates query structure from values.
  • Helps prevent injection-style problems.
  • Makes query reuse easier.
  • Provides cleaner application code.

17. Executing a Query

The SDK provides query APIs that allow the application to execute a QueryDefinition.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.country = @country")
.WithParameter("@country", "US");
using FeedIterator<Customer> iterator =
container.GetItemQueryIterator<Customer>(query);
while (iterator.HasMoreResults)
{
FeedResponse<Customer> response =
await iterator.ReadNextAsync();
foreach (Customer customer in response)
{
Console.WriteLine(customer.name);
}
}

This demonstrates an important concept:

Cosmos DB queries can return results in multiple pages.


18. FeedIterator and Pagination

A query may return more data than can reasonably be delivered in one response.

The SDK therefore exposes query results through an iterator.

Conceptually:

Query
Page 1
Page 2
Page 3
...

The application checks:

iterator.HasMoreResults

and retrieves each page using:

await iterator.ReadNextAsync()

This is important for scalability.

Exam tip

If a question asks how to process a potentially large Cosmos DB query result set, look for an answer involving:

FeedIterator / paginated results rather than loading the entire result set into memory.


19. Cross-Partition Queries

Suppose a container uses:

/country

as its partition key.

A query such as:

SELECT *
FROM c
WHERE c.country = "US"

provides a partition key value.

This allows Cosmos DB to target the appropriate partition.

However, a query such as:

SELECT *
FROM c
WHERE c.loyaltyLevel = "Gold"

does not specify the partition key.

The service may therefore need to query multiple partitions.

This is a cross-partition query.

Cross-partition queries are not inherently wrong. They are sometimes necessary.

However, they can require more resources and incur higher request charges than targeted queries.


20. Supplying a Partition Key to a Query

The SDK can provide the partition key value separately from the query itself.

For example:

var query = new QueryDefinition(
"SELECT * FROM c WHERE c.loyaltyLevel = @level")
.WithParameter("@level", "Gold");
var requestOptions = new QueryRequestOptions
{
PartitionKey = new PartitionKey("US")
};
using FeedIterator<Customer> iterator =
container.GetItemQueryIterator<Customer>(
query,
requestOptions: requestOptions);

The application is effectively telling Cosmos DB:

Search only the US partition.

This can significantly improve query efficiency when the access pattern permits it.


21. Query Performance and Request Units

Azure Cosmos DB measures database operations using Request Units (RUs).

The RU charge depends on factors such as:

  • The operation being performed.
  • The amount of data processed.
  • The complexity of the query.
  • Indexing.
  • Number of partitions involved.
  • Number of documents examined.
  • Amount of data returned.

A query that scans many partitions can consume substantially more RUs than a targeted query.

Applications should therefore design queries and partition keys together.


22. Indexing

Cosmos DB automatically indexes properties by default in many common configurations.

Indexes help Cosmos DB efficiently locate matching documents.

However, indexing every property isn’t always optimal for every workload.

Applications with specialized workloads may need to configure indexing policies to balance:

  • Query performance.
  • Write performance.
  • Storage.
  • RU consumption.

For the AI-200 exam, understand the relationship:

More/appropriate indexing
Efficient queries
Potentially lower query cost

But indexing isn’t a substitute for good partition-key design.


23. Querying Arrays and Nested Properties

Cosmos DB documents can contain nested objects and arrays.

For example:

{
"id": "1001",
"customer": {
"name": "John",
"country": "US"
},
"orders": [
{
"id": "O100",
"total": 125
},
{
"id": "O101",
"total": 200
}
]
}

A nested property can be accessed using dot notation:

SELECT c.customer.name
FROM c

Cosmos DB also supports array operations.

For example, the ARRAY_CONTAINS function can determine whether an array contains a particular value.

The ability to query nested JSON is one of the significant advantages of the NoSQL model.


24. Query Functions

Azure Cosmos DB for NoSQL supports many built-in functions.

Examples include functions for:

  • Strings.
  • Arrays.
  • Mathematical calculations.
  • Date/time operations.
  • Type checking.
  • Spatial data.

For example:

SELECT *
FROM c
WHERE CONTAINS(c.name, "Smith")

Another example:

SELECT *
FROM c
WHERE ARRAY_CONTAINS(c.tags, "AI")

The important exam concept is not memorizing every function but understanding that Cosmos DB’s query language provides rich querying capabilities against JSON documents.


25. Querying With ORDER BY

Results can be sorted using ORDER BY.

For example:

SELECT
c.id,
c.name,
c.total
FROM c
ORDER BY c.total DESC

This returns the highest totals first.

Queries can also use OFFSET and LIMIT patterns for controlled result sets.


26. Querying With Aggregates

Cosmos DB supports aggregate functions such as:

COUNT
SUM
AVG
MIN
MAX

For example:

SELECT VALUE COUNT(1)
FROM c
WHERE c.country = "US"

The VALUE keyword is useful when the desired result is the scalar value rather than an object containing a property.


27. Querying With SELECT VALUE

Consider:

SELECT c.name
FROM c

This returns objects such as:

{
"name": "John"
}

Using:

SELECT VALUE c.name
FROM c

returns the values directly:

"John"
"Mary"
"Robert"

This distinction can appear in exam questions.


28. Querying With Continuation Tokens

Cosmos DB can return a continuation token when a query result spans multiple pages.

The application can use the continuation token to continue retrieving results.

This is particularly useful for:

  • Large result sets.
  • Pagination.
  • Resuming queries.
  • Avoiding the need to retrieve everything at once.

The SDK’s iterator abstraction commonly handles this pagination process for the application.


29. Point Reads vs. Queries

One of the most important distinctions to understand is:

RequirementPreferred operation
Retrieve a known item by ID and partition keyPoint read
Find items matching conditionsQuery
Retrieve multiple items from a partitionQuery
Modify one known itemReplace/Patch
Create or update an itemUpsert
Remove one known itemDelete

Example

If you know:

id = customer-1001
country = US

use:

ReadItem(id, partitionKey)

rather than:

SELECT * FROM c WHERE c.id = "customer-1001"

The point read is designed specifically for this scenario.


30. Common Exam Traps

Trap 1: Confusing the database with the container

A database contains containers.

A container contains items.


Trap 2: Treating Cosmos DB like a relational database

Cosmos DB for NoSQL stores JSON documents and uses containers rather than relational tables.


Trap 3: Forgetting the partition key

The partition key is central to Cosmos DB scalability and query performance.


Trap 4: Using a query for a known item

If both the item ID and partition key are known, use a point read.


Trap 5: Creating a CosmosClient for every request

The client should generally be reused.


Trap 6: Building queries with string concatenation

Use parameterized queries with QueryDefinition.


Trap 7: Assuming every query is single-partition

A query that doesn’t target a partition may become a cross-partition query.


Trap 8: Loading all results into memory

Use the SDK’s iterator/pagination model to process potentially large result sets incrementally.


31. AI-200 Exam Takeaways

For this topic, make sure you can explain the following without referring to documentation:

  1. Cosmos DB hierarchy
    • Account → Database → Container → Item.
  2. CosmosClient
    • Establishes the SDK connection to the Cosmos DB account.
    • Should generally be reused.
  3. Authentication
    • Understand account keys versus Microsoft Entra ID and managed identity.
  4. Partition keys
    • Determine logical data distribution.
    • Are critical to scalability and query performance.
  5. Point reads
    • Use item ID + partition key when both are known.
  6. Queries
    • Use Cosmos DB’s SQL-like query language.
  7. Parameterized queries
    • Use QueryDefinition and parameters rather than string concatenation.
  8. Cross-partition queries
    • Can occur when a query isn’t targeted to a specific partition.
  9. FeedIterator
    • Used to process paginated query results.
  10. Request Units
    • Measure Cosmos DB resource consumption.
  11. Indexing
    • Supports efficient queries and can affect RU consumption.
  12. CRUD operations
    • Create, read, update, upsert, patch, and delete items through the SDK.

Practice Exam Questions

Question 1

An application running in Azure needs to connect to Azure Cosmos DB for NoSQL. The organization requires that no database credentials be stored in application configuration.

Which authentication approach should the developer prefer?

A. Store the Cosmos DB account key in the application’s source code.

B. Store the Cosmos DB connection string in an environment variable.

C. Use a managed identity with Microsoft Entra ID authentication and appropriate Cosmos DB permissions.

D. Create a new Cosmos DB account key whenever the application starts.

Answer: C

Explanation:
A managed identity allows an Azure-hosted application to authenticate without storing long-lived credentials in application code or configuration. The identity must have the appropriate permissions to access Cosmos DB. Hard-coded keys and connection strings introduce credential-management risks.


Question 2

A container uses /customerId as its partition key. An application needs to retrieve a specific item, and it already knows both the item’s id and customerId.

Which operation should the application use?

A. A point read using the item ID and partition key.

B. A cross-partition SQL query.

C. A query using ORDER BY.

D. A query using GROUP BY.

Answer: A

Explanation:
When the item ID and partition key are known, a point read is the appropriate operation. It directly addresses the item instead of executing a query across documents.


Question 3

A developer needs to allow users to search for customers by name. The name is supplied by the user at runtime.

Which approach should the developer use?

A. Concatenate the user input into the SQL string.

B. Encode the user’s input as Base64 and concatenate it into the SQL string.

C. Create a separate container for each possible customer name.

D. Use a parameterized QueryDefinition.

Answer: D

Explanation:
A parameterized query separates query structure from user-supplied values. The Cosmos DB SDK supports parameters through QueryDefinition.WithParameter(). This is preferable to dynamically concatenating user input into query strings.


Question 4

A Cosmos DB container is partitioned by /region. An application executes:

SELECT *
FROM c
WHERE c.productCategory = "AI"

The query does not specify a region.

What should the developer understand about this query?

A. It automatically becomes a point read.

B. It may require a cross-partition query.

C. It can only return one document.

D. Cosmos DB automatically changes the partition key for the query.

Answer: B

Explanation:
Because the query does not restrict the /region partition key, Cosmos DB may need to query multiple partitions. Cross-partition queries are supported, but they can consume more resources than targeted queries.


Question 5

An application executes a query that can return hundreds of thousands of documents. The developer wants to avoid loading all results into memory simultaneously.

Which SDK approach is most appropriate?

A. Use a FeedIterator and process the results page by page.

B. Convert the query into a point read.

C. Increase the item’s partition key value.

D. Retrieve the entire result set using a single string response.

Answer: A

Explanation:
Cosmos DB queries can return results in multiple pages. The SDK’s FeedIterator allows an application to retrieve and process each page incrementally, which is more appropriate for large result sets.


Question 6

An application repeatedly creates a new CosmosClient object every time it performs a database operation.

What should the developer do?

A. Create a new client for every item.

B. Create two clients for every request to provide redundancy.

C. Reuse a CosmosClient instance for the lifetime of the application.

D. Replace the SDK with direct HTTP calls for every operation.

Answer: C

Explanation:
CosmosClient is designed to be reused. Creating clients repeatedly introduces unnecessary connection-management overhead and can negatively affect application performance.


Question 7

A container uses /country as its partition key. An application frequently retrieves customers when both their customer ID and country are known.

Which design provides the most direct access to an individual customer?

A. Store all customers in a single partition.

B. Use a point read with the customer ID and country as the partition key value.

C. Run a cross-partition query for every customer.

D. Use ORDER BY country before retrieving the customer.

Answer: B

Explanation:
A point read using the item ID and partition key can directly locate an item. This is preferable to running a query when the application’s access pattern already provides both values.


Question 8

A developer wants to update only the status property of a large Cosmos DB document rather than replacing the entire document.

Which operation is most appropriate?

A. CreateItem

B. ReadItem

C. DeleteItem

D. Patch

Answer: D

Explanation:
Patch is designed for modifying specific properties or paths within an existing item without requiring the entire document to be replaced.


Question 9

A Cosmos DB application performs a query that searches across many physical partitions. The query consumes significantly more Request Units than a similar query that targets a single partition.

What is the most likely explanation?

A. Cross-partition queries can require work across multiple partitions.

B. Cosmos DB charges a fixed number of RUs for every query regardless of its scope.

C. Point reads always consume more RUs than cross-partition queries.

D. Partition keys have no relationship to query performance.

Answer: A

Explanation:
Queries that span multiple partitions may require Cosmos DB to perform work across those partitions, which can increase resource consumption. Designing partition keys around application access patterns can help reduce unnecessary cross-partition queries.


Question 10

A developer wants a query to return only customer names as scalar values instead of objects such as:

{
"name": "John Smith"
}

Which query should the developer use?

A.

SELECT *
FROM c

B.

SELECT c
FROM c

C.

SELECT VALUE c.name
FROM c

D.

SELECT OBJECT(c.name)
FROM c

Answer: C

Explanation:
SELECT VALUE returns the selected expression directly rather than wrapping it in a JSON object. Therefore:

SELECT VALUE c.name
FROM c

returns scalar values such as:

"John Smith"
"Mary Jones"

rather than objects containing a name property.


Final Exam Reminder

For AI-200, don’t think of Cosmos DB simply as “a NoSQL database that I can query.” Think about the relationship between data modeling, partitioning, SDK operations, queries, and performance.

The most important decision pattern is:

Know the item ID + partition key? → Point read.
Need to find items based on criteria? → Query.
Know the partition key? → Target the partition when possible.
Large result set? → Process pages with the SDK iterator.
User-supplied values? → Parameterize the query.
Azure-hosted application without stored credentials? → Prefer managed identity/Entra ID where supported.


Go to the AI-200 Exam Prep Hub main page

Implement a change feed processor to detect and handle new or updated items (AI-200 Exam Prep)

This post is a part of the AI-200: Developing AI Cloud Solutions on Azure  Exam Prep Hub.
This topic falls under these sections:
Develop AI solutions by using Azure data management services (25–30%)
   --> Develop AI solutions by using Azure Cosmos DB for NoSQL
      --> Implement a change feed processor to detect and handle new or updated items


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Overview

Azure Cosmos DB for NoSQL provides a change feed that records changes made to items in a container. Applications can consume this feed to react to data changes without repeatedly querying the entire container.

For the AI-200 exam, an important implementation pattern is the change feed processor. It provides a push-based mechanism for detecting changes and delivering them to application code for processing.

A change feed processor is particularly useful when an application needs to perform an action whenever items are created or updated, such as:

  • Processing newly submitted documents
  • Generating embeddings for newly created content
  • Updating a search index
  • Synchronizing data with another system
  • Running AI processing when new data arrives
  • Performing analytics or enrichment
  • Triggering downstream business workflows
  • Maintaining materialized or derived data

The change feed processor also handles important operational concerns such as checkpointing, load balancing, lease management, and recovery.


1. What Is the Azure Cosmos DB Change Feed?

The change feed is a persistent record of changes to items in an Azure Cosmos DB container.

Conceptually, it looks like this:

Application
|
| Creates/updates items
v
Azure Cosmos DB Container
|
| Change feed
v
Change Feed Processor
|
+--> Process new item
+--> Generate embedding
+--> Update search index
+--> Call downstream service
+--> Store derived data

Instead of repeatedly asking:

“Which items have changed since the last time I checked?”

the application can consume the change feed and process changes incrementally.

This makes the change feed especially useful for event-driven and near-real-time architectures.


2. Latest Version Change Feed Mode

For the AI-200 scenario involving detection of new or updated items, the default latest version change feed mode is particularly important.

In latest version mode:

  • Creates appear in the change feed.
  • Updates appear in the change feed.
  • Deletes do not appear.
  • If an item is changed multiple times before it is read, the feed provides the latest version rather than every intermediate version.

For example:

Item created
|
v
Status = "Pending"
|
v
Status = "Processing"
|
v
Status = "Completed"

If these changes occur before the consumer reads the feed, latest-version mode may expose the current version rather than every intermediate state.

Therefore, latest-version mode is appropriate when the application cares about the current state of changed items, rather than every individual mutation.

Important exam distinction

If an application must detect deletes or process every intermediate version, latest-version mode isn’t sufficient.

Azure Cosmos DB also supports all versions and deletes mode, which captures creates, updates, and deletes. That mode has additional requirements, including continuous backup, and is available for Azure Cosmos DB for NoSQL.


3. What Is a Change Feed Processor?

The change feed processor is a higher-level mechanism for consuming the Azure Cosmos DB change feed.

It uses a push model.

Rather than requiring your application to repeatedly pull batches and manage continuation state itself, the processor:

  1. Reads changes from the monitored container.
  2. Determines which changes need to be processed.
  3. Delivers batches of changes to your application code.
  4. Maintains processing state using a lease container.
  5. Distributes work among multiple processor instances.
  6. Recovers work when an instance fails.

The change feed processor is currently provided through the Azure Cosmos DB .NET V3 and Java V4 SDKs. Python and Node.js applications can consume the change feed using the pull model rather than the change feed processor library.


4. The Four Components of a Change Feed Processor

A key AI-200 concept is understanding the four major components.

4.1 Monitored Container

The monitored container is the Azure Cosmos DB container whose changes you want to process.

For example:

Database: AIApplication
Container: Documents
Partition key: /customerId

The processor monitors Documents.

When items are created or updated, those changes become available through the change feed.


4.2 Lease Container

The lease container stores the state used by the change feed processor to coordinate processing.

This is extremely important.

The lease container allows multiple processor instances to share the workload without processing the same lease simultaneously.

Conceptually:

                 Lease Container
                /       |       \
               /        |        \
              v         v         v
          Lease 1    Lease 2    Lease 3
             |          |          |
             v          v          v
          Worker A   Worker B   Worker C

The leases represent ownership and progress for portions of the change feed.

The lease container can be in the same Cosmos DB account as the monitored container or in a separate account.

Exam tip

If a question asks:

What component maintains the state of change feed processing?

The answer is generally:

The lease container.


5. Compute Instances

A compute instance hosts the change feed processor.

Examples include:

  • Azure Kubernetes Service pods
  • Azure App Service instances
  • Azure Virtual Machines
  • Long-running application processes
  • Hosted background services

For example:

AKS Cluster
Pod 1 --> Change Feed Processor
Pod 2 --> Change Feed Processor
Pod 3 --> Change Feed Processor

Each processor instance must have a unique instance name.

The processor distributes leases among the available instances.


6. The Delegate

The delegate is your application code that processes the changes.

For example, suppose an AI application stores documents in Cosmos DB.

When a document changes, the delegate might:

  1. Extract the text.
  2. Generate an embedding.
  3. Store the embedding.
  4. Update a vector index.
  5. Record processing status.

Conceptually:

Cosmos DB Change
|
v
Change Feed Processor
|
v
Delegate
|
+--> Extract text
|
+--> Generate embedding
|
+--> Store embedding
|
+--> Update AI search data

The delegate is therefore where the application’s business logic lives.


7. How the Processing Lifecycle Works

The basic lifecycle is:

Read change feed
|
v
Are there changes?
/ \
No Yes
| |
v v
Wait Send batch
| |
+------<-------+
|
v
Delegate succeeds?
/ \
No Yes
| |
v v
Retry from Update
checkpoint lease

More precisely, the processor:

  1. Reads the change feed.
  2. Waits if no changes are available.
  3. Sends a batch of changes to the delegate.
  4. Waits for successful processing.
  5. Updates the lease with the latest successfully processed position.
  6. Continues processing.

The checkpoint is therefore advanced after successful processing.


8. Why the Change Feed Processor Uses At-Least-Once Processing

One of the most important concepts for the exam is that the change feed processor provides an at-least-once delivery guarantee.

Suppose the processor reads:

Change A
Change B
Change C

and passes them to your delegate.

If the delegate fails before the checkpoint is successfully updated, the processor can process those changes again.

Therefore:

Change A
Change B
Change C
|
v
Process
|
X Failure
|
v
Retry
|
v
Change A
Change B
Change C

This means your application should generally be idempotent.


9. Why Idempotency Matters

An idempotent operation can safely be executed more than once without producing an incorrect final result.

For example, suppose the change feed processor receives:

{
"id": "document-123",
"status": "completed"
}

Your processing logic might update a downstream record:

document-123 -> completed

If the same change is processed twice, the final state remains:

document-123 -> completed

That is preferable to an operation such as:

balance = balance + 100

where processing the same event twice could incorrectly add the amount twice.

Exam rule

Design change feed handlers assuming a change may be delivered more than once.


10. Lease-Based Load Distribution

The change feed processor can distribute processing across multiple instances.

For example:

Change Feed
------------------------------------------------
Partition Range 1
Partition Range 2
Partition Range 3
Partition Range 4
------------------------------------------------
| | | |
v v v v
Worker 1 Worker 2 Worker 3 Worker 4

The lease container coordinates ownership of these workloads.

If one worker fails, its leases can eventually be acquired by another worker.

This provides fault tolerance without requiring the developer to manually coordinate workers.


11. Scaling the Change Feed Processor

Suppose you initially have:

Worker 1

and later add:

Worker 2
Worker 3

The change feed processor can redistribute leases among the workers.

Conceptually:

Before:
Worker 1
├── Lease 1
├── Lease 2
├── Lease 3
└── Lease 4
After scaling:
Worker 1
├── Lease 1
└── Lease 2
Worker 2
└── Lease 3
Worker 3
└── Lease 4

This allows processing to be parallelized.

However, simply adding instances does not mean that processing becomes infinitely parallel.

The available workload is constrained by the number of leases/partition ranges.

The number of processor instances should not exceed the number of available leases for meaningful distribution.


12. Partitioning and Change Feed Processing

Azure Cosmos DB containers are partitioned using a partition key.

For example:

Container: Documents
Partition key: /customerId

The change feed processor works with the underlying partition ranges.

Each range can be processed independently, allowing parallel processing.

This is one reason that selecting an appropriate partition key remains important even when using the change feed.

A poor partition key can create an uneven workload.


13. Starting Position

An important implementation detail is the processor’s starting position.

When a change feed processor is initialized for the first time, its starting point determines which changes it processes.

In latest-version mode, you can configure the processor to start from a specified time or from the beginning of the container’s lifetime.

For example:

Container history
|
|---- Change A
|---- Change B
|---- Change C
|---- Change D
|---- Change E
|
^
|
Start processor

If configured to begin at Change A, the processor can process the historical changes.

If configured to start from the current point, older changes aren’t processed.

Important

The starting-position configuration is used when initializing the processor. Once the lease container has established the processor’s state, changing the starting configuration doesn’t reset the existing checkpoint.


14. Change Feed Processor vs. Pull Model

There are two major approaches to consuming the change feed.

FeatureChange Feed ProcessorPull Model
Processing stylePushPull
Checkpoint managementLease containerApplication-managed continuation
Load balancingBuilt inApplication responsibility
Error/retry infrastructureBuilt inApplication responsibility
.NET supportYesYes
Java supportYesYes
PythonNot through processor libraryYes
Node.jsNot through processor libraryYes

The change feed processor is generally easier when you want Azure Cosmos DB to manage the mechanics of distributing work and maintaining processing state.


15. Change Feed Processor vs. Azure Functions Trigger

Another important distinction is between the change feed processor and the Azure Functions trigger for Cosmos DB.

Both can be used to build event-driven applications.

For example:

Cosmos DB
|
+----> Change Feed Processor
|
+----> Azure Functions Trigger

The change feed processor is useful when you need more direct control over a long-running processing application.

The Azure Functions trigger is useful when you want a serverless implementation.

The Azure Functions trigger also uses a lease container to maintain processing state.


16. Handling Processing Failures

Suppose your delegate encounters an exception:

Batch
|
v
Delegate
|
X Exception

The processor doesn’t simply assume the batch succeeded.

Because the checkpoint hasn’t advanced successfully, the processor can retry the batch.

This behavior produces the at-least-once guarantee.

Important design consideration

If a particular item consistently causes processing to fail, the processor can repeatedly encounter the same problem.

A robust application should therefore have an error-handling strategy.

For example:

Change
|
v
Process
|
X Failure
|
+--> Retry
|
+--> Persistent failure
|
v
Error/DLQ storage

An application might persist information about the failed change to another Cosmos DB container or another durable store so that the processing pipeline doesn’t remain permanently blocked by one problematic change.


17. Monitoring Change Feed Lag

A change feed processor can fall behind the incoming changes.

For example:

New changes:
1000 events/sec
Processing:
700 events/sec
Result:
Change feed lag increases

The change feed estimator can be used to monitor processor progress and estimate lag.

This can help identify:

  • Insufficient processing capacity
  • Slow downstream services
  • Throttling
  • Application errors
  • Lease problems
  • Processing bottlenecks

18. Request Units and the Change Feed

Change feed processing isn’t free from a Cosmos DB throughput perspective.

Reading the change feed from the monitored container consumes request units (RUs).

Operations involving the lease container also consume RUs.

For example:

Monitored Container
|
+--> Change feed reads --> RU consumption
Lease Container
|
+--> Lease reads
+--> Lease updates
+--> Lease coordination
|
v
RU consumption

If the monitored or lease container experiences throttling, change processing can be delayed.

This is especially important when deploying multiple processor instances or multiple processing workloads that share a lease container.


19. Lease Container Permissions

When Microsoft Entra ID authentication is used, the processor’s identity needs appropriate permissions.

The monitored container requires permissions related to:

  • Reading account metadata
  • Reading the change feed

The lease container requires permissions for operations such as:

  • Reading items
  • Creating items
  • Replacing items
  • Deleting items
  • Executing queries

This is an important distinction:

The application doesn’t just need permission to read the monitored data; it also needs permission to maintain the processor’s lease state.


20. Using a Global Endpoint

For a change feed processor workload, Microsoft recommends using the global Cosmos DB endpoint rather than a region-specific endpoint.

For example:

Preferred:
https://contoso.documents.azure.com

rather than:

https://contoso-westus.documents.azure.com

Regional preferences should be configured through the appropriate SDK region settings.

This is important because lease documents are scoped to the configured endpoint. Changing endpoints can result in separate lease state.


21. A Typical AI Application Architecture

Consider an AI document-processing application.

A user uploads a document, and the application stores metadata in Cosmos DB.

The desired workflow is:

User
|
v
Application
|
v
Cosmos DB
|
| New/updated document
v
Change Feed
|
v
Change Feed Processor
|
v
Processing Delegate
|
+--> Extract document text
|
+--> Generate embedding
|
+--> Store vector
|
+--> Update search metadata
|
+--> Notify downstream application

This architecture avoids repeatedly scanning the entire container looking for new work.

It also allows the processing workload to scale independently from the application that writes the data.


22. Example .NET Concept

A simplified .NET implementation conceptually looks like this:

var processor = monitoredContainer
.GetChangeFeedProcessorBuilder<MyDocument>(
"documentProcessor",
HandleChangesAsync)
.WithInstanceName("worker-01")
.WithLeaseContainer(leaseContainer)
.Build();
await processor.StartAsync();

The important concepts are:

  • monitoredContainer — where changes originate.
  • leaseContainer — where processing state is maintained.
  • HandleChangesAsync — your business logic.
  • WithInstanceName — uniquely identifies the processor instance.
  • Processor startup — begins monitoring the change feed.

The exact SDK APIs can vary by SDK version, so the exam focus should be on understanding the architecture and responsibilities rather than memorizing every method signature. The current change feed processor documentation identifies .NET V3 and Java V4 as the SDKs that provide the processor library.


23. Important Exam Concepts to Remember

For AI-200, make sure you can distinguish the following:

Monitored container

Contains the data whose changes are being detected.

Lease container

Maintains processor state and coordinates work across instances.

Delegate

Contains the application’s processing logic.

Compute instance

Hosts the change feed processor.

Latest-version mode

Captures the latest versions of creates and updates; deletes aren’t included.

All versions and deletes mode

Captures creates, updates, and deletes, including intermediate changes.

Checkpoint

Records the latest successfully processed position.

At-least-once delivery

A change can be processed more than once, so handlers should be idempotent.

Pull model

The application manages reading, continuation state, and processing coordination.

Change feed processor

Provides a higher-level push-based processing model with lease-based coordination.


Practice Exam Questions

Question 1

An AI application stores documents in an Azure Cosmos DB for NoSQL container. Whenever a document is created or updated, the application must perform additional processing. The development team wants Azure Cosmos DB to manage checkpointing and distribute processing across multiple application instances.

Which solution should the team implement?

A. A timer-triggered Azure Function that scans the container

B. Periodic SQL queries

C. Azure Cosmos DB analytical store queries

D. Change feed processor

Answer: D

Explanation

The change feed processor is designed to process changes incrementally and provides built-in lease-based coordination and checkpoint management. It can distribute change feed processing across multiple instances.

The other approaches require the application to identify changes itself and are less appropriate for event-driven incremental processing.


Question 2

A change feed processor processes a batch of changes successfully but fails before the processing state is checkpointed. What should the application expect?

A. The changes are permanently discarded

B. The batch can be delivered again

C. The entire Cosmos DB container is automatically restored

D. The change feed is permanently disabled

Answer: B

Explanation

The change feed processor provides at-least-once delivery. If processing succeeds but the checkpoint isn’t successfully advanced, the processor can process the same changes again.

Application processing logic should therefore be designed to be idempotent.


Question 3

Which component is primarily responsible for maintaining the state and coordinating ownership of change feed processing across multiple processor instances?

A. Monitored container

B. Compute instance

C. Lease container

D. Application Gateway

Answer: C

Explanation

The lease container stores the state used by the change feed processor to coordinate processing across instances.

The monitored container provides the source data, while compute instances host the processing application.


Question 4

An application uses the default latest-version change feed mode. An item is created and then updated three times before the processor reads the changes. What behavior should the application expect?

A. Only the delete operation is returned

B. All four versions are guaranteed to be returned

C. No changes are returned because the item changed multiple times

D. The latest version of the item is available rather than every intermediate version

Answer: D

Explanation

Latest-version mode provides the latest version of an item in the feed rather than preserving every intermediate change between reads.

If the application needs every create, update, and delete operation, it should consider all versions and deletes mode instead.


Question 5

A developer is building a change feed processor application that will run on three AKS pods. What is the primary purpose of assigning each processor instance a unique instance name?

A. To identify each compute instance participating in lease distribution

B. To specify the Cosmos DB partition key

C. To determine the consistency level

D. To select the Cosmos DB database

Answer: A

Explanation

Each change feed processor instance should have a unique instance name. The processor uses the instances and leases to distribute processing work across the deployment.

The instance name is unrelated to partition-key selection, database selection, or consistency configuration.


Question 6

An AI application must react when documents are deleted from an Azure Cosmos DB for NoSQL container. Which change feed capability is most appropriate?

A. Latest-version change feed mode

B. All versions and deletes change feed mode

C. Increasing the consistency level

D. Increasing the container’s RU/s

Answer: B

Explanation

All versions and deletes mode captures creates, updates, and deletes.

Latest-version mode does not capture deletes.

All versions and deletes mode has additional requirements, including continuous backup, and is specifically available for Azure Cosmos DB for NoSQL.


Question 7

A change feed processor application experiences increasingly large processing delays. Investigation shows that the application is processing changes correctly but cannot keep up with incoming changes.

Which metric or capability is most useful for determining whether the processor is falling behind?

A. Azure DNS query count

B. Azure Storage blob count

C. Change feed estimator

D. Azure Resource Manager activity log

Answer: C

Explanation

The change feed estimator can be used to estimate the lag between the changes available in the monitored container and the progress of the change feed processor.

This can help identify processing bottlenecks and determine whether additional processing capacity may be necessary.


Question 8

A change feed processor’s delegate updates an external database. The same change may occasionally be delivered more than once. What should the developer do?

A. Disable checkpointing

B. Use an idempotent processing design

C. Increase the Cosmos DB consistency level to strong

D. Disable leases

Answer: B

Explanation

The change feed processor provides at-least-once delivery, meaning a change can be processed more than once.

The delegate should therefore be designed to handle duplicate processing safely. Idempotent operations are one of the most important techniques for doing this.


Question 9

A company runs several change feed processor instances and notices that the lease container is experiencing RU throttling. What is a likely consequence?

A. Change feed processing can be delayed

B. All documents in the monitored container are deleted

C. The Cosmos DB account automatically switches to strong consistency

D. The application automatically receives unlimited RU/s

Answer: A

Explanation

The lease container performs operations that consume request units. If the lease container is throttled, lease coordination and renewal can be delayed, which can delay change feed processing.

The monitored container’s change feed reads also consume RUs. Both the monitored and lease containers should therefore be appropriately provisioned.


Question 10

A development team wants to consume an Azure Cosmos DB change feed from a Python application. They want to use the built-in change feed processor library that automatically handles lease-based processing.

What should the team do?

A. Use the .NET change feed processor library from Python

B. Use the Java change feed processor library from Python

C. Use the change feed pull model from Python

D. Use Azure SQL Database instead

Answer: C

Explanation

The Azure Cosmos DB change feed processor library is available for .NET and Java. Python applications can consume the change feed using the pull model, where the application manages continuation state and processing.


Key Takeaways

For the AI-200 exam, the most important ideas are:

  1. The change feed records changes to Azure Cosmos DB items.
  2. The change feed processor provides a push-based processing model.
  3. The monitored container is the source of changes.
  4. The lease container stores processing state and coordinates workers.
  5. The delegate contains the application’s change-processing logic.
  6. Multiple processor instances can share the workload through leases.
  7. Change feed processing provides at-least-once delivery.
  8. Handlers should therefore be idempotent.
  9. Latest-version mode captures creates and updates but not deletes.
  10. All versions and deletes mode captures creates, updates, and deletes.
  11. The change feed processor library is available for .NET and Java; Python and Node.js use the pull model.
  12. Change feed processing consumes RUs.
  13. Throttling of the monitored or lease container can delay processing.
  14. The change feed estimator can help identify processing lag.
  15. The lease container is fundamental to distributed, fault-tolerant change feed processing.

The exam’s scenario questions are likely to test whether you can select the right change feed mode, processing model, lease architecture, error-handling strategy, and scaling approach, rather than simply recognizing the term “change feed.”


Go to the AI-200 Exam Prep Hub main page

Practice Questions: Describe Azure Cosmos DB APIs (DP-900 Exam Prep)

Practice Questions


Question 1

Which API in Azure Cosmos DB uses a SQL-like query language?

A. Gremlin API
B. Cassandra API
C. Core (SQL) API
D. Table API

Answer: C

Explanation:
The Core (SQL) API uses a SQL-like syntax to query JSON documents.


Question 2

Which Azure Cosmos DB API is BEST suited for applications currently using MongoDB?

A. Core (SQL) API
B. MongoDB API
C. Cassandra API
D. Table API

Answer: B

Explanation:
The MongoDB API provides compatibility with MongoDB drivers and queries.


Question 3

Which API should you choose for graph-based data and relationships?

A. Table API
B. Cassandra API
C. Gremlin API
D. MongoDB API

Answer: C

Explanation:
The Gremlin API is designed for graph data models and relationship analysis.


Question 4

Which API in Cosmos DB is most similar to Azure Table Storage?

A. MongoDB API
B. Cassandra API
C. Table API
D. Core (SQL) API

Answer: C

Explanation:
The Table API uses a key-value model similar to Azure Table Storage.


Question 5

Which statement about Azure Cosmos DB APIs is TRUE?

A. You can switch APIs after creating the account
B. Each API uses a different query language and data model
C. All APIs use T-SQL
D. APIs determine storage redundancy

Answer: B

Explanation:
Each API has its own data model and query language.


Question 6

Which API would you choose for a distributed system currently using Apache Cassandra?

A. Core (SQL) API
B. MongoDB API
C. Cassandra API
D. Gremlin API

Answer: C

Explanation:
The Cassandra API supports Cassandra Query Language (CQL) and workloads.


Question 7

Which API is the default and most commonly used in Azure Cosmos DB?

A. Table API
B. Gremlin API
C. Core (SQL) API
D. Cassandra API

Answer: C

Explanation:
The Core (SQL) API is the most commonly used and general-purpose API.


Question 8

Which scenario is BEST suited for the Table API?

A. Complex graph traversal
B. Large-scale relational queries
C. Simple key-value data storage
D. Document-based analytics

Answer: C

Explanation:
The Table API is ideal for simple, scalable key-value storage.


Question 9

What is a key consideration when choosing a Cosmos DB API?

A. The size of the storage account
B. The number of virtual machines
C. The application’s existing data model and query language
D. The type of Azure subscription

Answer: C

Explanation:
API selection depends on existing technologies and data models.


Question 10

Which statement best describes Azure Cosmos DB APIs?

A. Each API uses a different underlying database engine
B. APIs provide different ways to interact with the same service
C. APIs are only used for relational data
D. APIs determine the pricing tier only

Answer: B

Explanation:
All APIs use the same Cosmos DB service but offer different interfaces and models.


✅ Quick Exam Takeaways

✔ Cosmos DB APIs allow different ways to interact with the same service

✔ APIs:

  • Core (SQL) → SQL-like queries (most common)
  • MongoDB → MongoDB compatibility
  • Cassandra → Distributed systems (CQL)
  • Table → Key-value storage
  • Gremlin → Graph data

✔ Key concepts:

  • API choice depends on data model and existing system
  • API selection is permanent after creation

✔ Exam tip:
👉 Match data model → API type


Go to the DP-900 Exam Prep Hub main page.

Describe Azure Cosmos DB APIs (DP-900 Exam Prep)

This post is a part of the DP-900: Microsoft Azure Data Fundamentals Exam Prep Hub. 
This topic falls under these sections:
Describe considerations for working with non-relational data on Azure (15–20%)
--> Describe Capabilities and Features of Azure Cosmos DB
--> Describe Azure Cosmos DB APIs


Note that there are 10 practice questions (with answers and explanations) for each section to help you solidify your knowledge of the material. Also, there are 2 practice tests with 60 questions each available on the hub below the exam topics section.

Azure Cosmos DB supports multiple APIs that allow developers to interact with the database using different data models and familiar query languages.

For the DP-900 exam, you should understand what these APIs are, how they differ, and when to use each one.


What Are Azure Cosmos DB APIs?

APIs in Azure Cosmos DB define:

  • How data is structured
  • How it is queried
  • Which tools and SDKs are used

✔ Each API provides a different way to interact with the same underlying Cosmos DB service.


Why Multiple APIs?

Azure Cosmos DB supports multiple APIs to:

  • Allow developers to use familiar tools
  • Enable easy migration from existing systems
  • Support different types of applications and data models

💡 Key idea:
👉 Choose the API based on your application’s existing technology or data model


Core Azure Cosmos DB APIs


1. Core (SQL) API

Also known as the SQL API.

Key Features

  • Uses a SQL-like query language
  • Stores data as JSON documents
  • Most commonly used API

Use Cases

  • New application development
  • General-purpose NoSQL workloads

Best for: Developers familiar with SQL who want flexibility


2. MongoDB API

Key Features

  • Compatible with MongoDB drivers and tools
  • Uses MongoDB query syntax

Use Cases

  • Migrating existing MongoDB applications
  • Applications already using MongoDB

Best for: MongoDB workloads moving to Azure


3. Cassandra API

Key Features

  • Compatible with Apache Cassandra
  • Supports Cassandra Query Language (CQL)

Use Cases

  • Large-scale distributed workloads
  • Applications using Cassandra

Best for: Cassandra-based systems needing cloud scalability


4. Table API

Key Features

  • Similar to Azure Table Storage
  • Key-value data model
  • Uses OData-based queries

Use Cases

  • Simple key-value workloads
  • Applications already using Table Storage

Best for: Lightweight, scalable key-value scenarios


5. Gremlin API

Key Features

  • Supports graph data models
  • Uses Gremlin query language

Use Cases

  • Graph-based applications
  • Relationship-heavy data

Best for: Social networks, recommendation engines, network analysis


Key Differences Between APIs

APIData ModelQuery LanguageBest For
Core (SQL)Document (JSON)SQL-likeGeneral-purpose apps
MongoDBDocumentMongoDB queryMongoDB migration
CassandraWide-columnCQLDistributed systems
TableKey-valueODataSimple scalable storage
GremlinGraphGremlinRelationship-based data

Important Concepts for DP-900


1. Same Service, Different Interfaces

All APIs run on Azure Cosmos DB, but:

  • Each API has its own endpoint
  • Each uses different query syntax
  • Each supports different SDKs

2. API Choice Is Permanent

  • You choose the API when creating a Cosmos DB account
  • You cannot switch APIs later

3. Performance and Features Are Shared

  • Global distribution
  • Low latency
  • High availability
  • Scalability

✔ These benefits apply regardless of API choice.


When to Choose Each API

  • Core (SQL) API → Default choice for most applications
  • MongoDB API → Existing MongoDB apps
  • Cassandra API → Distributed, large-scale systems
  • Table API → Simple key-value workloads
  • Gremlin API → Graph relationships

Why This Matters for DP-900

On the exam, you may be asked to:

  • Identify the correct API for a scenario
  • Match APIs to data models
  • Understand why multiple APIs exist
  • Recognize migration scenarios

Summary — Exam-Relevant Takeaways

✔ Azure Cosmos DB supports multiple APIs:

  • Core (SQL) API
  • MongoDB API
  • Cassandra API
  • Table API
  • Gremlin API

✔ Each API:

  • Uses a different data model
  • Has its own query language

✔ Key concept:
👉 Choose the API based on your application’s needs or existing system

✔ Important:

  • API choice is fixed at creation
  • All APIs benefit from Cosmos DB features (scalability, global distribution)

Go to the Practice Exam Questions for this topic.

Go to the DP-900 Exam Prep Hub main page.

Identify use cases for Azure Cosmos DB (DP-900 Exam Prep)

This post is a part of the DP-900: Microsoft Azure Data Fundamentals Exam Prep Hub. 
This topic falls under these sections:
Describe considerations for working with non-relational data on Azure (15–20%)
--> Describe capabilities and features of Azure Cosmos DB
--> Identify use cases for Azure Cosmos DB


Note that there are 10 practice questions (with answers and explanations) for each section to help you solidify your knowledge of the material. Also, there are 2 practice tests with 60 questions each available on the hub below the exam topics section.

Azure Cosmos DB is a fully managed, globally distributed database service designed for modern applications that require low latency, massive scalability, and flexible data models.

For the DP-900 exam, you should understand when and why to use Azure Cosmos DB, especially compared to other Azure storage and database services.


What Is Azure Cosmos DB?

Azure Cosmos DB is a NoSQL, multi-model database service that supports:

  • Global distribution across multiple regions
  • Low-latency reads and writes
  • Automatic scaling
  • Multiple APIs (Core SQL, MongoDB, Cassandra, Table, Gremlin)

✔ It is designed for high-performance, internet-scale applications.


Key Characteristics That Drive Use Cases

Understanding Cosmos DB use cases starts with its capabilities:

1. Global Distribution

  • Replicate data across multiple Azure regions
  • Users access data from the closest region

✔ Enables global applications with low latency


2. Low Latency

  • Single-digit millisecond response times
  • Ideal for real-time applications

3. Massive Scalability

  • Scales throughput and storage independently
  • Handles millions of requests per second

4. Flexible Schema

  • Schema-less (JSON-based data model)
  • Supports evolving application requirements

5. Multiple APIs

  • Supports different data models:
    • SQL (Core API)
    • MongoDB
    • Cassandra
    • Table
    • Gremlin (graph)

✔ Allows developers to use familiar tools and frameworks


Common Use Cases for Azure Cosmos DB


1. Global Web and Mobile Applications

Scenario

Applications with users distributed worldwide.

Why Cosmos DB?

  • Global distribution
  • Low latency access
  • High availability

✔ Example:

  • Social media platforms
  • E-commerce applications

2. Real-Time Personalization

Scenario

Applications that tailor content to users instantly.

Why Cosmos DB?

  • Fast read/write performance
  • Flexible schema

✔ Example:

  • Product recommendations
  • Personalized dashboards

3. IoT and Telemetry Data

Scenario

Large volumes of streaming data from devices.

Why Cosmos DB?

  • High ingestion rates
  • Scalable storage
  • Schema flexibility

✔ Example:

  • Sensor data collection
  • Smart devices

4. Gaming Applications

Scenario

Online games requiring real-time interactions.

Why Cosmos DB?

  • Low latency
  • Global availability
  • High throughput

✔ Example:

  • Leaderboards
  • Player profiles
  • Game state storage

5. E-commerce Platforms

Scenario

High-traffic applications with variable workloads.

Why Cosmos DB?

  • Elastic scalability
  • Fast performance
  • Global distribution

✔ Example:

  • Shopping carts
  • Product catalogs

6. Content Management Systems

Scenario

Managing diverse and evolving content.

Why Cosmos DB?

  • Schema-less design
  • Flexible data models

✔ Example:

  • Blogs
  • Media platforms

7. Event-Driven and Microservices Architectures

Scenario

Modern distributed applications.

Why Cosmos DB?

  • Scales independently per service
  • Supports high-throughput operations

✔ Example:

  • Microservices storing independent datasets

When NOT to Use Azure Cosmos DB

Cosmos DB is not ideal when:

  • You need complex joins and relational queries
  • You require strict relational consistency across multiple tables
  • Your workload is small and cost-sensitive

✔ In these cases, relational databases like Azure SQL may be more appropriate.


Cosmos DB vs Other Azure Storage Options

ServiceBest For
Blob StorageUnstructured files (images, videos)
Azure FilesFile shares
Table StorageSimple key-value storage
Cosmos DBGlobal, high-performance NoSQL apps

Why This Matters for DP-900

On the exam, you may be asked to:

  • Identify appropriate Cosmos DB use cases
  • Choose Cosmos DB for global, low-latency applications
  • Compare it with other Azure storage services
  • Recognize scenarios requiring scalability and flexibility

Summary — Exam-Relevant Takeaways

✔ Azure Cosmos DB = globally distributed NoSQL database

✔ Key strengths:

  • Low latency
  • Global distribution
  • Massive scalability
  • Flexible schema

✔ Common use cases:

  • Global apps
  • Real-time personalization
  • IoT and telemetry
  • Gaming
  • E-commerce

✔ Not suitable for:

  • Complex relational workloads
  • Heavy join operations

✔ Key decision factor:
👉 High scale + low latency + global users = Cosmos DB


Go to the Practice Exam Questions for this topic.

Go to the DP-900 Exam Prep Hub main page.

Practice Questions: Identify use cases for Azure Cosmos DB (DP-900 Exam Prep)

Practice Questions


Question 1

Which scenario is BEST suited for Azure Cosmos DB?

A. Running complex SQL joins across multiple tables
B. Storing structured financial transactions with strict relational constraints
C. Supporting a globally distributed mobile application with low latency
D. Hosting a traditional on-premises file share

Answer: C

Explanation:
Cosmos DB is ideal for globally distributed applications requiring low latency.


Question 2

Which type of application benefits MOST from Cosmos DB’s global distribution capabilities?

A. Local desktop application
B. Single-region reporting system
C. Global e-commerce website
D. Batch processing system

Answer: C

Explanation:
Global applications benefit from multi-region replication and low latency.


Question 3

Which use case is BEST suited for Cosmos DB?

A. Data warehouse for historical reporting
B. IoT application collecting real-time sensor data
C. Relational database with complex joins
D. File storage for images

Answer: B

Explanation:
Cosmos DB is optimized for high-ingestion, real-time data scenarios like IoT.


Question 4

Why is Cosmos DB suitable for real-time personalization scenarios?

A. It enforces strict relational schemas
B. It supports high-latency operations
C. It provides low-latency read/write performance
D. It requires predefined schemas

Answer: C

Explanation:
Low latency enables instant updates and responses for personalization.


Question 5

Which application would MOST benefit from Cosmos DB?

A. Payroll system requiring strict ACID compliance across multiple tables
B. Static website hosting images
C. Gaming application storing player state globally
D. Spreadsheet-based reporting system

Answer: C

Explanation:
Gaming apps require low latency, high throughput, and global availability.


Question 6

Which scenario is NOT a good fit for Cosmos DB?

A. Global content management system
B. Real-time analytics dashboard
C. Complex relational reporting with joins
D. Social media application

Answer: C

Explanation:
Cosmos DB is not ideal for complex relational queries or joins.


Question 7

Which feature of Cosmos DB makes it ideal for microservices architectures?

A. Fixed schema design
B. Independent scalability for each service
C. Requirement for relational constraints
D. Limited throughput options

Answer: B

Explanation:
Each microservice can scale independently using Cosmos DB.


Question 8

Which use case involves storing flexible, evolving data structures?

A. Financial ledger system
B. Product catalog with changing attributes
C. Relational reporting system
D. Fixed-schema inventory system

Answer: B

Explanation:
Cosmos DB’s schema-less design supports evolving data models.


Question 9

Which scenario best demonstrates Cosmos DB’s high-throughput capabilities?

A. Processing monthly reports
B. Handling millions of real-time user requests
C. Archiving old documents
D. Storing backup files

Answer: B

Explanation:
Cosmos DB is designed for high-throughput, real-time workloads.


Question 10

Which Azure service would you choose for a globally distributed application requiring millisecond response times?

A. Azure Blob Storage
B. Azure Files
C. Azure Cosmos DB
D. Azure Table Storage

Answer: C

Explanation:
Cosmos DB is specifically designed for low-latency, globally distributed applications.


✅ Quick Exam Takeaways

✔ Cosmos DB = global, low-latency NoSQL database

✔ Best for:

  • Global web/mobile apps
  • IoT and telemetry
  • Gaming
  • Real-time personalization
  • Microservices

✔ Key strengths:

  • Global distribution
  • Massive scalability
  • Flexible schema
  • High throughput

✔ Not ideal for:

  • Complex joins
  • Strict relational workloads

✔ Exam tip:
👉 If you see “global + real-time + high scale” → think Cosmos DB


Go to the DP-900 Exam Prep Hub main page.