Cosmos DB: RUs, Indexing Policies and Consistency Levels
30-second answer
Every Cosmos DB operation costs Request Units (RUs): about 1 RU for a 1 KB point read, more for writes and queries. By default the indexing policy indexes every property, which makes filters cheap but writes expensive, so you exclude paths you never filter on (such as a big /embedding/* array) and add composite indexes for multi-property ORDER BY. Consistency levels trade freshness for cost and latency: Strong, Bounded staleness, Session (the default), Consistent prefix and Eventual. Strong and Bounded staleness reads cost about twice the RUs of the weaker levels.
Exam objective: 2.1.2 Optimize query performance and Request Units (RUs) consumption by using indexing policies and consistency levels. (Skills measured as of October 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Every operation costs <strong>Request Units</strong>. Run a query that filters on the partition key.
👆 Click the glowing item in the portal to continue
Read the steps as text
- Every operation costs Request Units. Run a query that filters on the partition key.
- Open Query Stats. Under 3 RUs, because only one partition was read.
- Filter on name instead and the query fans out to every partition: 5× the cost for one item.
- By default every property is indexed, so every write pays to index long fields like description. Exclude / and include only the paths you filter or sort on.
- Writes now cost less than half. Reads on the included paths still use the index.
- Set the account’s default consistency. A client can ask for weaker consistency per request, never stronger.
🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.
🖱️ Drag to rotate · scroll or pinch to zoom
Indexing and consistency
By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big embedding array. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual.
🤔 What happens if…
Read this tour as text
- Text becomes a vector. An embedding model turns text into a list of numbers, a vector (1,536 numbers for
text-embedding-3-small). Texts that mean similar things get vectors that sit close together, so "refund" lands near "money back". - Cosmos DB: items, partitions, RUs. In Azure Cosmos DB for NoSQL, JSON items live in containers, spread across logical partitions by the partition key. Every operation costs Request Units (RUs). A point read by id and partition key costs about 1 RU. A query that scans every partition costs far more.
- Indexing and consistency. By default Cosmos DB indexes every property, so writes cost more RUs. An indexing policy can exclude paths you never filter on, such as the big
embeddingarray. Consistency levels trade freshness for speed and cost: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual. - Vector search in Cosmos DB. A vector embedding policy tells Cosmos DB where the vectors are, their dimensions and distance function. A vector index makes search fast:
diskANNorquantizedFlatfor large sets, orflatfor exact search on small vectors (up to 505 dimensions). ThenORDER BY VectorDistance(c.embedding, @q)returns the closest items. - Change feed. The change feed is an ordered log of inserts and updates in a container (deletes only show up in the *all versions and deletes* mode). A change feed processor reads it with a lease container that remembers how far each worker got, so a new product can be embedded the moment it’s saved.
- PostgreSQL with pgvector. In Azure Database for PostgreSQL, the pgvector extension adds a
vector(1536)column type. Without an index, every search compares against every row (a sequential scan). An HNSW or IVFFlat index finds near neighbours fast, trading a little recall for a lot of speed. - RAG with a metadata filter. Retrieval-augmented generation (RAG): embed the question, fetch the closest chunks (
ORDER BY embedding <=> $1 LIMIT 5), filter by metadata such astenant_idorlang, then send those chunks to the model as context. The answer is grounded in your own data. - Azure Managed Redis. Azure Managed Redis keeps hot data in memory. Cache-aside: check Redis, and on a miss read the database and store the result with a TTL. When data changes, invalidate the key. Redis can also hold a vector index for fast similarity search, for example a semantic cache of answers.
Every Cosmos DB call has a price in request units. Create an orders container, read data three ways from Python and compare the bill, then change consistency and indexing and watch the numbers move.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
Writes cost 40 RUs each and the bill keeps climbing.
😊 THE SOLUTION
Trim the indexing policy and pick the right consistency level.
- Indexing every property✓ Exclude paths you never query
- Strong consistency everywhere✓ Session is usually enough
- Unknown query cost✓ Read the request charge
Start with a question
Your Cosmos DB bill doubled after you started storing embeddings, but you only added one field. What happened?
Picture a library that writes an index card for every word in every book. Finding a book is quick. But each new book means hundreds of new cards, and the librarian spends all day writing them.
That’s Cosmos DB’s default. It indexes every property, including your new 1,536-number embedding array. Each write now pays for indexing all of those numbers, in Request Units. You fix it with the indexing policy: tell it which paths to skip. Then you look at the other dial that changes cost, the consistency level.
Explain it like I’m 10
Visual: RUs, indexing and consistency in motion
See where the RUs go: a point read, a fan-out query, an embedding that every write has to index, and the consistency slider.
Read the video script
- Items live in logical partitionsA Cosmos DB container spreads its items across logical partitions. The partition key, here slash category, decides where each one lives. Every kettle goes in the kettles partition.
- Point read: about 1 RUWhen you know an item's id and its partition key, you do a point read. Cosmos DB goes straight to that one item. For a one kilobyte item, that's about one request unit.
- No partition key? It fans outRun a query without the partition key, and it fans out to every partition. Each one does its share of the work, so the charge climbs. These numbers are examples, but the gap is real.
- Every path is indexed by defaultBy default, Cosmos DB indexes every property. Add a 1,536 number embedding, and every write pays to index all of those numbers too.
- Skip indexing /embedding/*Put slash embedding slash star in the excluded paths, and writes stop paying for it. A vector index can still cover that field. Just don't exclude a path that a query filters on.
- Consistency is a sliderThe other dial is consistency. It runs from Strong to Eventual, and Session is the default. Within your own session, you always read your own writes.
- Stronger reads cost about twiceSlide to Strong or Bounded staleness, and reads cost about twice as much, because they check two replicas. A client can choose a weaker level than the account default, never a stronger one.
The technical explanation
Request Units
An RU bundles CPU, memory and IO into one number. Rough costs to keep in your head:
| Operation | Typical cost |
|---|---|
| Point read, 1 KB item | about 1 RU |
| Write (create, replace, upsert), 1 KB item, default indexing | about 5 RUs or more, and more with every indexed property |
| Query | depends on items scanned, index use, result size and partitions touched |
You buy throughput in one of three ways: provisioned manual (fixed RU/s), provisioned autoscale (you set a maximum and it scales between 10% and that maximum), or serverless (pay per RU used, for spiky or small workloads). Go over the RU/s you have and the service returns 429 Too Many Requests. The SDK retries for you, but steady 429s mean you need more throughput or cheaper operations.
Always measure. The response header x-ms-request-charge tells you the exact charge:
container.query_items(query="SELECT * FROM c WHERE c.category = @c",
parameters=[{"name": "@c", "value": "kettles"}],
partition_key="kettles")
print(container.client_connection.last_response_headers["x-ms-request-charge"])
Indexing policy
The default policy indexes everything with range indexes, uses consistent indexing mode (the index updates with every write), and excludes only the system _etag path. That’s great for ad hoc filters and expensive for writes when items are big.
Here’s a lean policy for a product container that stores embeddings:
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{ "path": "/*" }
],
"excludedPaths": [
{ "path": "/\"_etag\"/?" },
{ "path": "/embedding/*" },
{ "path": "/description/?" }
],
"compositeIndexes": [
[
{ "path": "/category", "order": "ascending" },
{ "path": "/price", "order": "ascending" }
]
]
}
How to read the paths:
/*means every path under the root./description/?means the scalar value atdescription./embedding/*means everything underembedding, including every element of the array.- You can flip it round: include only the paths you filter on (
/category/?,/price/?) and exclude/*. That’s the leanest option for write-heavy containers.
Composite indexes are needed for ORDER BY on more than one property, and they help queries that filter on one property and sort on another. The order (ascending or descending) has to match the query, or be its exact reverse.
Changing the policy on an existing container is allowed. Cosmos DB rebuilds the index in the background using spare RUs, and queries keep working while it does.
Consistency levels
Consistency is set as the account default and applies to reads. A client or a single request can choose a weaker level than the default, never a stronger one.
| Level | What a reader is promised | Read cost |
|---|---|---|
| Strong | Always the latest committed write, in every region. | About 2x |
| Bounded staleness | At most K versions or T time behind, in order. | About 2x |
| Session (default) | Within one session: read your own writes, in order. Others may lag. | 1x |
| Consistent prefix | Never out of order, but may be behind. | 1x |
| Eventual | Will catch up eventually; order isn’t guaranteed. | 1x |
Strong and Bounded staleness read from two replicas to keep their promise, which is why their reads cost about twice as much. Strong in a multi-region account also adds write latency, because a write waits for every region.
Weakening the level for one client in Python:
client = CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=DefaultAzureCredential(),
consistency_level="Eventual", # weaker than the account's Session default
)
Session is the right answer for most apps, AI chat history included: the user sees their own messages straight away, and you don’t pay for global agreement.
Architect level Indexing mode none, and the vector index
indexingMode: "none" turns indexing off. It suits a container used only as a key-value store with point reads, or a bulk load where you’ll turn indexing back on afterwards. Queries without an index scan everything, so don’t use it for anything you search.
If you search embeddings, the vector path goes in excludedPaths (so the range index skips it) and in vectorIndexes (so the vector index covers it). Those are two different indexes. Excluding the path from the range index is what Microsoft recommends to keep insert RUs and latency down.
Real-world business scenario
Contoso Learning (fictional)
- The problem
- A tutoring app stored lesson chunks with 1,536-number embeddings in Cosmos DB. Ingesting a new course cost so many RUs that imports took hours and student traffic was throttled. The account also used Strong consistency, chosen "to be safe" when the project started.
- What they used
- The team excluded /embedding/* and the long text field from the range index, added a vector index on the embedding, added a composite index for the course list sorted by course and lesson number, and moved the account default to Session.
- Why that choice
- Writes stopped paying to range-index thousands of numbers, and Session still lets each student see their own progress immediately.
- The result
- Course imports finished well inside the throughput budget, the 429 errors went away during class hours, and read costs fell because reads no longer needed two replicas.
When to use it and when not to
✓ Use it when…
- Writes are expensive and items carry big fields you never filter on.
- A query sorts on two or more properties, or filters on one and sorts on another.
- You want each user to see their own changes without paying for Strong consistency.
✕ Think twice when…
- Excluding a path a query filters on. The query falls back to a scan.
- Choosing Strong or Bounded staleness for data where a short lag doesn't matter. You pay double for reads.
- Setting indexingMode to none on a container you query.
↔ Alternatives to consider
- Autoscale throughput when traffic swings through the day.
- Serverless for small or spiky workloads billed per RU.
- Azure Managed Redis in front of Cosmos DB for hot, repeated reads.
Test yourself with exercises
5 original practice questions in the AI-200 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner What is a Request Unit?
Model answer
It's Cosmos DB's single currency for work. Instead of sizing CPU and disks, I pay for RUs per second. A point read of a 1 KB item is about 1 RU, a write is several, and a query depends on how much it has to scan. If I go over my RU/s, I get 429 responses.
Interviewer follows up
What does the SDK do with a 429?
You
It waits for the retry-after time the service sends and retries a few times automatically. If 429s keep coming, I need more throughput, autoscale, or cheaper operations.
Intermediate Your container stores a 1,536-number embedding in every item. Writes are expensive. What do you change?
Model answer
I exclude the embedding path from the range index by adding /embedding/* to excludedPaths, and give it a vector index instead if I search it. Indexing 1,536 numbers per item for range queries I'll never run just burns RUs on every write.
Experienced developer Which consistency level would you pick for a chat app's conversation history, and why?
Model answer
Session, which is the default. The user who just sent a message must see it on the next read, and Session guarantees read-your-own-writes inside that client's session. Other users don't need to see it instantly. Strong would double the read RU cost and add latency for no benefit here.
Interviewer follows up
Can a client ask for a stronger level than the account default?
You
No. A client or request can only relax the level, for example from Session to Eventual. To go stronger you change the account default.
Scenario A query with ORDER BY c.category, c.price fails. What's missing?
Model answer
A composite index on (/category ascending, /price ascending). ORDER BY on more than one property needs a matching composite index in the indexing policy.
Architecture & design How would you lower the RU bill of a read-heavy AI catalogue without hurting correctness?
Model answer
Point reads instead of queries wherever I know the id and partition key, a lean indexing policy that excludes large unfiltered paths, Session consistency rather than Strong, and a Redis cache in front for the hottest items. Then autoscale so I'm not paying for peak RU/s all night.
Quick revision
Key points
- A point read of 1 KB costs about 1 RU; writes and queries cost more.
- The default indexing policy indexes every path (/*) and excludes /_etag.
- Exclude large paths you never filter on (like /embedding/*) to cut write RUs.
- ORDER BY on several properties needs a composite index.
- Five consistency levels: Strong, Bounded staleness, Session (default), Consistent prefix, Eventual.
- Strong and Bounded staleness reads cost about twice the RUs; clients can only weaken the default.
Important terminology
- Request Unit (RU)
- A normalised measure of CPU, memory and IOPS. Throughput is provisioned or billed in RUs per second.
- Indexing policy
- A container setting that decides which property paths are indexed, which are excluded, and which composite, spatial or vector indexes exist.
- Composite index
- An index over two or more properties, needed for ORDER BY on several properties and useful for filters plus sorting.
- Consistency level
- The guarantee about how fresh and how ordered the data you read is, set on the account and weakened per client or request.
- Session consistency
- The default level. Within one session a client reads its own writes, in order.
- Bounded staleness
- Reads may lag writes by at most K versions or T time, and are otherwise in order.
- 429 Too Many Requests
- The response when requests need more RUs per second than the container or database has. The SDK retries after the suggested wait.
Common mistakes
- Leaving a 1,536-number embedding array in the range index.
- Choosing Strong consistency "to be safe" for data that only one user writes and reads.
- Trying to set a stronger consistency on the client than the account default.
Exam tips
- "Reduce RU cost of writes" = exclude paths in the indexing policy.
- "ORDER BY two properties returns an error" = add a composite index.
- "User must always see their own updates, lowest cost" = Session.
- "Reads must never return stale data, any region" = Strong.
Five quick revision questions
-
1.What's the default consistency level?Show
Session.
-
2.Which property paths does the default indexing policy include?Show
All of them (/*), except the system /_etag path.
-
3.What index does ORDER BY on two properties need?Show
A composite index.
-
4.Which two consistency levels make reads cost about twice as many RUs?Show
Strong and Bounded staleness.
-
5.What HTTP status means you ran out of RU/s?Show
429 Too Many Requests.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Vector Search in Cosmos DB for NoSQL
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.