Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 11 of 28
❮Prev Next❯

Cosmos DB: RUs, Indexing Policies and Consistency Levels

Module 2: Data for AI ⏱ 12 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    Azure portal: Request units, indexing policy and consistency Check the RU charge, edit the indexing policy and set consistency.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    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
    1. Every operation costs Request Units. Run a query that filters on the partition key.
    2. Open Query Stats. Under 3 RUs, because only one partition was read.
    3. Filter on name instead and the query fans out to every partition: 5× the cost for one item.
    4. 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.
    5. Writes now cost less than half. Reads on the included paths still use the index.
    6. 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.

    😟 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
    🛠️ Solved with: RUs, indexing and consistency

    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.

    ▶ Explainer video See it in motion 7 steps · 1 min 34 sec

    An animation of a Cosmos DB container with items spread across logical partitions by category. A point read costs about 1 RU, a query without the partition key fans out to every partition and costs more, indexing every path makes writes expensive until /embedding/* is excluded, and a consistency slider runs from Strong to Eventual with Session as the default. RU numbers other than the point read are labelled as examples.
    Read the video script
    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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.
    6. 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.
    7. 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:

    OperationTypical cost
    Point read, 1 KB itemabout 1 RU
    Write (create, replace, upsert), 1 KB item, default indexingabout 5 RUs or more, and more with every indexed property
    Querydepends 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 at description.
    • /embedding/* means everything under embedding, 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.

    LevelWhat a reader is promisedRead cost
    StrongAlways the latest committed write, in every region.About 2x
    Bounded stalenessAt 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 prefixNever out of order, but may be behind.1x
    EventualWill 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

    EdTech

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    Each item in a container includes a property named embedding that contains 1,536 floating-point numbers. The container uses the default indexing policy. Queries never filter on the embedding property by using equality or range filters.

    You need to reduce the RU charge of write operations. What should you do?

    Question 2

    Question 2 of 5

    A query includes ORDER BY c.category ASC, c.price ASC and returns an error that states that the order by query does not have a corresponding composite index. What should you add to the indexing policy?

    Question 3

    Question 3 of 5

    A chat application stores conversation history in Azure Cosmos DB. After a user sends a message, that user must always see the message when the history is read again. Other users do not need to see the message immediately. You must minimize read cost. Which consistency level should you use?

    Question 4

    Question 4 of 5 · Select 2

    An Azure Cosmos DB account uses Session as the default consistency level. Which TWO statements are true?

    Question 5

    Question 5 of 5

    An application frequently receives HTTP status code 429 from Azure Cosmos DB during peak hours. What does this status code indicate?

    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. 1.What's the default consistency level?Show

      Session.

    2. 2.Which property paths does the default indexing policy include?Show

      All of them (/*), except the system /_etag path.

    3. 3.What index does ORDER BY on two properties need?Show

      A composite index.

    4. 4.Which two consistency levels make reads cost about twice as many RUs?Show

      Strong and Bounded staleness.

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.