DP-420 Cheat Sheet
Design and develop database solutions
Evaluate resource models and SDK solutions
Read full chapterCheat sheet
Sharp facts the exam loves — scan these before test day.
- Strong consistency returns the latest committed item version
When every reader must observe the latest committed item version, use strong consistency because it provides linearizability. The guarantee applies to committed data rather than exposing partial writes. It is stronger than the user-specific freshness provided by session consistency.
Trap Using session consistency for a shared inventory figure, which preserves a client's session guarantees rather than freshness across independent sessions.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Strong consistency and has regions in East US and West Europe. A pricing service in East US updates an item named P1. While that
- You are designing four Azure Cosmos DB for NoSQL workloads for a regional bank. Each workload gets its own account with one write region and two read regions, and each account uses the weakest consist
- You have an Azure Cosmos DB for NoSQL account named account1 that has a single write region in East US and read regions in West Europe and Japan East. Stock-reservation services in all three regions r
- Bounded staleness limits lag by versions or elapsed time
Bounded staleness constrains replication lag by K item versions or T time, whichever bound is reached first. If a partition's inter-region lag exceeds the configured bound, writes to that partition are throttled until replication catches up. Choose it when a measurable freshness bound is required without demanding the most recent global commit on every read.
Trap Choosing consistent prefix for a maximum-age requirement, which supplies no configured time or version bound.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with one write region and two read regions. The default consistency level is Bounded staleness, configured with 200,000 versions and 600 se
- You are designing an Azure Cosmos DB for NoSQL account for a price-quote service with a write region in West Europe and read regions in North Europe and UK South. Read regions can lag behind writes, b
- You have an Azure Cosmos DB for NoSQL account named account1 with a write region in East US and a read region in West Europe. The default consistency level is Bounded staleness with 100,000 versions a
- Bounded-staleness minimums depend on the number of regions
Bounded staleness permits minimum settings of 10 versions and 5 seconds for a single-region account. For an account with multiple regions, the minimum settings are 100,000 versions and 300 seconds. Check the account's region count before accepting a proposed staleness configuration.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with a single write region in East US and read regions in Canada Central and Brazil South. The default consistency level is Bounded stalene
- You manage an Azure Cosmos DB for NoSQL account named account1 that currently has one region, West US 3. Its default consistency level is Bounded staleness with the smallest bounds allowed for a singl
- Your company has two Azure Cosmos DB for NoSQL accounts that use Bounded staleness. The dev account has one region, West US. The prod account has a write region in West US and a read region in East US
- Session consistency preserves a user's read-your-writes guarantee
When a user must immediately read their own updates while other sessions may lag, use session consistency. Within the session it provides read-your-writes and write-follows-reads guarantees, with latency and read throughput comparable to eventual consistency. Multiple participating clients must share the relevant session token to preserve the same session boundary.
Trap Choosing bounded staleness solely for a shopping-cart session, which adds quorum-read cost when only session-local guarantees are required.
- Consistent prefix preserves the visibility of transactionally grouped writes
Consistent prefix returns transactionally grouped updates consistently with their commit order: writes within a transaction are visible together. It does not impose a maximum staleness interval. Current documentation distinguishes this transaction grouping from independent single-document writes, which can exhibit eventual consistency.
Trap Selecting eventual consistency for ordered transactional visibility, which provides no ordering guarantee.
- Eventual consistency can return data older than a previous read
Eventual consistency reads from a replica that can be behind other replicas, so a client can receive stale data or even a version older than one it previously read. Use it for workloads that tolerate temporary discrepancies and require no ordering guarantee. Convergence in the absence of new writes is not a promise of immediate freshness.
Trap Using eventual consistency for a client that requires monotonic reads, which allows later reads to regress.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Eventual consistency. A status dashboard polls an item named job42 every second. Occasionally a poll shows an older status than t
- You have a mobile app that uses an Azure Cosmos DB for NoSQL account named account1 with Eventual consistency. Each app instance uses one CosmosClient. Users report that a refreshed order status somet
- Strong and bounded-staleness reads cost twice as many RUs
Strong and bounded-staleness reads consult two replicas, whereas session, consistent-prefix, and eventual reads consult one. For the same read workload, the quorum-read levels consume approximately twice the RUs and provide half the read throughput at a fixed RU budget. Write RU charges for the same write operation are identical across consistency levels.
Trap Weakening consistency to reduce the RU charge of the same insert workload, which changes read cost rather than the write operation's RU charge.
3 questions test this
- You have a read-heavy catalog API that uses an Azure Cosmos DB for NoSQL account with Bounded staleness. The API needs no staleness bound across regions, but each client session must read its own writ
- You have an IoT ingestion service that only inserts items into an Azure Cosmos DB for NoSQL account named account1 and never reads them back. account1 uses Session consistency. A team member proposes
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Session consistency. A container has 20,000 RU/s that are used only for point reads of 1-KB items, and the workload currently rea
- Strong consistency adds inter-region distance to write latency
Strong consistency across multiple regions must coordinate commits across regions, so geographically distant regions increase write latency. The documented 99th-percentile write-latency expression is twice the round-trip time between the farthest regions plus 10 milliseconds. A requirement for globally current reads therefore needs to be reconciled with the write-latency budget.
Trap Choosing strong consistency to improve geographically distributed write latency, which adds synchronous inter-region coordination.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Strong consistency, with a write region in East US and read regions in West Europe and Australia East. Users only need to read th
- You are designing an Azure Cosmos DB for NoSQL account for a payment ledger. Every read in every region must return the latest committed balance. The 99th-percentile write-latency budget is 50 ms. The
- Strong consistency cannot be used with multiple write regions
Strong consistency is unsupported on an Azure Cosmos DB account configured with multiple write regions. Treat this as a compatibility constraint when choosing a consistency level. A design cannot obtain both configurations simply by changing a client's consistency option.
Trap Selecting strong consistency for an existing multi-write account, which combines incompatible account settings.
- Dynamic quorum preserves strong consistency by excluding unhealthy regions
In a strongly consistent account with at least three regions, dynamic quorum can remove slow or unresponsive regions from the quorum to improve write availability and replication latency. Removed regions cannot serve reads until they become consistent with the other regions and rejoin the quorum.
- Bounded staleness is an anti-pattern for local reads and writes in a multi-write account
When each application instance reads and writes in its local writable region and needs no cross-region staleness bound, avoid bounded staleness. Its inter-region replication-lag dependency adds a constraint that this local access pattern does not require. Select a weaker level that meets the application's actual read guarantees instead.
Trap Choosing bounded staleness solely to obtain local read-your-writes behavior, which session consistency can provide without imposing the inter-region lag bound.
- PBS estimates observed freshness rather than configuring a consistency guarantee
Probabilistically Bounded Staleness (PBS) estimates the probability that a workload using weaker consistency receives strongly consistent reads in practice. A favorable PBS observation describes that workload's observed behavior; it does not replace the account's configured consistency guarantee with bounded staleness or strong consistency.
- The account's default consistency applies to its databases and containers
Azure Cosmos DB configures the default consistency level at account scope, and reads and queries in its databases and containers inherit that default. Read consistency applies to an individual read operation within a logical partition; it is not a cross-container transaction guarantee. Recreate SDK client instances after changing the account default so they use the new setting.
Trap Assigning separate persisted default consistency levels to two containers in one account, which mistakes an account default for a container policy.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. An administrator changes its default consistency level from Session to Bounded staleness in the Azure portal. A long-running .NET worker s
- You have an Azure Cosmos DB for NoSQL account named account1 with a database named db1. Reads from the orders container must always return the latest committed version, while reads from the logs conta
- The traditional ConsistencyLevel override only weakens reads
The SDK's traditional ConsistencyLevel setting can relax read consistency at client or request scope, and a request setting overrides the client default. It cannot strengthen the account default through that mechanism. Relaxing a read also leaves the account's write-replication behavior unchanged.
Trap Setting ItemRequestOptions.ConsistencyLevel to Strong on an eventual account, which attempts to strengthen consistency through a relax-only override.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 whose default consistency level is Strong. A .NET application creates its CosmosClient with CosmosClientOptions.ConsistencyLevel set to Eve
- You have an Azure Cosmos DB for NoSQL account named account1 whose default consistency level is Eventual. A .NET application in Gateway mode reads payment items, and a developer adds the following cod
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Strong consistency and has regions in East US and West US. To reduce latency, a developer sets CosmosClientOptions.ConsistencyLev
- A session token is a partition-bound minimum-version barrier
A session token identifies the minimum session progress a read must honor for the relevant partition. It does not request a historical snapshot: a replica with newer committed data can return that newer data. Preserve tokens as opaque values rather than parsing or editing their contents.
Trap Reusing an older session token to retrieve an earlier item version, which confuses a minimum-version barrier with historical version selection.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Session consistency. Two microservices share a user's session by passing session tokens through a message queue. To shorten messa
- You have an Azure Cosmos DB for NoSQL account named account1 that uses Session consistency. An audit tool saved the session token returned when version 1 of an item named inv-7 was written. Versions 2
- Session tokens must follow the user across independent client instances
When a write and subsequent read can reach different application instances, pass the write's session token to the instance performing the read. Each CosmosClient maintains its own token cache, so another instance does not automatically know the user's most recent write. Without a relevant token, a session read can behave like an eventual read for that partition.
Trap Relying on the session-token cache in a different web server's CosmosClient, which is not shared across processes.
2 questions test this
- You have an ASP.NET Core API that writes cart items by using the Azure Cosmos DB for NoSQL .NET SDK v3 and Session consistency. A separate instance of the API, which has its own CosmosClient, reads th
- You have a web application that runs on four virtual machines behind Azure Load Balancer, which distributes requests round-robin without session affinity. Each virtual machine has its own CosmosClient
- ReadConsistencyStrategy is a separate direct-mode read-control mechanism
ReadConsistencyStrategy is a preview feature documented for Java SDK 4.69 or later and .NET SDK 3.46 or later. Unlike the traditional ConsistencyLevel override, it permits supported read strategies stronger than the account default. It is supported only in Direct mode, so it cannot be substituted into a Gateway-mode design.
Trap Applying ReadConsistencyStrategy to a Gateway client, which does not support this preview mechanism.
- LATEST_COMMITTED guarantees local committed freshness rather than a global lag bound
The LATEST_COMMITTED read strategy (part of the preview ReadConsistencyStrategy feature) performs quorum reads and barrier requests against replicas in the local region to obtain the latest locally committed data. Cross-region replication remains asynchronous, so the strategy does not impose bounded staleness across regions. Use its local freshness guarantee only when a global time-or-version bound is unnecessary.
Trap Replacing bounded staleness with LATEST_COMMITTED while retaining a maximum inter-region lag requirement, which the local-region strategy does not guarantee.
2 questions test this
- Your Java application uses Azure Cosmos DB Java SDK 4.70 in Direct mode with an account that has one write region, two read regions, and Session as its default consistency level. A reporting service i
- You have a Java application that uses Azure Cosmos DB Java SDK 4.70 in Direct mode against an account with a write region in East US and a read region in West US. The default consistency level is Sess
- GLOBAL_STRONG requests globally linearizable reads through ReadConsistencyStrategy
The preview ReadConsistencyStrategy mechanism includes GLOBAL_STRONG, documented as providing linearizable reads across all regions. Choose that strategy when a read must be globally linearizable rather than just locally fresh.
Trap Choosing LATEST_COMMITTED for a globally current read requirement, which establishes freshness within the local region rather than global linearizability.
- Session is the default consistency level for a new account
Azure Cosmos DB applies session consistency to a new account when another consistency level is not selected.
- ReadConsistencyStrategy takes precedence over ConsistencyLevel on the same request
In the direct-mode-only ReadConsistencyStrategy preview, ReadConsistencyStrategy determines the read behavior when both it and ConsistencyLevel are specified on the same request.
- RUs measure operation work while RU/s measures available throughput
A Request Unit normalizes CPU, I/O, and memory consumed by an Azure Cosmos DB operation. Provisioned RU/s describes how much of that work is available per second, not the number of requests the application may send. Operations with different complexity therefore consume different portions of the same throughput allocation.
Trap Sizing RU/s as one unit per application request, which ignores differences between operation charges.
- Response request-charge metadata reports the work an operation consumed
Use the x-ms-request-charge response header, or RequestCharge on a .NET SDK response, to measure RU consumption. For a paged query, add the charge from every page to obtain the complete query charge. The charge measures work already performed rather than the container's provisioned RU/s.
Trap Treating the first query page's RequestCharge as the complete query cost, which omits work performed by subsequent page requests.
- Larger items require more RUs to read and write
Item size is a primary RU charge driver: reading or writing a larger JSON item generally consumes more RUs. With default indexing, additional indexed properties also increase write work. A design that repeatedly replaces a large item should account for the whole written item's size, not only the changed property's size.
Trap Estimating a full replace from the size of its one changed field, which ignores the rest of the rewritten document.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container in which each customer item is 300 KB because it embeds the customer's documents. A dashboard performs thousands of point reads per minute by id and par
- You have an Azure Cosmos DB for NoSQL container that stores 100-KB product items. An application updates a 50-byte stockLevel property on each item by reading the item, changing the property, and call
- Equivalent operations on the same data have deterministic RU charges
Azure Cosmos DB makes RU charges deterministic for a given operation over a given dataset. Repeating the same query against unchanged data has the same total RU cost even if the service divides results into different page sizes. Query complexity, source data, result size, and script work must all be represented in a workload estimate.
Trap Assuming a different number of response pages proves that unchanged query logic became cheaper, which confuses paging with total operation work.
2 questions test this
- You are planning the throughput for a new Azure Cosmos DB for NoSQL workload. The workload includes point reads, inserts of 5-KB items, two queries with different filters, and a stored procedure. The
- You have an Azure Cosmos DB for NoSQL container. A reporting query is run once with MaxItemCount set to 100 and returns 10 pages. It's run again against the same unchanged data with MaxItemCount set t
- HTTP 429 retries should respect the service's retry-after interval
HTTP 429 indicates request-rate throttling, represented by HttpStatusCode.TooManyRequests in .NET. Azure Cosmos DB SDKs retry these responses automatically according to their configured limits and honor x-ms-retry-after-ms. If retries are exhausted, the application receives the error and should use the retry-after guidance or an appropriate backoff policy.
Trap Immediately resubmitting every throttled request in a tight loop, which disregards the service's indicated recovery interval.
2 questions test this
- You have a .NET service that uses the Azure Cosmos DB .NET SDK v3 with its default client options. During a traffic spike, the container exceeds its provisioned RU/s and the service returns HTTP 429 r
- You have a .NET batch job that writes to an Azure Cosmos DB for NoSQL container by using the .NET SDK v3 with its default retry settings. During peaks, some writes still fail with a CosmosException wh
- Manual throughput suits sustained predictable demand
When a workload has sustained, predictable traffic, manual provisioned throughput lets you reserve a fixed RU/s allocation. Billing is based on the provisioned capacity per hour even if the application consumes fewer RUs. Throughput changes use increments of 100 RU/s, subject to the resource's current minimum.
Trap Choosing manual throughput for a nearly idle application solely to pay for consumed requests, which is the serverless billing model.
- Autoscale varies throughput between one tenth of Tmax and Tmax
When a provisioned workload has variable or unpredictable demand, configure autoscale with the required maximum throughput Tmax. The service scales between 0.1 times Tmax and Tmax without application interruption. The entry maximum is 1,000 RU/s, and configured maximums use increments of 1,000 RU/s.
Trap Sizing autoscale as if idle capacity falls to zero, which ignores its one-tenth minimum.
2 questions test this
- You are developing a new application on an Azure Cosmos DB for NoSQL container, and its throughput requirement is still unknown. You plan to use autoscale throughput and monitor usage before you adjus
- You have an Azure Cosmos DB for NoSQL container named events that uses autoscale throughput with a maximum throughput (Tmax) of 20,000 RU/s. The container stores 50 GB of data. Overnight, the applicat
- Autoscale billing follows the highest scaled throughput within the hour
Autoscale is still provisioned capacity, not per-request serverless billing. Under uniform autoscale, an hour is billed according to the highest throughput reached in that hour, with a minimum of one tenth of Tmax. A short peak can therefore determine that hour's throughput charge.
Trap Using the hourly average consumed RU/s to predict an autoscale invoice, which ignores the hourly peak billing rule.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container in a single-region account that uses autoscale with a maximum throughput of 10,000 RU/s. Dynamic scaling isn't enabled. During one hour, the system stay
- You have an Azure Cosmos DB for NoSQL container that uses autoscale with a maximum throughput of 20,000 RU/s. The finance team wants to see, for each hour of last month, the RU/s that the container wa
- Dynamic autoscale scales physical partitions and regions independently
Dynamic autoscale allows each physical partition in each region to scale according to its own usage instead of scaling everything to match the busiest partition and region. This avoids unnecessary scale-ups for nonuniform workloads. Billing aggregates the highest scaled throughput for each partition and region during the hour.
Trap Treating classic autoscale's hottest-partition scaling as independent partition scaling, which overlooks the dynamic-scaling enhancement.
2 questions test this
- Your Azure Cosmos DB for NoSQL account was created in 2025 and has one write region and one read region. A container uses autoscale with a maximum of 10,000 RU/s across four physical partitions, and t
- You have an Azure Cosmos DB for NoSQL container with autoscale Tmax of 2,000 RU/s, two physical partitions, and a write region and a read region, so each partition can scale up to 1,000 RU/s in each r
- Dynamic scaling is an account feature that applies only to autoscale resources
Dynamic scaling is enabled by default on accounts created after September 25, 2024, and can be enabled on older accounts. The account-level setting applies to its autoscale containers and shared-throughput databases. It does not convert manual resources to autoscale and does not apply to serverless accounts.
Trap Enabling Dynamic Scaling to make a manually provisioned container autoscale, which leaves its capacity mode unchanged.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that was created in 2023. Its containers use autoscale, but monitoring shows that every partition scales to match the hottest partition. Th
- You have an Azure Cosmos DB for NoSQL account created in 2023. It contains container c1 with autoscale throughput, database db2 with autoscale shared throughput used by three containers, and container
- Serverless charges for consumed RUs without a reserved throughput allocation
When traffic is intermittent with low average utilization, evaluate serverless because it bills for consumed RUs rather than a reserved RU/s allocation. You do not provision throughput when creating resources in a serverless account. The database operations remain available, but the capacity and billing behavior differ from provisioned throughput.
Trap Provisioning shared database RU/s in a serverless account, which has no reserved-throughput resource to configure.
2 questions test this
- You have an Azure Cosmos DB for NoSQL serverless account named account1. A deployment script that uses the .NET SDK calls CreateContainerAsync("orders", "/customerId", 400) to create a container for a
- You are designing a back end for an internal approval API that uses Azure Cosmos DB for NoSQL. The API runs in one Azure region on Azure Functions, is used for a few minutes several times a day, and h
- A requirement for multiple Azure regions rules out serverless
Azure Cosmos DB serverless accounts run in a single Azure region and cannot provide provisioned-throughput geo-distribution. If an application requires more than one region, choose a provisioned-throughput account. Low average traffic does not remove that compatibility constraint.
Trap Selecting serverless for a low-traffic application that must use two regions, which violates its single-region restriction.
2 questions test this
- You have an Azure Cosmos DB for NoSQL serverless account named account1 in West Europe that stores order data for a regional retail application. A new disaster-recovery policy requires a replica of th
- You are designing an Azure Cosmos DB for NoSQL account for a low-traffic booking application that averages 50 RU/s with occasional bursts. A compliance rule requires that the data be replicated to two
- The throughput migrate command changes an existing container's provisioned-throughput type
To change an existing NoSQL container from manual throughput to autoscale, use az cosmosdb sql container throughput migrate with --throughput-type autoscale and the resource identifiers. Use --throughput-type manual for the reverse migration. Throughput update changes an allocation within the current mode rather than performing this mode migration.
Trap Running throughput update to switch a manual container to autoscale, which changes throughput values rather than migrating the mode.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named legacy that uses manual throughput. A developer plans to switch legacy to autoscale from a .NET deployment routine by calling ReplaceThroughputAsy
- You have an Azure Cosmos DB for NoSQL container named container2 in database db1 that uses 4,000 RU/s of manual throughput. You need to change container2 to autoscale by using the Azure CLI. You plan
- You have an Azure Cosmos DB for NoSQL container named container3 that uses manual throughput. You need to switch container3 to autoscale and then set its maximum throughput to 10,000 RU/s by using two
- Creating an autoscale resource requires autoscale throughput properties
To create an autoscale database or container in .NET, supply throughputProperties built with ThroughputProperties.CreateAutoscaleThroughput(Tmax). The value specifies the autoscale maximum, whereas an ordinary integer throughput argument provisions manual RU/s. SDK support for creating autoscale resources does not imply support for migrating an existing manual resource to autoscale.
Trap Passing an integer throughput argument and expecting it to mean Tmax, which selects manual throughput instead of an autoscale definition.
2 questions test this
- You are writing a .NET deployment routine that uses the Azure Cosmos DB .NET SDK v3 to create a container that must use autoscale throughput with a maximum of 4,000 RU/s. The routine calls the followi
- You have an Azure Cosmos DB for NoSQL container named legacy that uses manual throughput. A developer plans to switch legacy to autoscale from a .NET deployment routine by calling ReplaceThroughputAsy
- Provisioned throughput and serverless have different latency commitments
When capacity selection requires SLA-backed point-operation latency, evaluate provisioned throughput rather than choosing solely by average traffic or billing. Microsoft's capacity-mode comparison lists less than 10-ms point-read and write latency for provisioned throughput, versus serverless SLO targets of less than 10 ms for point reads and less than 30 ms for writes. SLA conditions still apply; multi-region strong consistency has a separate write-latency expression. A serverless SLO is not the same commitment as the provisioned-throughput SLA.
2 questions test this
- Your team plans to move a single-region Azure Cosmos DB for NoSQL workload from provisioned throughput to a serverless account to cut costs. The workload is mostly point reads and point writes. An int
- You are designing an Azure Cosmos DB for NoSQL account for a payment authorization service in one Azure region. Traffic is low and intermittent, but the contract requires that point writes complete in
- Serverless maximum throughput grows with storage-driven physical partition count
A serverless container has a documented maximum capacity of 5,000 RU/s per physical partition. When its data outgrows one physical partition, its maximum container throughput increases with the number of partitions. These values are capacity ceilings rather than guaranteed throughput, so consumed-RU billing does not provide unlimited instantaneous burst capacity.
Trap Applying the provisioned-throughput 10,000-RU/s physical-partition ceiling to serverless sizing, because serverless has a separate per-partition capacity limit.
When a container needs predictable reserved throughput, provision throughput on that container. Database-level throughput is shared by participating containers and guarantees no fixed share to any one of them. Current guidance recommends dedicated container throughput for most workloads, especially when containers have different growth or demand patterns.
Trap Using database-shared throughput to guarantee each tenant container an equal reserved share, which the shared pool does not enforce.
2 questions test this
- You are reviewing four planned Azure Cosmos DB for NoSQL workloads. Current guidance recommends container-level throughput for most workloads, and you will approve database-level shared throughput onl
- You have an Azure Cosmos DB for NoSQL database named tenants that has 4,000 RU/s of shared manual throughput and 10 containers, one for each enterprise customer. A new contract requires that every cus
- A container with dedicated throughput does not draw from its database's shared allocation
A database can contain both shared-throughput containers and containers with dedicated throughput. The dedicated container receives its own provisioned allocation, while the database allocation is shared only among the participating shared containers. Include both allocations when estimating the resource's provisioned capacity.
Trap Adding a dedicated container's allocation to the shared pool available to other containers, which double-counts isolated capacity.
2 questions test this
- You have an Azure Cosmos DB for NoSQL database named sales that has 4,000 RU/s of shared manual throughput used by five containers. A sixth container named orders was created in sales with 2,000 RU/s
- Six containers in the crm database of an Azure Cosmos DB for NoSQL account draw on the database's 5,000 RU/s of shared manual throughput. The exports container in crm was provisioned with its own 3,00
- Shared and dedicated throughput cannot be interchanged on the same existing container
A container's choice between database-shared and dedicated throughput is made at creation. Moving between these granularities requires copying data into a container created with the desired setting. This differs from changing manual provisioned throughput to autoscale on an existing resource.
Trap Using a manual-to-autoscale migration to turn a shared container into a dedicated one, which changes the scaling mode rather than the throughput granularity.
2 questions test this
- You have an Azure Cosmos DB for NoSQL database named db1 with 4,000 RU/s of shared throughput. A container named reports in db1 uses the shared throughput and now needs its own dedicated 2,000 RU/s. T
- You are designing an Azure Cosmos DB for NoSQL database named Z that has shared throughput for several small containers. You plan to add a container named B, and its owner expects B to need guaranteed
A shared-throughput database normally allows up to 25 containers to participate in its allocation. Additional containers must be created with dedicated throughput, subject to documented legacy exemptions. Do not assume that adding containers always leaves the database's existing shared-throughput arrangement available.
2 questions test this
- A database named media in an Azure Cosmos DB for NoSQL account uses shared manual throughput, and all 25 of its containers draw on that allocation. The account isn't covered by the legacy exemption th
- Your team is designing a new Azure Cosmos DB for NoSQL database for a partner portal. The design calls for 32 small partner containers, and the team wants as many of them as possible to draw on one sh
- A manual container's minimum throughput includes storage and historical provisioning
For a manual-throughput container, estimate the minimum RU/s as the maximum of 400 RU/s, current storage in GB multiplied by 1 RU/s, and the highest RU/s ever provisioned divided by 100. A temporary large scale-up can therefore raise the minimum you can later select. Read the resource's current minimum before planning a scale-down.
Trap Returning a previously large container to 400 RU/s solely because current traffic is low, which ignores storage and historical-throughput minimums.
2 questions test this
- You manage four Azure Cosmos DB for NoSQL containers that use dedicated manual throughput. Container A stores 350 GB, and its highest throughput ever was 30,000 RU/s. B stores 60 GB and once had 70,00
- A cost script estimates the lowest manual throughput allowed for each Azure Cosmos DB for NoSQL container by using MAX(400, storage in GB x 1, current RU/s / 100). For a container named claims that st
- Autoscale's minimum configurable Tmax includes storage and its historical maximum
For an autoscale container, the minimum configurable Tmax is the maximum of 1,000 RU/s, current storage in GB multiplied by 10 RU/s, and the highest configured maximum divided by 10, rounded up to the next 1,000 RU/s. This is a lower bound on the selected maximum, not the live one-tenth scaling floor. Storage growth can require Tmax to increase.
Trap Applying the manual container's historical-maximum divisor to autoscale Tmax, which uses a different minimum formula.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named archive that uses autoscale throughput. Its maximum throughput was once set to 100,000 RU/s, and it now stores 10 GB of data. A script calculates
- You have an Azure Cosmos DB for NoSQL container named logs that uses autoscale throughput. The highest maximum throughput ever configured was 20,000 RU/s, and the container now stores 300 GB of data.
- Large throughput increases can complete asynchronously
A provisioned-throughput increase can require background resource provisioning rather than taking effect immediately. While a scaling operation is in progress, another modification can return HTTP 423. In .NET, inspect ThroughputResponse.IsReplacePending to distinguish a pending replacement from an already completed allocation.
Trap Starting a large ingestion immediately after requesting a large RU/s increase, which assumes background scaling has already finished.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named ingest that has 10,000 RU/s. Next Monday, a one-time data load will require 500,000 RU/s. You plan to scale the container by using the .NET SDK fr
- You have an Azure Cosmos DB for NoSQL container named ingest. A script raised its throughput from 10,000 RU/s to 400,000 RU/s. Minutes later, a second script calls ReplaceThroughputAsync to change the
- Throughput redistribution reallocates capacity among physical partitions
The preview redistribution feature supports manual and autoscale provisioned resources and can move RU/s from quieter physical partitions to busier ones without necessarily raising total throughput. It does not apply to serverless accounts. Custom partition allocations switch the throughput policy from Equal to Custom, which blocks normal container- or database-level throughput changes until Equal distribution is restored.
Trap Changing overall container throughput while a Custom per-partition policy is active, which is blocked to preserve those custom allocations.
2 questions test this
- You manage four Azure Cosmos DB for NoSQL accounts. Each has a container with a hot physical partition and other partitions with unused throughput. You plan to use the throughput redistribution previe
- You have an Azure Cosmos DB for NoSQL container named orders that has 20,000 RU/s. Last week, you used the redistribution preview to give one hot physical partition more RU/s. Today, a deployment pipe
For a shared database, the usual storage and historical-provisioning minimums also include a container-count term. For manual throughput, that term is 400 + MAX(container count - 25, 0) times 100 RU/s; for autoscale's minimum Tmax, it is 1,000 + MAX(container count - 25, 0) times 1,000 RU/s. The term matters for legacy databases permitted to exceed the normal shared-container count limit, so a container-only minimum formula is insufficient there.
Trap Applying only the dedicated-container minimum formula to a legacy shared database with many containers, which omits its container-count term.
2 questions test this
- You have a legacy Azure Cosmos DB for NoSQL shared-throughput database named portal that is exempt from the 25-container limit. portal uses manual throughput, has 34 containers, stores 12 GB, and its
- You have a legacy Azure Cosmos DB for NoSQL shared-throughput database that is exempt from the 25-container limit. The database uses manual throughput, has 30 containers, stores 15 GB of data, and has
- The standard per-resource throughput quota can be raised through support
The documented default maximum provisioned throughput is 1,000,000 RU/s per dedicated container or shared-throughput database. A support request can increase that resource quota. This is distinct from a full logical partition's architectural limit, which is not removed by increasing the resource-wide quota.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container that has 300,000 RU/s. One logical partition key, a celebrity's profile, receives about 15,000 RU/s at peak and is throttled. A team proposes a support
- You are preparing an Azure Cosmos DB for NoSQL container named ticketing for a concert sale. Load tests show that the container needs 1,400,000 RU/s of dedicated provisioned throughput for two hours,
- Per-partition throughput has separate retrieval and redistribution commands
Use az cosmosdb sql container retrieve-partition-throughput to inspect current physical-partition allocations, selecting --physical-partition-ids or --all-partitions as needed. Use redistribute-partition-throughput with --target-partition-info to request the desired per-partition allocations. These commands require the cosmosdb-preview extension; their documented CLI path has no shared-database equivalent, for which the PowerShell database cmdlets are available.
Trap Using throughput migrate to move RU/s between physical partitions, which changes the resource's provisioned-throughput type rather than its per-partition allocation.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1 with dedicated throughput and the cosmosdb-preview Azure CLI extension installed. Before you redistribute throughput, you want to see t
- You have an Azure Cosmos DB for NoSQL database named shared1 that has shared throughput, with a hot physical partition. You need to read the current RU/s of each physical partition of shared1 before y
- Equal allocation can throttle a hot physical partition below the resource's total RU budget
The default Equal throughput policy divides provisioned throughput evenly among a resource's physical partitions. A busy partition can exhaust its assigned share and return throttling responses while other partitions still have unused capacity. Evaluate the allocation available to the busy partition rather than treating all resource RU/s as one immediately usable pool.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named sessions with 8,000 RU/s of manual throughput spread across four physical partitions. Its throughput has never been redistributed. One physical pa
- You have an Azure Cosmos DB for NoSQL container that receives 429 responses, although its total RU consumption is about 40 percent of the provisioned throughput. You suspect that one physical partitio
- ReadThroughputAsync retrieves throughput settings and the current minimum
Use ReadThroughputAsync on the database or container whose throughput is being inspected. In .NET, the overload taking RequestOptions returns a ThroughputResponse with Resource and MinThroughput; the parameterless convenience call returns only a nullable throughput value. Use the richer response when a planned scale-down must respect the resource's current minimum.
Trap Reading ContainerProperties to obtain MinThroughput, which belongs to the throughput response rather than the container definition.
2 questions test this
- An inventory script for an Azure Cosmos DB for NoSQL account that uses provisioned throughput runs the following code for every container: int? throughput = await container.ReadThroughputAsync(); For
- You are writing a .NET job for an Azure Cosmos DB for NoSQL container named telemetry that uses manual throughput. Each night, the job lowers the throughput to the lowest value that the container allo
- ReplaceThroughputAsync changes an existing resource's throughput allocation
Use ReplaceThroughputAsync on a database or container to change its provisioned throughput allocation. For an existing autoscale resource, pass ThroughputProperties.CreateAutoscaleThroughput with the new maximum. This updates throughput settings rather than replacing container properties or migrating between manual and autoscale modes.
Trap Using ReplaceContainerAsync to scale RU/s, which changes the container definition rather than its separately managed throughput allocation.
2 questions test this
- You have an Azure Cosmos DB for NoSQL database named products that has 1,000 RU/s of shared manual throughput. Eight containers in products use the shared throughput and have no dedicated throughput.
- You have an Azure Cosmos DB for NoSQL container named orders that uses autoscale throughput with a maximum of 4,000 RU/s. Before a sales event, a .NET maintenance tool must raise the autoscale maximum
- Redistribution changes total throughput when the target allocations change its sum
A throughput redistribution request in the redistribution preview is not necessarily a capacity-neutral transfer. If the requested physical-partition allocations sum to a different total, the operation updates the resource's total throughput accordingly. Include a larger requested total in capacity and cost planning.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container that has 12,000 RU/s of manual throughput across three physical partitions, with 4,000 RU/s each. Partition 0 is hot. An engineer runs az cosmosdb sql c
- You have an Azure Cosmos DB for NoSQL container named baskets with 12,000 RU/s of manual throughput across three physical partitions, P0, P1, and P2, each with 4,000 RU/s. P0 is hot and needs 6,000 RU
- A redistribution target above 10,000 RU/s triggers a physical-partition split
The redistribution preview accepts a target of up to 20,000 RU/s for a physical partition, but a target above 10,000 RU/s triggers splitting. The original partition first receives up to 10,000 RU/s, and the requested throughput is then divided evenly among the resulting partitions. The larger request does not authorize one physical partition to remain above its 10,000-RU/s ceiling.
2 questions test this
- You manage an Azure Cosmos DB for NoSQL container named clickstream with physical partitions that each have 4,000 RU/s. Partition 0 is hot, and its traffic is spread across many logical partition keys
- You have an Azure Cosmos DB for NoSQL container named leaderboard. One physical partition is hot, and diagnostic logs show that a single logical partition key, the current season's global ranking, con
- Priority-based execution preferentially throttles low-priority work during contention
When interactive requests and less urgent background work compete for a container's RU/s, enable priority-based execution on the account and assign High or Low priority through SDK request options. In .NET, set ItemRequestOptions.PriorityLevel to PriorityLevel.High or PriorityLevel.Low. The service attempts to throttle low-priority requests first when demand exceeds configured throughput, but this preference is best effort rather than an SLA or a reservation of additional capacity.
Trap Using AllowBulkExecution to protect interactive requests from background ingestion, because bulk grouping optimizes aggregate throughput without assigning service-side request priority.
- Throughput buckets cap a workload's percentage without reserving that share
The throughput-bucket preview limits an assigned workload to a configured maximum percentage of a dedicated container's throughput, while the underlying capacity remains shared. Assign ordinary requests with ItemRequestOptions.ThroughputBucket or set a client-wide bucket with WithThroughputBucket; bulk-enabled clients require client-level assignment rather than a bucket on each operation. Buckets govern workload consumption rather than redistributing RU/s among physical partitions. Shared-throughput database containers and serverless accounts do not support this feature.
Trap Using physical-partition throughput redistribution to impose an application-specific RU ceiling, because redistribution assigns capacity by storage partition rather than by request workload.
- New NoSQL containers automatically index their item properties by default
A newly created NoSQL container has an automatic indexing policy that indexes every item's properties and uses range indexes for strings and numbers. This supplies query support without separate index creation for each property. The indexing policy belongs to the container rather than to the account or client.
Trap Creating a separate account-wide index policy for all containers, which mistakes a per-container setting for an account property.
2 questions test this
- You have an Azure Cosmos DB for NoSQL database named db1 that contains a container named orders, which is queried on many properties, and a container named audit, which is only written to and read by
- You are creating a container named catalog in an Azure Cosmos DB for NoSQL database. Queries will filter on brand, price, and color, and the product team will add new properties to items over time. Qu
- Consistent indexing updates synchronously while None disables indexing
A container's Consistent indexing mode updates its index synchronously with item writes and deletes. None disables indexing and is appropriate for a pure key-value workload that does not need secondary-index queries. Indexing mode is a container policy, not a choice among the five read-consistency levels.
Trap Selecting None to request eventual read consistency, which disables indexing instead of selecting a read-consistency level.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1 whose indexing mode is Consistent. The account uses Session consistency. To reduce RU charges, a developer proposes setting container1'
- You plan to create an Azure Cosmos DB for NoSQL container named sessions that will be used purely as a key-value store. The application performs only point reads and upserts by id and partition key an
- A unique-key policy enforces uniqueness within a logical partition
When a tenant's items must not repeat a business value, define a unique-key policy on that value and partition by the tenant identifier. The policy prevents duplicate values within each logical partition, not across all partition-key values. A create or update that violates the constraint is rejected.
Trap Using a unique email policy to enforce account-wide uniqueness across unrelated partition keys, which exceeds the policy's logical-partition scope.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named accounts that uses /tenantId as the partition key and a unique key on /email. A new requirement states that an email address must be unique across
- You are designing a multitenant application that stores user profiles in an Azure Cosmos DB for NoSQL container named users. Every query filters on the tenant ID and must be served from a single logic
- Paths grouped in one unique key constrain their combined value
A composite unique key groups multiple property paths into one uniqueness constraint. The combined tuple must be unique within a logical partition; each component need not be individually unique. Use separate unique-key constraints only when each value must be independently unique.
Trap Defining separate first-name and last-name constraints to prevent duplicate full names, which unnecessarily requires each name component to be unique.
2 questions test this
- You plan to create a container named contacts in an Azure Cosmos DB for NoSQL account. The partition key is /companyId. Within a company, two contacts can share a first name or a last name, but the sa
- You have an Azure Cosmos DB for NoSQL container named contacts that uses /companyId as the partition key. The requirement is that no company stores two contacts with the same full name. A teammate pro
- Unique-key policies must be defined when the container is created
An existing container's unique-key policy cannot be added or changed in place. To introduce a different policy, create a new container with the required constraints and copy the data. Check for conflicting existing values before performing the copy.
Trap Replacing an existing container's properties to add a new unique-key constraint, which is not a mutable container policy.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named customers that has 2 TB of data and no unique key policy. A new requirement states that customer numbers must be unique within each partition key
- You have an Azure Cosmos DB for NoSQL container named orders1 that has no unique key policy. You created a container named orders2 with a unique key on /orderNumber and the same partition key. You ver
- Missing unique-key paths participate as null and path names are case-sensitive
Unique keys are not sparse: a missing constrained path contributes a null value to the uniqueness check. Property paths and JSON string values are case-sensitive, so a mis-cased path can unexpectedly constrain null rather than the intended field. For a single-path constraint, multiple missing values in the same logical partition violate uniqueness.
Trap Using a mis-cased path such as /email for items containing Email, which constrains missing null values instead of the intended property.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named members that has a unique key on /email. Items store the address in a property named Email. The first insert in a logical partition succeeds, but
- You have an Azure Cosmos DB for NoSQL container named customers with /storeId as the partition key and a unique key policy on /phone. In store S7, an existing customer item has no phone property. An a
- A standard unique-key policy allows up to ten constraints
A standard unique-key policy supports at most 10 unique-key constraints or combinations. Grouping several property paths in one composite constraint consumes one constraint entry. Count policy entries rather than counting every participating property as a separate constraint.
3 questions test this
- You plan to create an Azure Cosmos DB for NoSQL container that has the following unique key policy: - one composite key on /firstName, /lastName, and /email - one composite key on /badgeId and /siteId
- You plan to create an Azure Cosmos DB for NoSQL container whose unique key policy already includes two composite keys that each group five property paths. You want to add as many additional single-pat
- You are designing an Azure Cosmos DB for NoSQL container for a government registry. Twelve different identifier properties must each be independently unique within a logical partition, so they can't b
- A standard unique-key policy has a total budget of sixteen path values
The unique-key documentation gives a maximum of 16 path values in a standard unique-key policy. A composite constraint consumes one path value for each participating property, so its paths still count individually toward that budget. Check the total path count separately from the number of constraints.
2 questions test this
- You plan to create an Azure Cosmos DB for NoSQL container named people for an HR application. To prevent duplicate records, the proposed unique key policy defines five composite unique keys. Each comp
- You plan to create an Azure Cosmos DB for NoSQL container whose unique key policy already includes two composite keys that each group five property paths. You want to add as many additional single-pat
- Unique-key enforcement slightly increases item mutation RU charges
A container with a unique-key policy has slightly higher RU charges for creating, updating, and deleting items. Include that enforcement overhead when estimating mutation costs. The constraint is not a cost-free metadata declaration.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named catalog that receives 50,000 point reads and 200 item updates per hour. You plan to recreate catalog with a unique key on /sku and copy the data.
- You are estimating the throughput for an Azure Cosmos DB for NoSQL container named registrations. Load testing measured the RU charge of creates, updates, and deletes on a test container that had no u
- A database manages containers while a container is the scaling unit
An Azure Cosmos DB account contains databases, and a database manages one or more containers of items. The container is the unit of horizontal storage and throughput scalability. Multiple item shapes can coexist because containers are schema-agnostic.
2 questions test this
- You plan to store orders and customer profiles for an online store in an Azure Cosmos DB for NoSQL account. Orders and profiles have different properties, and every item includes a type property that
- You are designing an Azure Cosmos DB for NoSQL solution for an IoT telemetry platform. The telemetry data will grow from 50 GB to 40 TB, and the ingestion rate is expected to increase tenfold. You mus
- Create-if-not-exists methods support repeatable resource initialization
Use CreateDatabaseIfNotExistsAsync on CosmosClient and CreateContainerIfNotExistsAsync on Database for repeatable initialization. Their create counterparts attempt creation and can fail when the named resource already exists. Perform these metadata operations during setup rather than on every item request.
Trap Calling resource creation during every point read to obtain a container reference, which introduces unnecessary metadata work on the data path.
2 questions test this
- You have a .NET application that uses the Azure Cosmos DB .NET SDK v3. At startup it calls CreateDatabaseAsync to create a database named db1. The first deployment succeeds, but every later restart fa
- You have an ASP.NET Core API that uses the Azure Cosmos DB .NET SDK v3. For every point read, the API calls CreateContainerIfNotExistsAsync to get a Container object and then calls ReadItemAsync. Unde
- Container creation supplies the partition-key path and optional dedicated throughput
In .NET, Database.CreateContainerAsync accepts an id, partitionKeyPath, and optional throughput. ContainerProperties provides the richer definition needed for policies such as unique keys or hierarchical key paths. Setting a dedicated throughput allocation at creation is different from letting the container share a database allocation.
Trap Passing an item's partition-key value where CreateContainerAsync expects the partition-key path, which confuses a definition such as /category with a value such as bikes.
2 questions test this
- You are writing a .NET method that creates a container named products in a database by using the Azure Cosmos DB .NET SDK v3. Items include a category property whose values include bikes and helmets,
- You are writing a .NET deployment script that uses the Azure Cosmos DB .NET SDK v3 to create a container named tenants. The container must use a hierarchical partition key on /tenantId and /userId, an
- Resource proliferation can exhaust account metadata limits independently of item throughput
An account has a documented combined limit of 500 databases and containers, and metadata operations use a separate system allocation with a maximum of 240 RU/s. Increasing a container's item throughput does not enlarge that metadata allocation. Cache resource references and avoid unnecessary enumeration or creation calls in request loops.
Trap Raising item RU/s to remove throttling caused by repeated resource metadata calls, which uses a different throughput allocation.
3 questions test this
- You are designing a SaaS application on an Azure Cosmos DB for NoSQL account. The plan is to create one database for each of 300 customers and two containers in each database, for a total of 600 conta
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET API lists all containers in database db1 at the start of every request to find the container it needs. During peak hours, the API r
- You have an ASP.NET Core API that uses the Azure Cosmos DB .NET SDK v3. For every point read, the API calls CreateContainerIfNotExistsAsync to get a Container object and then calls ReadItemAsync. Unde
- CreateContainerIfNotExists checks identity rather than reconciling an existing configuration
CreateContainerIfNotExistsAsync checks for an existing container by id. If it exists, the method does not validate that properties such as throughput match the requested configuration. Inspect and manage the existing settings separately rather than using this initializer as a configuration-reconciliation operation.
Trap Calling CreateContainerIfNotExistsAsync with new throughput and assuming it updates an existing container, which checks existence instead of reconciling its properties.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders that has 400 RU/s of manual throughput. A deployment pipeline runs the following .NET code to raise the throughput to 4,000 RU/s: await dat
- You have a .NET setup routine that calls CreateContainerIfNotExistsAsync for a container named carts and then must log whether the container was created during this run or already existed. The routine
- GetContainer returns a proxy without establishing that the resource exists
CosmosClient.GetContainer(databaseId, containerId) obtains a proxy reference for later operations. It does not guarantee that the remote container exists. Use creation or a service operation when existence must actually be established; repeatedly acquiring a proxy is not a database validation request.
Trap Treating a non-null GetContainer result as proof that the remote container was deployed, which returns a proxy even without that guarantee.
2 questions test this
- You have a .NET monitoring job that uses the Azure Cosmos DB .NET SDK v3. The job must report whether a container named audit exists in database db1. It must not create the container if it's missing,
- You have a .NET health check that uses the Azure Cosmos DB .NET SDK v3. The check calls client.GetContainer("db1", "orders") and reports healthy when the returned object isn't null. After an operator
- Database and container deletion use resource-management methods rather than item deletion
In .NET, call Database.DeleteAsync to delete a database and Container.DeleteContainerAsync to delete a container. DeleteItemAsync instead removes one addressed item while retaining its container. Choose the resource-level operation only when removing the resource itself is the intended management action.
Trap Deleting individual items to remove a container resource, which leaves the container and its configuration in place.
2 questions test this
- You have an Azure Cosmos DB for NoSQL database named db1 that contains containers named orders, customers, and temp. The temp container is no longer needed, and its throughput and configuration must b
- You have an Azure Cosmos DB for NoSQL container named staging that has 1,000 RU/s of dedicated throughput. To decommission it, a script iterated through all items and called DeleteItemAsync for each o
- The free-tier discount must be selected at account creation
Azure Cosmos DB free tier provides a lifetime discount for the first 1,000 RU/s and 25 GB of storage on one opted-in account per subscription. Opt in when creating the account rather than planning to enable it later on an existing account. Work beyond the allowance is not automatically free.
Trap Creating a standard account first and planning to attach free tier after loading data, which misses the account-creation opt-in boundary.
2 questions test this
- Your team created an Azure Cosmos DB for NoSQL account named account1 with standard pricing and loaded 5 GB of test data. No other account in the subscription uses free tier. The team now wants the fr
- You have an Azure Cosmos DB for NoSQL account named account1 that was created with free tier in a single region. account1 has container A with 600 RU/s and container B with 700 RU/s of dedicated manua
- Reuse one SDK client per account for the application's lifetime
Use a singleton CosmosClient per Azure Cosmos DB account for the lifetime of the application. Its connections and routing caches are reused across databases and containers in that account. Separate tenant databases or partition keys in the same account do not require separate client instances; separate accounts do.
Trap Creating a new CosmosClient for every tenant partition in one account, which duplicates connection pools and routing caches without an account boundary.
2 questions test this
- You have a B2B application that gives each of 40 customers a dedicated Azure Cosmos DB for NoSQL account so that each customer can have its own regions and keys. One instance of the application serves
- You have a multitenant .NET API that stores each of 40 tenants in its own database, with one container per database, in a single Azure Cosmos DB for NoSQL account. The API creates a CosmosClient for e
- Direct mode reduces hops while Gateway uses a single HTTPS endpoint
When the environment supports the required connections and low latency is important, use Direct mode in the .NET or Java SDK. Direct connects to backend replicas over TLS-encrypted TCP, while Gateway routes requests through an HTTPS frontend. Gateway is appropriate for strict outbound-port restrictions or limited socket budgets and is the mode used by Python and the other non-.NET/non-Java SDKs.
Trap Selecting Direct mode in the Python SDK to bypass the gateway, which that SDK does not support.
2 questions test this
- You have a .NET service on Azure virtual machines that uses the Azure Cosmos DB .NET SDK v3. The virtual machines have no outbound port restrictions, and the service must minimize the latency of point
- You have a Python application that uses the Azure Cosmos DB Python SDK and runs on a virtual machine with all outbound ports open. A developer proposes switching the client to Direct mode to remove th
- Direct-mode clients still use HTTPS to obtain routing metadata
Direct mode changes the data-operation route but still uses Gateway HTTPS requests to discover account, container, and replica-routing information. The SDK caches that metadata and reuses the resulting TCP connections. An environment that permits backend TCP but blocks the metadata endpoint cannot fully initialize the client.
Trap Removing HTTPS access after selecting Direct mode, which still needs gateway metadata discovery and refresh.
2 questions test this
- You have a .NET application that uses Direct mode against an Azure Cosmos DB for NoSQL account. During a network review, an architect asks which requests the client still sends through the gateway ove
- You have a .NET service that uses Direct mode against an Azure Cosmos DB for NoSQL account through its public endpoint. The service has been running for a day and has cached its container and routing
- ApplicationRegion and ApplicationPreferredRegions guide client routing
ApplicationRegion tells the .NET SDK where the application runs, and ApplicationPreferredRegions supplies an ordered list of preferred account regions. These are alternative client-routing options configured through CosmosClientOptions; set one, not both. They do not create regions in the account or change the account's write-region configuration.
Trap Setting ApplicationRegion to provision a missing account region, which changes client preferences rather than account topology.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account with regions in West US, East US, and West Europe. A .NET application runs in East US 2, but for compliance reasons its reads must prefer West Europe firs
- You have an Azure Cosmos DB for NoSQL account named account1 with regions in West US and East US. A .NET application deployed in Japan East sets CosmosClientOptions.ApplicationRegion to Regions.JapanE
- A custom Cosmos serializer controls user payloads rather than SDK-owned resource types
CosmosClientOptions.Serializer customizes serialization and deserialization of user request and response payloads. SDK-owned types such as ContainerProperties and DatabaseProperties continue to use the SDK's default serializer. Keep serialized property names aligned with the stored JSON, especially the lowercase id and partition-key fields.
Trap Expecting a custom user serializer to redefine the serialization of ContainerProperties, which remains SDK-controlled.
2 questions test this
- You have a .NET application that uses the Azure Cosmos DB .NET SDK v3 with a custom CosmosSerializer set in CosmosClientOptions.Serializer. The serializer converts every property name to PascalCase. A
- You have a .NET application that uses the Azure Cosmos DB .NET SDK v3. You set CosmosClientOptions.Serializer to a custom CosmosSerializer that renames properties and omits null values. The applicatio
- Rate-limited retry count and retry wait time are independent client options
The .NET client's MaxRetryAttemptsOnRateLimitedRequests limits the number of retries after rate limiting. MaxRetryWaitTimeOnRateLimitedRequests limits the time budget spent waiting for such retries. Configure both with the application's tolerance for delayed responses; increasing the retry budget does not add service capacity.
Trap Raising only the request timeout to configure the number of HTTP 429 retries, which is governed by separate retry options.
2 questions test this
- You have a .NET bulk import job that uses the Azure Cosmos DB .NET SDK v3. Logs show that throttled requests fail after the SDK has made its maximum number of rate-limited retries, while the cumulativ
- You have a .NET service that uses the Azure Cosmos DB .NET SDK v3 with default client options. During peaks, the service receives 429 responses whose retry-after values are about 8 seconds. Logs show
- Idle TCP timeout and port reuse control sparse Direct-mode connection costs
For sparse Direct-mode workloads with many clients, IdleTcpConnectionTimeout can close unused TCP connections and PortReuseMode.PrivatePortPool can reduce ephemeral-port demand. Connections otherwise remain open for reuse by default. The idle timeout must be at least 10 minutes; avoid very short values because frequent reconnection adds overhead.
Trap Constructing a new client after each operation to release idle ports, which discards all routing and connection reuse instead of tuning connection lifetime.
2 questions test this
- You have hundreds of .NET worker instances that each use the Azure Cosmos DB .NET SDK v3 in Direct mode and send a few requests every hour. The hosts are running out of ephemeral ports. A developer pr
- You have a .NET application that uses Direct mode for sparse traffic and sets PortReuseMode to PrivatePortPool. You plan to set CosmosClientOptions.IdleTcpConnectionTimeout so that unused connections
- RequestTimeout alone is not an end-to-end operation deadline
The .NET client's RequestTimeout governs waiting for a network response, not the full operation across all internal work and retries. Use a CancellationToken as well when an end-to-end deadline is required. Keep timeout and retry settings consistent with the application's allowed operation duration.
Trap Treating RequestTimeout as a strict cap on the full operation including every retry, which only bounds a narrower network wait.
2 questions test this
- You have a .NET API that reads items by calling ReadItemAsync on an Azure Cosmos DB for NoSQL container. A single read can include several network requests because of retries. The team wants an approx
- You have a .NET application that sets CosmosClientOptions.RequestTimeout to 5 seconds. During a regional network issue, some ReadItemAsync calls take more than 15 seconds before they return, and the l
- The .NET SDK should be used asynchronously throughout the call chain
Use async and await for Azure Cosmos DB .NET operations rather than blocking on Task.Result or Task.Wait. Blocking asynchronous network calls can starve the thread pool and degrade concurrent request handling. An asynchronous SDK call provides little benefit if its caller immediately blocks waiting for it.
Trap Wrapping every asynchronous SDK call in Task.Wait to simplify request handling, which can exhaust request-processing threads.
2 questions test this
- You have an ASP.NET Core API whose repository methods await the Azure Cosmos DB .NET SDK, but the controller actions call repository.GetOrderAsync(id).Result. Under load, requests queue and latency cl
- You have a .NET worker that calls the Azure Cosmos DB .NET SDK by using .Result on each ReadItemAsync call, and the worker suffers thread pool starvation under load. In a code review, a developer prop
- Direct mode through public or service endpoints needs TCP ports 10000 through 20000
A Direct-mode client using public or service endpoints must reach backend TCP ports 10000 through 20000 in addition to Gateway HTTPS access on port 443. Select Gateway mode when the environment permits only the HTTPS route. Merely selecting Direct in client options cannot establish connections that the environment blocks.
2 questions test this
- You have a .NET service that will use Direct mode against an Azure Cosmos DB for NoSQL account through its public endpoint. The network team needs the complete list of outbound ports to allow from the
- You have a .NET service that runs in a network that allows only outbound HTTPS traffic on port 443 to Azure. The service uses the Azure Cosmos DB .NET SDK v3 against an account's public endpoint, and
- Direct-mode connection demand grows with partitions and active concurrency
A Direct-mode client establishes connections to replica endpoints on demand as it accesses physical partitions. More partitions increase the endpoints it may need, and higher concurrent request volume can require additional connections to the same endpoint. Estimate socket demand from both the accessed partition set and active concurrency.
- Direct TCP concurrency depends on both requests per connection and connections per endpoint
MaxRequestsPerTcpConnection controls how many requests can share one Direct TCP connection, while MaxTcpConnectionsPerEndpoint caps connections to each backend endpoint. Together they bound the requests that can be sent simultaneously to that endpoint. Configure this active concurrency budget separately from idle-connection lifetime or client-port reuse.
Trap Increasing IdleTcpConnectionTimeout to raise active request capacity, which retains idle connections longer rather than changing request multiplexing or the endpoint connection cap.
- GatewayModeMaxConnectionLimit controls the SDK-managed Gateway connection pool
For the SDK-managed HTTP handler, GatewayModeMaxConnectionLimit sets the maximum concurrent connections to the target endpoint in Gateway mode and defaults to 50. With a custom HttpClientFactory, configure the supplied handler's MaxConnectionsPerServer instead. Direct TCP connection settings do not configure this HTTP pool.
Trap Increasing MaxTcpConnectionsPerEndpoint to expand a Gateway HTTP pool, which configures Direct backend TCP connections rather than Gateway connections.
- HttpClientFactory supplies the HttpClient used for SDK HTTPS communication
CosmosClientOptions.HttpClientFactory accepts a delegate that supplies an HttpClient for HTTPS communication. This covers Gateway operations and Direct-mode metadata requests, making it useful when an application manages shared HTTP clients. It does not replace the Direct TCP data transport.
- Built-in serialization options can remove the need for a custom CosmosSerializer
Use CosmosClientOptions.SerializerOptions for supported built-in serialization settings, such as ignoring null values, without implementing a custom serializer. To select System.Text.Json for user payloads, set UseSystemTextJsonSerializerWithOptions with JsonSerializerOptions. Reserve a custom CosmosSerializer for behavior these built-in options do not supply.
- System.Text.Json payload serialization does not remove the Newtonsoft.Json dependency
The Azure Cosmos DB .NET v3 SDK still uses Newtonsoft.Json internally for system types when user payloads use System.Text.Json. Microsoft's setup guidance therefore requires an explicit Newtonsoft.Json dependency and recommends version 13.0.3 or higher. Keep that dependency when switching the application's payload serializer.
- A finite HTTP pooled-connection lifetime lets a reused client react to DNS changes
When configuring the HTTP transport for a long-lived CosmosClient, set SocketsHttpHandler.PooledConnectionLifetime so pooled HTTPS connections are periodically replaced. An open pooled connection does not react to a DNS change; creating replacement connections allows the transport to resolve the endpoint again. Supply the handler through HttpClientFactory while retaining singleton client reuse, and balance connection churn against the required DNS responsiveness.
Trap Tuning IdleTcpConnectionTimeout to refresh the HTTPS connection pool, because that option controls idle Direct-mode TCP connections rather than the HTTP handler's pooled lifetime.
Implement database operations
Read full chapterCheat sheet
Sharp facts the exam loves — scan these before test day.
- SELECT VALUE returns the projected JSON value without an object wrapper
Use SELECT VALUE c.categoryName FROM c to return an array of category-name values rather than objects containing a categoryName property. A regular property projection returns an object per result. VALUE can also project an explicitly constructed JSON object when the application needs a custom result shape.
Trap Using SELECT c.categoryName for a client expecting scalar strings, which produces property-bearing objects instead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named members. Each item stores first and last properties for a member's given name and family name. A mobile client binds the query results directly to
- You have an Azure Cosmos DB for NoSQL container named catalog. A published REST contract requires each query result to be a JSON object that has a categoryName property. The current query is SELECT c.
- Query projections can rename fields and access nested JSON values
The SELECT list can rename a projected property with AS and access nested properties using dot notation. For example, SELECT c.metadata.status AS state FROM c returns a state field sourced from metadata.status. Array elements can be accessed by index when a particular position is intended.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named invoices. Each item embeds a customer object with a name property and a summary object with a total property. Invoices are queried thousands of ti
- You have an Azure Cosmos DB for NoSQL container named orders. Each item has a lines array of objects that contain sku and qty properties. You are completing the following query so that each result inc
- You have an Azure Cosmos DB for NoSQL container named tickets. Each item stores its workflow state in a nested property, as in {"id": "t1", "metadata": {"status": "open"}}. The items are written by se
- IS_DEFINED tests property presence while IS_NULL tests an explicit null value
Use IS_DEFINED(c.optionalField) to determine whether a JSON property exists. Use IS_NULL(c.optionalField) to test whether its value is null; a missing property is undefined rather than null. These functions distinguish omitted data from a deliberately stored null.
Trap Using IS_NULL to select every item missing an optional property, which tests a different JSON state.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named people. Many items omit the optional middleName property. A query that uses WHERE IS_NULL(c.middleName) to find people without a middle name retur
- You have an Azure Cosmos DB for NoSQL container named subscriptions. When a customer reactivates, App1 sets "cancelledAt": null to show that a cancellation was cleared. Items for customers who never c
- ARRAY_CONTAINS requires true for a partial object match
ARRAY_CONTAINS(array, value) checks whether the array contains the specified value and defaults to full-object matching. Supply a third argument of true to match an object using only the supplied subset of properties. This tests array membership without projecting one result for every element.
Trap Omitting the third argument when matching only one field of a larger array object, which requests a full rather than partial object match.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. In older items, the lines array stores plain strings such as A1-red and B7-blue rather than objects. A developer reuses a filter that wa
- You have an Azure Cosmos DB for NoSQL container named orders. Each order item has a lines array of objects, such as { "sku": "A1", "qty": 2, "color": "blue" }, and App1 doesn't know the qty or color v
- NoSQL JOIN expands arrays within an item rather than joining documents
Use JOIN t IN c.tags to enumerate an item's array elements and filter or project each matching element. NoSQL joins are scoped to a single item and do not join separate documents or containers. Multiple joined arrays produce a cross product within that item.
Trap Using a SQL-style JOIN between book items and review items, which is not a supported cross-document join.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. One item has a colors array with three values and a sizes array with four values. You run SELECT c.id, cl, s FROM c JOIN cl IN c.colors
- You have an Azure Cosmos DB for NoSQL container named library. Book items and review items are stored as separate items, and each review has a bookId property. A developer writes SELECT b.title, r.rat
- DISTINCT removes duplicates from the projected query results
When a query must return each category value only once, use SELECT DISTINCT VALUE c.category FROM c. DISTINCT compares the projected results, so repeated category values collapse into one result even when they come from different items.
Trap Projecting id alongside category in SELECT DISTINCT to produce a category-only list, which makes deduplication compare the entire projected object instead of category alone.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products that holds four items. Two items have category set to Tools, one item has category set to Books, and the fourth item has no category prop
- You have an Azure Cosmos DB for NoSQL container named products. A developer runs SELECT DISTINCT c.category, c.id FROM c to build a list of categories, but the results contain the same category many t
- TOP needs ORDER BY to select a predictable ordered subset
TOP limits how many query results are returned but does not itself define which ordered values come first. Pair it with ORDER BY when the requirement is the cheapest or otherwise ordered first N results. A parameter can supply the TOP count.
Trap Using TOP alone to retrieve the cheapest items, which limits results without specifying price order.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. A home page widget runs SELECT TOP 10 * FROM c WHERE c.status = 'open' to show the oldest open orders. The container holds about 50,000 op
- You have an Azure Cosmos DB for NoSQL container named scores. A leaderboard API lets a caller choose how many top scores to return, from 1 to 50, by passing n in the request. You need a query that ret
- COUNT of a constant counts matching items while COUNT of a property counts its values
Use SELECT VALUE COUNT(1) FROM c with the required WHERE filter to count matching items. COUNT(c.name) instead counts occurrences of the name expression, which is a different requirement when items may omit that property. VALUE produces a scalar count rather than an object-wrapped aggregate.
Trap Using COUNT(c.optionalField) as the total item count, which counts values of an optional expression rather than every matching item.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named customers that stores 120,000 items. A dashboard tile labeled Total customers runs SELECT VALUE COUNT(c.email) FROM c and displays 97,400. An audi
- You have an Azure Cosmos DB for NoSQL container named products. Only some products have a discount property, and its value can be a number or null. Products without an active promotion simply omit the
- Multi-value and scalar subqueries can be used in different query positions
A multi-value subquery returns multiple single-column results and is used as a relational expression in FROM. A scalar subquery returns a single value and can appear in SELECT or WHERE as well as FROM. NoSQL query results have one JSON value column, so relational table subqueries with multiple columns are not the model.
2 questions test this
- A product report runs SELECT p.name, (SELECT VALUE COUNT(1) FROM c IN p.colors) AS colorsCount FROM products p against an Azure Cosmos DB for NoSQL container. A new team member asks how to classify th
- A developer with a relational background writes FROM products p JOIN (SELECT t.key, t.value FROM t IN p.tags) and plans to treat the subquery as a two-column derived table in an Azure Cosmos DB for No
- Query text and expression counts have independent service limits
The documented maximum SQL query text length is 512 KB. A query normally supports up to 10 JOIN statements and 10 UDFs, with increases to those count limits available through support. Parameterization and document size limits do not remove query-text or expression-count constraints.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named claims. An analyst's 3 KB query calls 11 different user-defined functions, each with the udf. prefix, in its SELECT and WHERE clauses. The query f
- You have an Azure Cosmos DB for NoSQL container named products. A vendor reporting tool generates one query that uses 12 JOIN expressions to expand nested arrays, and the query fails because it exceed
- You have an Azure Cosmos DB for NoSQL container named devices. App1 receives 30,000 device ids without partition key values and builds one query with WHERE c.id IN followed by every id. The generated
- A query targets one container rather than spanning database containers
A NoSQL query may span logical partitions within its selected container, but it does not query several containers or accounts as one resource. If a model distributes data across containers, application code must issue the relevant requests separately and combine their results. Cross-partition querying and cross-container querying are different capabilities.
Trap Treating enable_cross_partition_query as permission to query every container in a database, which expands partition scope only within the selected container.
3 questions test this
- An Azure Cosmos DB for NoSQL database has two containers, invoices and vendors. An analyst opens Data Explorer on the invoices container and runs SELECT * FROM vendors v, expecting to see vendor recor
- A team designing a new Azure Cosmos DB for NoSQL app considers putting customers, orders and invoices in three separate containers. A reviewer recommends colocating the entity types in fewer container
- A Python job calls query_items on the orders container proxy with enable_cross_partition_query=True and a query that also refers to customers, a second container in the same Azure Cosmos DB for NoSQL
- BETWEEN includes both endpoints of a filter range
BETWEEN evaluates whether a value falls within an inclusive range. For example, c.price BETWEEN @low AND @high includes prices equal to either bound as well as prices between them.
Trap Using c.price > @low AND c.price < @high for an inclusive price band, which excludes both boundary values.
2 questions test this
- A query against an Azure Cosmos DB for NoSQL container named products uses WHERE c.price BETWEEN 50 AND 100 to build a mid-range price list. One product has a price of exactly 100, stored as a number.
- A storefront filter lets shoppers pick a price band from 50 to 100, and products priced exactly 50 or exactly 100 must be included. The current query on an Azure Cosmos DB for NoSQL container uses WHE
- IN in a filter tests membership in a value list
A WHERE predicate such as c.status IN ('Open', 'Pending') matches an item when its status equals one of the listed values. This use of IN is a Boolean membership test, not the array iteration introduced by IN in FROM or JOIN.
2 questions test this
- A support dashboard must list tickets from an Azure Cosmos DB for NoSQL container whose status is either Open or Pending. Each ticket item has a single status string. The developer wants one compact p
- A developer reviews WHERE c.status IN ('Open', 'Pending') in an Azure Cosmos DB for NoSQL query and confuses it with the IN used in FROM t IN c.tags, which iterates an array. You need to explain what
- GROUP BY forms summary rows for equal grouping values
Use GROUP BY when the result needs one summary per distinct value or combination of grouping expressions. For example, SELECT c.category, COUNT(1) AS itemCount FROM c GROUP BY c.category projects the grouping value with an aggregate calculated for that group. Ungrouped item properties do not identify a single value for such a summary row.
Trap Using ORDER BY c.category to request a count per category, which sorts item results without forming aggregate groups.
2 questions test this
- A catalog team needs one result row per product category with the number of items in that category from an Azure Cosmos DB for NoSQL container. A developer wrote SELECT c.category, COUNT(1) AS itemCou
- A sales report must return one summary row for every combination of category and brand in an Azure Cosmos DB for NoSQL container, with the item count for that combination. The query starts with SELECT
- SUM calculates a total over expression values
Use SUM(c.amount) when a query needs the total amount across matching items. The function aggregates the amount expression rather than counting how many items matched.
Trap Using COUNT(c.amount) for a monetary total, which counts expression occurrences rather than adding their values.
2 questions test this
- A finance API must return the total of all invoice amounts in an Azure Cosmos DB for NoSQL container as a single number rather than an object. Every invoice stores amount as a number. The current quer
- You have an Azure Cosmos DB for NoSQL container named stock. Four items match a report filter: three have quantity values of 10, 20 and 30, and the fourth has no quantity property at all. None of the
- AVG calculates the mean of expression values
Use AVG(c.amount) when a query needs the average amount across its numeric input values. SELECT VALUE AVG(c.amount) returns the aggregate directly rather than an object-wrapped property.
Trap Using SUM(c.amount) for an average amount, which returns a total rather than a mean.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. Two watch items match a filter, with price values of 98 and 105. A developer runs SELECT AVG(p.price) AS averagePrice FROM products p wi
- You have an Azure Cosmos DB for NoSQL container named products. A .NET pricing service deserializes the first result of a query directly into a double that holds the mean price of all products. Every
- AVG skips undefined values but becomes undefined for included nonnumeric values
AVG omits undefined inputs from its calculation. If an included input is null, a string, or a Boolean, the entire aggregate instead returns undefined. Filter a heterogeneous property to numeric values when only its numeric observations should contribute to the average.
Trap Using IS_DEFINED alone to prepare mixed values for AVG, which retains defined null, string, and Boolean inputs.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named reviews. Every review item has a Boolean recommended property set to true or false. A dashboard must show the share of reviews that recommend the
- A ratings query, SELECT VALUE AVG(c.rating) FROM c, returns undefined on an Azure Cosmos DB for NoSQL container. Most items store rating as a number, but some store null and some store the string "N/A
- MIN and MAX return the lowest or highest expression value, not the item
Use MIN(c.price) when a query needs the lowest value of an expression among matching items, and MAX(c.price) when it needs the highest. Either aggregate returns that expression value, not the complete item containing it.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. A product page must show the complete cheapest product item, including its name, sku and price, so that App1 can render it without anoth
- You have an Azure Cosmos DB for NoSQL container named products. Several products can share the lowest price, and a clearance page must list every product item that is tied at that lowest price, with a
When an item should qualify if any child matches a condition, use EXISTS with a correlated array subquery, such as EXISTS (SELECT VALUE t FROM t IN c.tags WHERE t.score > @minimum). The expression returns a Boolean for the parent. Multiple matching children do not create multiple outer results for that parent.
Trap Using an outer JOIN to return each qualifying parent once, which produces one outer row for every matching child unless additional deduplication is applied.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. Each product item has a tags array of objects with a name property. A catalog export must return every product exactly once, including p
- A product catalog in Azure Cosmos DB for NoSQL stores a reviews array on each product item. A page must list each product once if at least one of its reviews has a score above 4. A query that joins c.
- ARRAY turns subquery results into a nested result array
Use ARRAY(subquery) in SELECT to return a nested array built from an item's child values. For example, ARRAY(SELECT VALUE t FROM t IN c.tags WHERE t.score > @minimum) retains only matching children inside the parent's projected array. The outer result remains parent-shaped rather than one row per child.
Trap Using JOIN t IN c.tags to construct a filtered nested array, which expands rows instead of collecting the child results into an array.
2 questions test this
- Product items in an Azure Cosmos DB for NoSQL container named catalog have a tags array of objects, each with name and score properties. A product page needs one result per product that contains the p
- You have an Azure Cosmos DB for NoSQL container named products. One item has a sizes array: [{ "key": "5" }, { "key": "6" }]. A developer runs SELECT p.name, ARRAY(SELECT s FROM s IN p.sizes) AS sizes
Use a correlated aggregate scalar subquery when each outer item needs a summary of its own children. For example, SELECT c.id, (SELECT VALUE COUNT(1) FROM t IN c.tags WHERE t.score > @minimum) AS matchingTags FROM c returns a separate child count for each item. The aggregate operates inside that item's correlated subquery rather than over all container items.
- Query property names are case-sensitive
A query must use the exact case of a stored JSON property name. The paths c.name and c.Name address different properties, so changing capitalization does not select the same value automatically.
- Bracket notation addresses property names that dot notation cannot express safely
Use quoted bracket notation, such as c['display name'] or c['order'], for property names containing spaces, punctuation, or reserved words. The quoted text is the literal property name rather than a sequence of nested path components.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named catalog. Items imported from a spreadsheet have a property literally named unit price, with a space, such as { "id": "p1", "unit price": 12.5 }. A
- An Azure Cosmos DB for NoSQL item has a nested object, "metadata": {"link": "https://contoso.com/p/1"}, and no other properties containing a period. A developer writes SELECT c["metadata.link"] AS lin
- Undefined property expressions are omitted from projected objects
A scalar property path evaluates to undefined when the property does not exist. If a projected object's property is assigned that undefined result, the property is omitted from the result rather than emitted as null. A projection containing only that missing property can therefore produce an empty object.
2 questions test this
- A query against an Azure Cosmos DB for NoSQL container is SELECT VALUE {"nick": c.nickname} FROM c. Some user items don't have a nickname property at all, and the client deserializes each result into
- User items in an Azure Cosmos DB for NoSQL container have an id, and only some have a nickname property. A mobile client runs SELECT c.id, c.nickname FROM c and must handle every result shape it can r
- Type predicates test usable JSON types rather than mere property presence
Use IS_NUMBER, IS_STRING, or IS_ARRAY when a query condition depends on an expression having that JSON type. For example, IS_NUMBER(c.amount) selects numeric values before numeric aggregation. A present property can still have a different type from the operation's intended input.
Trap Using IS_DEFINED(c.amount) as numeric validation, which accepts any defined type rather than only numbers.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named inventory. A data-quality job must find items whose qty property exists but holds something other than a number, such as a string or null, so that
- You have an Azure Cosmos DB for NoSQL container named offers. Some offer items have a numeric discount, some have "discount": null, and the rest have no discount property. An audit query runs SELECT *
- You have an Azure Cosmos DB for NoSQL container named payments. Over time, the amount property has been written as a number in most items, as a string such as N/A in some items and as null in a few, a
- CONTAINS tests for a substring anywhere in a string
Use CONTAINS(c.name, @text) when the required text may appear anywhere in the string. Matching is case-sensitive by default; a third argument of true requests case-insensitive matching. The second argument is substring text rather than a LIKE wildcard pattern.
Trap Using ARRAY_CONTAINS for a text substring, which tests array-element membership rather than characters within a string.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. A developer who is used to SQL wildcards writes WHERE CONTAINS(c.sku, "AB%") to find SKUs that begin with AB, such as AB-100 and AB-200.
- You have an Azure Cosmos DB for NoSQL container named articles. A search box must return articles whose description includes the search term anywhere, at the start, in the middle or at the end, and th
- You have an Azure Cosmos DB for NoSQL container named books. Users search titles by typing a word, and the word can appear anywhere in a title. Users type in any capitalization, so searching for adven
- STARTSWITH tests a string prefix
Use STARTSWITH(c.code, @prefix) when the required text must occur at the beginning of the string. A match elsewhere in the string is insufficient for this predicate.
Trap Using CONTAINS for a required code prefix, which also matches the text at nonleading positions.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named stores. An autocomplete query uses WHERE STARTSWITH(@prefix, c.name), where @prefix is the text that the user typed. It returns only stores whose
- You have an Azure Cosmos DB for NoSQL container named customers that holds 20 million items. A lookup box must return customers whose lastName begins with the typed text, passed as @prefix, with match
- ENDSWITH tests a string suffix
Use ENDSWITH(c.fileName, @suffix) when the required text must occur at the end of the string. This expresses a suffix condition rather than an arbitrary substring search.
Trap Using CONTAINS to validate a filename suffix, which also accepts a matching substring followed by more characters.
2 questions test this
- An upload validator queries an Azure Cosmos DB for NoSQL container with WHERE CONTAINS(c.fileName, '.pdf') to list files that should all be PDFs. A security review finds report.pdf.exe in the list, an
- You have an Azure Cosmos DB for NoSQL container named users with 3 million items. An audit query must return users whose email address ends with the company domain passed as @domain, such as @contoso.
- LIKE matches string patterns using wildcard syntax
Use LIKE when matching requires a pattern rather than a single literal substring. In its pattern, '%' matches zero or more characters and '_' matches one character. An ESCAPE clause allows a wildcard character to be treated literally when needed.
Trap Passing a percent-delimited pattern to CONTAINS, which searches for that literal text instead of interpreting LIKE wildcards.
2 questions test this
- Promotion items in an Azure Cosmos DB for NoSQL container have description text such as Save 20% today or Order 20 items. A query must return only descriptions that contain the literal text 20%, so th
- Product names in an Azure Cosmos DB for NoSQL container follow patterns such as Pro Max X, Pro Lite X and ProX. A query must return products whose name starts with Pro and ends with X, with any number
- ARRAY_LENGTH counts elements inside an array value
Use ARRAY_LENGTH(c.tags) to obtain the number of elements in an item's tags array. It operates on that JSON array rather than aggregating query rows from the container.
Trap Using COUNT(c.tags) to count one item's tags, which counts occurrences of the array expression across query inputs rather than its elements.
2 questions test this
- A data-quality query against an Azure Cosmos DB for NoSQL container uses WHERE ARRAY_LENGTH(c.tags) = 0 to find products that have no tags. It returns products whose tags array is empty, but products
- You have an Azure Cosmos DB for NoSQL container named articles. Each item has a tags array of strings, such as ["cosmos", "sdk", "query", "index"]. An editor page must list only the articles that have
- ARRAY_SLICE returns a segment of an array value
ARRAY_SLICE(array, start, length) returns an array segment beginning at the specified index with up to the specified number of elements. The length argument is optional, and a negative start locates the starting position relative to the array's end. This changes an array value rather than selecting a window of outer query rows.
Trap Using outer OFFSET LIMIT to shorten every item's nested array, which selects result rows rather than slicing each array value.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named sensors. Each item has a readings array that is ordered oldest first, and arrays have different lengths. A diagnostics view must project only the
- You have an Azure Cosmos DB for NoSQL container named devices. Each item has a log array whose entries are ordered newest first. A support page shows entries 10 at a time, and its second page must sho
- You have an Azure Cosmos DB for NoSQL container named recipes. Each recipe item has a steps array whose first element is always a preparation note that must be hidden. The app must project every remai
- ARRAY_CONCAT combines two or more arrays into one array
Use ARRAY_CONCAT(c.primaryTags, c.secondaryTags) to construct one array from the supplied array values. The function combines arrays within an expression rather than joining items or query result sets.
Trap Using CONCAT to combine JSON arrays, which is the string-concatenation function rather than the array operation.
- GETCURRENTDATETIME returns current UTC time as ISO 8601 text
GETCURRENTDATETIME() returns the current UTC date and time as an ISO 8601 string. Its result is date-time text, not a numeric Unix timestamp or a separate JSON DateTime type.
- DateTimeAdd shifts an ISO date-time by a specified date part
Use DateTimeAdd(datePart, amount, dateTime) to add a signed integer amount to a supported UTC ISO 8601 date-time string. For example, the date part 'day' selects day-based arithmetic, and a negative amount subtracts days. The result is another date-time string.
Trap Adding a numeric day count directly to an ISO date string, which does not invoke date-part arithmetic.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named subscriptions. Each item has a startAt property such as 2024-01-15T00:00:00.0000000Z. A developer projects DATETIMEADD("mm", 1, c.startAt) AS rene
- You have an Azure Cosmos DB for NoSQL container named sessions. App1 reads the current UTC time before each query, as an ISO 8601 string, and binds it to @now. A cleanup report must return sessions wh
- DateTimeDiff counts boundaries crossed for the selected date part
DateTimeDiff(datePart, start, end) returns a signed integer difference between supported UTC ISO 8601 date-time strings. The value counts boundaries crossed for the selected date part rather than measuring an exact elapsed interval in fractional units. Choose the date part to match the intended comparison.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named events. One item has start 2023-12-31T23:00:00.0000000Z and end 2024-01-01T01:00:00.0000000Z, two hours apart. A report projects DATETIMEDIFF("yyy
- You have an Azure Cosmos DB for NoSQL container named subscriptions. Each item stores startDate and endDate as ISO 8601 UTC strings. Billing charges one fee for each calendar month boundary that a sub
- You have an Azure Cosmos DB for NoSQL container named tickets. A dashboard query runs SELECT c.id, DateTimeDiff('hour', GetCurrentDateTime(), c.dueAt) AS hoursLeft FROM c. A ticket has dueAt set to 20
- Built-in rounding functions express the required integer rounding rule
Use ROUND for the nearest integer, CEILING for the smallest integer at least as large as the input, and FLOOR for the largest integer no greater than the input. Select the function according to the required rounding direction rather than writing a UDF for ordinary integer rounding.
Trap Using ROUND when capacity must always round upward, which can round down instead of applying CEILING's upper-integer rule.
- CONCAT builds a string from string expressions
Use CONCAT when a projection needs a string assembled from several values, such as a label built from an item's string fields. This built-in string operation avoids a custom UDF for ordinary concatenation.
- TRIM removes leading and trailing whitespace or selected characters
Use TRIM(c.label) to remove whitespace from both ends of a string expression. An optional second string specifies the characters to trim instead. The function does not remove matching characters from the middle of the value.
Trap Using REPLACE to clean only surrounding spaces, which can also remove spaces inside the text that should remain.
- GeoJSON geography points place longitude before latitude
A GeoJSON Point represents a location with a type of 'Point' and a coordinates array. For geography data, coordinates are ordered longitude first and latitude second, in degrees. Preserve that ordering when constructing locations for spatial predicates.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named stores. A developer is adding each store's location so that queries can call ST_DISTANCE and ST_WITHIN on it. The source system exports latitude a
- A store-locator app writes store locations to an Azure Cosmos DB for NoSQL container as GeoJSON Points with coordinates [latitude, longitude]. Proximity queries using ST_DISTANCE return stores on the
- Geometry uses a flat coordinate model while geography uses a round-earth model
Choose geometry for data expressed in a Euclidean flat coordinate system. Choose geography for actual earth locations and distances in a round-earth coordinate system. The spatial model determines how the coordinates represent the application space.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named surveys that uses the geography type. A field team supplies site locations as eastings and northings in meters from the National Grid of Britain.
- You have an Azure Cosmos DB for NoSQL container named layouts. Each item stores the shelves of one warehouse floor as shapes in a local grid measured in meters from a corner of the building, with no l
- ST_DISTANCE measures separation between GeoJSON shapes
Use ST_DISTANCE(location, reference) when a spatial query needs proximity, such as locations within a specified radius. The function returns a numeric distance; with the default geography reference system, the result is in meters. Compare that value with a radius expressed in matching units.
Trap Comparing ST_DISTANCE directly with a radius supplied in kilometers, which mismatches the default geography result's meter units.
2 questions test this
- A proximity filter against an Azure Cosmos DB for NoSQL container uses WHERE ST_DISTANCE(c.loc, @p) < 10 to find venues within 10 kilometers of the user. Venue locations are geography Points, and the
- You have an Azure Cosmos DB for NoSQL container named restaurants that uses the default geography reference system. Each item has a location GeoJSON Point. A mobile app passes the user's position as a
- ST_WITHIN tests whether the first GeoJSON shape lies within the second
Use ST_WITHIN(shape, boundary) for spatial containment, such as determining whether a location is inside a service area. The argument order identifies the shape being tested and the containing shape.
Trap Using ST_INTERSECTS when complete containment is required, which also accepts shapes that merely overlap.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named serviceareas. Each item stores one delivery area as a GeoJSON Polygon in c.area. When a customer places an order, App1 passes the customer's locat
- You have an Azure Cosmos DB for NoSQL container named stores. Each item has a location GeoJSON Point, and @zone is a GeoJSON Polygon for a delivery area that contains several stores. A developer filte
- You have an Azure Cosmos DB for NoSQL container named parcels. Each item stores a land parcel as a GeoJSON Polygon in c.parcel, and a flood zone is passed to the query as the GeoJSON Polygon @zone. An
- ST_INTERSECTS tests whether two GeoJSON shapes intersect
Use ST_INTERSECTS(firstShape, secondShape) when a query needs to know whether spatial shapes intersect. Unlike a containment test, an intersection can match partially overlapping shapes without requiring one to lie wholly inside the other.
Trap Using ST_WITHIN to find every overlapping service area, which excludes overlaps where neither shape contains the other.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named routes. Each item has a route GeoJSON LineString, and @zone is a GeoJSON Polygon for a flood area. A dispatcher must find routes that cross or tou
- Two delivery-zone polygons in an Azure Cosmos DB for NoSQL container partly overlap, and neither zone lies completely inside the other. A developer projects ST_INTERSECTS(a.zone, b.zone) and ST_WITHIN
- WHERE requires true even when a comparison evaluates to undefined
NoSQL comparisons across JSON types or involving an undefined property can produce undefined instead of coercing the operands to a common type. WHERE includes an item only when the filter evaluates to true. Consequently, c.status != 'Closed' does not by itself select items that lack status; include an explicit missing-property condition when those items should qualify.
Trap Using NOT(c.status = 'Closed') to include documents with no status, because NOT applied to undefined remains undefined.
- The ternary operator selects a projection value from a Boolean condition
Use condition ? valueIfTrue : valueIfFalse when a query must choose an output expression according to a Boolean condition. For example, SELECT VALUE (c.active ? 'Active' : 'Inactive') FROM c produces a label for items whose active property is Boolean.
Trap Using WHERE c.active = true to label both active and inactive items, because the filter removes the inactive items instead of projecting their alternative label.
- The coalesce operator supplies a fallback for an undefined property
Use the ?? operator when a projection needs a default value for a property that may be absent. For example, c.collapsible ?? false returns false when collapsible is undefined and otherwise uses the property's value. This supplies usable output for heterogeneous item shapes without requiring every stored item to contain that property.
Trap Using IS_NULL(c.collapsible) as the missing-property test for a fallback expression, because an omitted property is undefined rather than an explicit null.
- Parameterized queries bind values through names beginning with an at sign
When query values come from user input, bind them as parameters instead of interpolating them into SQL text. In .NET, construct QueryDefinition and call WithParameter with a name such as @category; JSON query specifications use the same leading @ in each parameter name. The service handles the value as data with appropriate escaping.
Trap Building query text with string interpolation around a category value, which treats input as query syntax rather than a bound value.
2 questions test this
- A developer calls the Azure Cosmos DB for NoSQL REST API directly from a Go service and posts a parameterized query body whose query property is SELECT * FROM p WHERE p.price < @maxPrice. The paramete
- You are building an ASP.NET Core API that queries an Azure Cosmos DB for NoSQL container named products by using the .NET SDK v3. Users type a category name into a search box, and the API returns the
- Query parameter values can contain any valid JSON without schema-based type validation
NoSQL parameter values can be strings, numbers, booleans, null, arrays, or nested JSON. They are not validated against a container schema because the data is schema-free. Choose value types matching the intended JSON comparison instead of expecting parameter binding to convert types.
Trap Supplying every numeric filter value as a string and relying on schema-driven conversion, which parameter binding does not provide.
- A .NET query iterator must be drained page by page
Container.GetItemQueryIterator returns a FeedIterator rather than the complete query result. Call ReadNextAsync while HasMoreResults is true, then enumerate the items inside each FeedResponse. Reading one response is sufficient only when the iterator reports no additional pages.
Trap Enumerating only the first FeedResponse from a large query, which leaves later result pages unread.
2 questions test this
- You are writing a .NET loop that drains a FeedIterator<Order> returned by GetItemQueryIterator for an Azure Cosmos DB for NoSQL container. Inside the loop, the code awaits ReadNextAsync and appends ea
- A .NET job uses Container.GetItemQueryIterator with the query SELECT * FROM c WHERE c.region = 'west' against an Azure Cosmos DB for NoSQL container named orders. The job awaits ReadNextAsync once and
- MaxItemCount limits one query page rather than the entire query
MaxItemCount specifies the maximum number of items in an individual query execution's response. The service may return fewer items because of throughput, response-size, or execution-time limits, and a page may even be empty. A value of -1 removes the client-specified page-item limit but does not remove service paging.
Trap Using MaxItemCount as a replacement for TOP to limit the entire result set, which only limits each response page.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. A .NET web app shows search results 25 at a time by setting MaxItemCount to 25 and passing the continuation token from each response to
- You have an Azure Cosmos DB for NoSQL container named orders. App1 uses the .NET SDK to run a cross-partition query with QueryRequestOptions.MaxItemCount set to 100. App1 calls ReadNextAsync in a loop
- A query continuation token bookmarks stateless query progress
A query continuation token lets a later request resume progress without a server-held query session. REST uses x-ms-continuation; a nonempty response token indicates further results. With the same SDK version these query tokens do not expire, so preserve them as opaque bookmarks with the associated query.
Trap Keeping a database cursor open as a prerequisite for resuming a query, which is unnecessary for stateless continuation-token paging.
2 questions test this
- A .NET Web API serves an Azure Cosmos DB for NoSQL query to a single-page app one page per HTTP request and keeps no server-side state between requests. After awaiting ReadNextAsync on the FeedIterato
- A stateless web API runs on several instances behind a load balancer and pages through an Azure Cosmos DB for NoSQL query for a mobile app. Users tap Next page minutes or hours after the first page, a
- GROUP BY and unordered DISTINCT do not support query continuation tokens
Queries using GROUP BY cannot use continuation tokens because of the state they would need to retain. DISTINCT also lacks continuation-token support unless ORDER BY is added. Check the query shape before designing a resumable paging API around a token.
Trap Exposing continuation-token paging for a GROUP BY report, which that query shape does not support.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named employees. A .NET reporting app runs SELECT DISTINCT VALUE e.department FROM employees e and must let users resume the list later by saving a cont
- A reporting API runs SELECT c.region, COUNT(1) AS orders FROM c GROUP BY c.region against an Azure Cosmos DB for NoSQL container named sales. The product owner wants the API to return the groups in sm
- OFFSET LIMIT skips results and takes a specified result window
OFFSET m LIMIT n skips m results and includes up to n subsequent results. Pair it with the intended ORDER BY when a particular ordered window is required. This is query-level result selection rather than the SDK's per-response page-size setting.
Trap Changing MaxItemCount to skip earlier query results, which controls page size and supplies no offset.
2 questions test this
- An export tool must skip the first 100 orders, sorted by orderDate, from an Azure Cosmos DB for NoSQL container named orders and then write the next 50 orders to a file. A developer proposes setting M
- A catalog page in a web app shows products from an Azure Cosmos DB for NoSQL container named products, 25 per page, sorted by name. Visitors can jump directly to any page number from a pager control,
- ToFeedIterator enables asynchronous LINQ query consumption
In .NET, GetItemLinqQueryable builds an IQueryable expression that can be filtered with LINQ. Convert the expression with ToFeedIterator and consume it asynchronously using ReadNextAsync. Direct enumeration of the IQueryable uses synchronous execution instead.
Trap Enumerating the IQueryable directly to obtain asynchronous query execution, which takes the synchronous path.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. App1, an ASP.NET Core API, builds a LINQ query by calling GetItemLinqQueryable<Order>() and adding a Where clause. App1 returns one page p
- You are reviewing App1, an ASP.NET Core API that queries an Azure Cosmos DB for NoSQL container named books. The code calls container.GetItemLinqQueryable<Book>(true), adds .Where(b => b.Price > 100),
- You are reviewing three .NET snippets that query an Azure Cosmos DB for NoSQL container named orders: - SnippetA: foreach over container.GetItemLinqQueryable<Order>(true).Where(o => o.Open) - SnippetB
- Queries can span partitions when a full partition value is not specified
A NoSQL query can return data from multiple logical partitions rather than requiring one full partition-key value. In the Python SDK, enable_cross_partition_query=True enables the documented cross-partition query path. This differs from point-operation addressing, which requires the item's partition key.
Trap Calling read_item with only an id to request a cross-partition lookup, which does not turn the point operation into a query.
2 questions test this
- A Python reporting script calls container.query_items with the query SELECT * FROM c WHERE c.status = 'late' against an Azure Cosmos DB for NoSQL container partitioned by /customerId. The script doesn
- A Python support tool receives only an order id, but the Azure Cosmos DB for NoSQL container named orders is partitioned by /customerId. The tool calls container.read_item(item=order_id) without a par
- Python cross-partition continuation support depends on the query shape
Current pagination documentation supports Python continuation tokens for streamable cross-partition queries such as SELECT with a WHERE filter. Cross-partition sorting, counting, and DISTINCT queries do not support those Python tokens. Verify the SDK and query shape before designing a Python paging endpoint instead of assuming every query accepted by query_items has the same resumption support.
Trap Copying a .NET resumable sorted cross-partition query directly into a Python token-based paging API, which has different continuation support.
2 questions test this
- A Python Flask endpoint pages through an Azure Cosmos DB for NoSQL container partitioned by /customerId and returns a continuation token with each page. Requests never include a partition key, so ever
- A team ports a .NET API that resumes a cross-partition query sorted with ORDER BY c.createdAt by using continuation tokens. The Python rewrite uses query_items without a partition key and stores the t
- The five-second and 4-MB query limits apply to a page rather than the entire query
A single query page retrieval is limited to five seconds of execution and a response of at most 4 MB. When a supported query reaches these boundaries, the service can return a page and continuation token so execution resumes in another request. These limits do not impose a five-second lifetime or 4-MB total-result limit across the complete paged query.
- A point read uses both id and partition key without executing a query
When an item's id and partition-key value are known, use ReadItemAsync or read_item for a point read. A 1-KB item read under session, consistent-prefix, or eventual consistency costs approximately 1 RU. A SELECT query with equivalent equality filters still executes as a query rather than becoming a point-read API call.
Trap Issuing SELECT with id and partition-key filters to obtain point-read charging, which does not change the query into a point operation.
- ReadItemStreamAsync avoids deserializing the item into a user object
Use ReadItemStreamAsync when a component needs the raw JSON stream rather than a deserialized object. Its ResponseMessage exposes the content stream for direct forwarding or custom processing. ReadItemAsync<T> is appropriate when the application needs a typed object.
Trap Reading a typed object and immediately serializing it again merely to forward raw JSON, which performs avoidable conversion.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named profiles. App1, a .NET gateway, reads a profile with ReadItemStreamAsync by using its id and partition key value, and then copies the response Con
- You have an Azure Cosmos DB for NoSQL container named catalog that uses /category as the partition key. App1 is a .NET API that receives a product id and category, reads the product with ReadItemAsync
- ReadManyItemsAsync retrieves a set of known id and partition-key pairs
When many independent items are known by id and partition-key pairs, use ReadManyItemsAsync rather than constructing an IN query. The API accepts the pairs and returns the matching items, with better documented latency than the equivalent large IN-query pattern. It needs item addresses rather than a SQL predicate.
Trap Building a large IN query for items whose full point-read addresses are already available, which bypasses the API designed for those pairs.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products that uses /categoryId as the partition key. A .NET pricing job receives 300 independent product references from several categories, and e
- A .NET pricing service receives 200 product references, each with an id and a categoryId value, which is the partition key of the Azure Cosmos DB for NoSQL container named products. The references spa
- An item payload requires a lowercase string property named id
An Azure Cosmos DB for NoSQL item payload requires a JSON string property named id, with that exact lowercase spelling. Properties named Id, ID, iD, or _id are ordinary JSON properties rather than substitutes, so configure C# serialization to emit the required JSON name.
2 questions test this
- A .NET v3 app serializes a Customer class whose key property is declared as public string Id { get; set; } with the default serializer settings. Every CreateItemAsync call to an Azure Cosmos DB for No
- You have an Azure Cosmos DB for NoSQL container named customers that uses /country as the partition key. A Python job loads JSON documents exported from a legacy system by calling create_item. Each do
- Replace writes the complete replacement representation of an existing item
Use ReplaceItemAsync to replace an existing item's full JSON representation. Its id argument must match the payload's id, and omitted properties are not retained as though the operation were a merge. Use Patch when only selected properties should change.
Trap Sending only changed fields to ReplaceItemAsync, which treats that partial payload as the full replacement representation.
2 questions test this
- A .NET job loads an order item, edits it, and calls ReplaceItemAsync(order, "order-1001", new PartitionKey(order.customerId)) on an Azure Cosmos DB for NoSQL container. Because of a copy-paste bug, th
- A .NET order service changes an order's status by calling ReplaceItemAsync with a small object that contains only id, customerId and status. After each update, the order's lines, totals and address di
- Upsert handles creation or replacement and reports which occurred
When either insertion or replacement is acceptable, use UpsertItemAsync to handle both outcomes with one API call. Inspect the response status code to distinguish the result: HTTP 201 means an item was created, and HTTP 200 means an item was replaced.
Trap Using ReplaceItemAsync for a write that must also create a missing item, which selects an operation requiring an existing item.
- DeleteItemAsync identifies an item by id and partition key and returns no item body
DeleteItemAsync<T> takes the item's id and partition-key value, with optional request options and cancellation. Its response Resource is always null, so retain needed item data before deleting it. The response still contains operation metadata.
Trap Using the delete response's Resource to archive the deleted document, which does not return the deleted item body.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders that uses /customerId as the partition key. A .NET cleanup job calls DeleteItemAsync<Order>(order.id, new PartitionKey(order.id)) for each
- A .NET retention job archives expired orders. For each order, it calls DeleteItemAsync<Order> with the id and partition key against an Azure Cosmos DB for NoSQL container, and then writes response.Res
- Disabling write content responses retains headers while omitting the returned resource
When the application does not need the written document echoed back, set EnableContentResponseOnWrite to false. Create, upsert, patch, and replace responses then omit the resource while retaining status and headers such as RequestCharge. This reduces bandwidth and client conversion work; it also suppresses a trigger's returned content.
Trap Disabling write content responses while relying on returned trigger content, which is suppressed along with the resource body.
- A write timeout can leave the operation's commit status unknown
A timeout while waiting for a write response does not prove that the service failed to commit the write. Design recovery around operation identity and idempotency rather than blindly repeating a non-idempotent action. A retried create can return Conflict because the initial timed-out create actually succeeded.
Trap Repeating an increment after every write timeout without checking application identity, which can apply the business action twice.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named invoices that uses /customerId as the partition key. App1 uses the azure-cosmos Python SDK and calls create_item without setting retry_write. One
- You have an Azure Cosmos DB for NoSQL container named payments that uses /accountId as the partition key and has no unique key policy. App1 creates each payment with CreateItemAsync and a client-gener
- SDK timeout retries distinguish safe reads from ambiguous writes
Azure Cosmos DB SDKs retry read-operation timeouts and connectivity failures when retry is feasible. They do not generally replay a write after a response timeout because they cannot determine whether it already reached the service. An application retry policy must preserve that read-versus-write distinction rather than treating every HTTP 408 or 503 identically.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named devices. App1 uses the azure-cosmos Python SDK with default client settings and doesn't pass retry_write on any call. During a network incident, A
- A team writes a custom retry policy for a .NET service that uses Azure Cosmos DB for NoSQL. The first draft replays any operation that fails with HTTP 408 or 503 exactly like a read. In testing, repla
- Invalid requests and oversized payloads need correction rather than transient retries
HTTP 400 Bad Request and HTTP 413 Request Entity Too Large are not transient retry cases in the SDK resilience guidance. Correct the request or reduce its payload before resubmitting it. Waiting and sending the same invalid request again does not address either cause.
Trap Applying the HTTP 429 retry-after policy to HTTP 413, which delays an unchanged oversized payload rather than making it valid.
2 questions test this
- A team writes a custom retry policy for a .NET client of Azure Cosmos DB for NoSQL. The policy must stop retrying requests that can't succeed without changes and instead log them for correction, follo
- A .NET ingestion service writes documents to an Azure Cosmos DB for NoSQL container. Some writes fail with HTTP 413, and the service's retry handler treats them like HTTP 429 by waiting and resending
- An item id has a maximum length of 1,023 bytes
An Azure Cosmos DB item id supports at most 1,023 bytes. Validate this identifier limit separately from the partition-key value limit and the overall document-size limit.
- Service-side item ids cannot contain slash or backslash
The service-side item-id character rules exclude '/' and '' even though both can be represented in JSON strings. Microsoft recommends alphanumeric ASCII ids for best interoperability with SDKs and other clients. JSON string validity alone is therefore insufficient identifier validation.
- Patch reduces payload and client work without guaranteeing a major RU reduction
When only selected properties change, use Patch to send those operations instead of a complete replacement document. This reduces network payload and client-side processing. Patch is still billed in RUs, and the documentation warns not to expect a significant RU reduction solely from choosing Patch.
Trap Selecting Patch solely to guarantee a large reduction in write RU charges, which is not a promised benefit.
2 questions test this
- A .NET service updates the lastSeen and status properties of 60-KB device documents in an Azure Cosmos DB for NoSQL container thousands of times per minute. Today it reads each document, changes the t
- Field devices report status to an Azure Cosmos DB for NoSQL container named devices. Each device document is about 40 KB, and each report changes only the lastSeen and battery properties. A developer
- Patch Add inserts an array element while Set updates an existing array position
Patch Add at a valid array index inserts a new element and shifts later elements. Set at a valid array index updates the existing element instead. Add with the '-' array position appends an element, whereas an index beyond the array length is invalid.
Trap Using Add at an existing array index to overwrite that element, which inserts and shifts instead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. An item has a tags array with the values sale, clearance and new, in that order. App1, a .NET app, must change the second tag from clear
- You have an Azure Cosmos DB for NoSQL container named devices. Each device item has a history array whose length varies from item to item. App1 must add a new entry after the last existing element of
- Patch Replace requires the target property to exist
Patch Replace uses strict replace-only semantics and fails when its target property is absent. Add and Set can add an absent object property, so choose Replace when an existing field is an invariant of the update. This property-level operation differs from replacing the whole item.
Trap Using Set to enforce that an object property already exists, which can create the missing property.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named offers. App1 updates the discount property of offer items by using partial document update. Every valid offer must already have a discount propert
- You have an Azure Cosmos DB for NoSQL container named customers. App1 updates customer items with PatchItemAsync and the operation PatchOperation.Replace("/loyaltyTier", "gold"). For customers that ne
- Patch Increment supports positive or negative adjustments and creates a missing field
Patch Increment atomically adjusts a numeric field by the supplied positive or negative amount. If the field is absent, the operation creates it with that amount as its value. It avoids a client-side read-modify-write cycle for a simple numeric adjustment.
Trap Reading a counter and issuing an unconditional replacement for every adjustment, which permits concurrent readers to overwrite each other's updates.
2 questions test this
- A ticketing service must decrease the seatsLeft counter of an event item in an Azure Cosmos DB for NoSQL container by one for each sale. Many sales happen concurrently, and the team wants to avoid a r
- You have an Azure Cosmos DB for NoSQL container named articles. New article items don't have a views property. When a reader opens an article, App1 sends a single patch request that contains only Patc
- Patch Remove and Move require existing source locations
Patch Remove fails if its target is absent and shifts later array positions when it removes an element. Move removes a value from an existing 'from' location and adds it to the destination. A move destination cannot be a child of its own source location.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named customers. Each item has an address object. App1 must keep the current address as a previous address and then store a new address, in one patch re
- You have an Azure Cosmos DB for NoSQL container named accounts. A cleanup job sends the same patch request to 10,000 items: Remove /legacyCode and Set /migrated to true. About 3,000 items never had a
- Patch paths escape tilde and slash characters using JSON Pointer notation
A Patch path identifies a location in the JSON document. Within property names, encode '
' as '0' and '/' as '~1' so they are not interpreted as path syntax. A property whose name contains a slash is not addressed the same way as two nested properties.Trap Using an unescaped slash inside a property name in a Patch path, which is interpreted as a nested-path separator.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named rates. Each item has a top-level property whose name is rate~eur/usd, including the tilde and the slash, and other systems read that exact name. A
- You have an Azure Cosmos DB for NoSQL container named devices. While investigating a support case, you review App1's partial document update requests and find a Set operation whose path is /limits/req
- You have an Azure Cosmos DB for NoSQL container named inventory. Items have a property named stock~level, including the tilde. App1 must set stock~level to 5 by using PatchItemAsync, but only if the i
- A conditional Patch evaluates a SQL-like predicate before applying changes
Use a Patch filter predicate such as from c where c.quantity > 0 when an update is valid only in a particular current business state. The Patch fails if the predicate is not satisfied. Multiple items can be patched transactionally when they share the same partition-key value and participate in a transactional batch.
Trap Checking quantity in a separate read followed by an unconditional Patch, which leaves a race between validation and update.
2 questions test this
- An order item and an inventory item share the same partition key value in an Azure Cosmos DB for NoSQL container. A .NET service must patch both items so that either both changes commit or neither doe
- You have an Azure Cosmos DB for NoSQL container named inventory that uses /storeId as the partition key. App1 builds a transactional batch for store7 that patches item A and item B. Each patch is Incr
- PatchItemAsync submits an addressed item's PatchOperation list
In .NET, call container.PatchItemAsync<T> with the item's id, partitionKey, and patchOperations. Construct the list with PatchOperation methods such as Add, Replace, Remove, or Increment and the required JSON paths. The request describes selected changes rather than supplying a complete replacement item.
Trap Passing a partial item body to ReplaceItemAsync as though it were a patch, which replaces the representation instead of interpreting PatchOperation values.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named customers partitioned by /tenantId. To change a customer's email, App1 calls ReplaceItemAsync with an object that holds only id, tenantId, and ema
- A .NET developer must change two properties of an existing order item in an Azure Cosmos DB for NoSQL container by sending only those changes, not a complete replacement item. The order's id and parti
- Conditional .NET patching sets PatchItemRequestOptions.FilterPredicate
To make PatchItemAsync conditional on a business-state predicate, set FilterPredicate on PatchItemRequestOptions and pass those requestOptions with the call. The value is a SQL-like expression such as 'FROM c WHERE c.used = false'. This places the condition on the patch request itself.
Trap Putting the condition in QueryRequestOptions before calling PatchItemAsync, which does not attach a filter predicate to the patch operation.
2 questions test this
- A .NET service must apply PatchItemAsync to a product item in an Azure Cosmos DB for NoSQL container only when the product's used property is false. The condition must be evaluated by the service as p
- You have an Azure Cosmos DB for NoSQL container named products. App1 lowers an item's price with PatchItemAsync, and the patch must apply only when the item's used property is false at the moment the
- Patch Add cannot recursively create missing parent nodes
Patch Add can create an absent final property only when its parent node already exists. Adding '/profile/address/city' therefore requires the parent object at '/profile/address' to exist. Establish the missing ancestors first rather than expecting one child Add to create the whole path.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. Order items don't have a shipping property yet. App1 sends one patch with Add at /shipping/carrier and the value contoso, and the request
- You have an Azure Cosmos DB for NoSQL container named tickets. Each ticket item has a status property that holds a string, such as open. App1 sends a patch with Add at /status/reason and the value lat
- One item Patch specification supports at most ten operations
A single item Patch specification can contain at most 10 patch operations. Count every operation in that list, even when several operations affect the same property.
2 questions test this
- A .NET service updates 12 separate properties of one item in an Azure Cosmos DB for NoSQL container with a single PatchItemAsync call, and the call is rejected because of the number of operations. The
- You are writing coding guidelines for developers who use partial document update against an Azure Cosmos DB for NoSQL container. The guidelines must state how many operations a single item patch speci
- Patch cannot modify system-generated metadata properties
Patch rejects changes to system-generated properties such as _ts, _etag, and _rid. The service owns those values, so a partial-update request cannot assign its own metadata versions or timestamps.
2 questions test this
- A migration tool copies items into an Azure Cosmos DB for NoSQL container and then sends a patch that sets _ts on each item to the original system's timestamp so reports keep their history. Every patc
- A developer plans a partial document update that changes several properties of a document in an Azure Cosmos DB for NoSQL container in one request. A reviewer warns that one of the planned target prop
- An item's ttl property can be patched
Use Patch to change an item's ttl without replacing the complete document. The ttl property is supported for partial updates even though system-generated properties are not. The resulting value still follows the container's TTL enablement and item-TTL rules.
2 questions test this
- A team wants to use partial document update to change the expiration of individual items in a TTL-enabled Azure Cosmos DB for NoSQL container without replacing whole documents. A reviewer believes ttl
- A container in Azure Cosmos DB for NoSQL has DefaultTimeToLive set to 3600. A support agent must extend the lifetime of one customer's session item to one day without rewriting the rest of the item, w
- Cosmos DB Patch does not implement the RFC Copy and Test operations
Azure Cosmos DB partial document update is inspired by JSON Patch RFC 6902 rather than implementing every RFC operation. Copy and Test are not implemented. Use the supported conditional Patch predicate when an update must depend on a current business-state condition.
- Bulk execution optimizes independent requests rather than making them one transaction
Enable AllowBulkExecution on the .NET CosmosClient when submitting many independent operations and aggregate throughput matters more than individual-operation latency. The SDK optimistically batches requests for efficiency. Bulk does not provide an all-or-nothing commit across the submitted work.
Trap Using bulk execution to guarantee an atomic transfer between unrelated partition keys, which batching does not make transactional.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that hosts a container named container1. Each night, App1 must load about two million independent telemetry items from thousands of devices
- You are designing order processing for an Azure Cosmos DB for NoSQL container named orders that uses /orderId as the partition key. Each order header and its order-line items share the same orderId va
- You have an Azure Cosmos DB for NoSQL container named accounts that uses /customerId as the partition key. App1 enables AllowBulkExecution on its CosmosClient and concurrently submits a debit to an it
- A transactional batch commits ordered point operations within one logical partition
When related point operations must succeed or fail together, use a transactional batch for one container and one partition-key value. Operations execute in their defined order under ACID guarantees with snapshot isolation. If any operation fails, the entire batch rolls back.
Trap Grouping operations merely because their items share a physical partition, which is broader than the supported logical-partition transaction boundary.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1 that uses /category as the partition key. App1 builds a transactional batch for the category value bikes that first creates item A and
- You have an Azure Cosmos DB for NoSQL container named container1 that uses /tenantId as the partition key. The items for tenant1 and tenant2 currently reside on the same physical partition. A develope
- You have an Azure Cosmos DB for NoSQL container named sales that uses /storeId as the partition key. When App1 records a sale, it must create a receipt item and replace the matching stock item, both f
- Transactional batches are limited by operation count, payload size, and execution time
A transactional batch supports at most 100 operations, a payload no larger than 2 MB, and an execution duration no longer than 5 seconds. All three constraints apply together. Splitting an oversized unit of work into separate batches also splits its atomic commit boundary.
Trap Splitting an oversized transaction into two batches while promising one atomic commit, which creates two independent transactions.
3 questions test this
- A .NET service builds a transactional batch of 80 upsert operations for one customer's partition key value in an Azure Cosmos DB for NoSQL container. Each upserted item is about 40 KB, so the batch ca
- You have an Azure Cosmos DB for NoSQL container named orders. App1 must write each order's line items atomically by using one transactional batch per order. You review three designs for the largest or
- You have an Azure Cosmos DB for NoSQL container named inventory that uses /warehouseId as the partition key. A stock transfer must update 140 items for one warehouse, and either every update must comm
- A failed batch identifies its failing operation while the others report failed dependency
A failed transactional batch preserves the actual error code on the operation that caused failure. Other operations report HTTP 424 Failed Dependency, so inspect the individual results to locate the root failure. A duplicate create can therefore show 409 for one operation and 424 for its peers.
Trap Treating every HTTP 424 in a batch as an independent root failure, which obscures the operation carrying the original error.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named inventory. App1 executes a transactional batch for the partition key value store7 that creates item A, replaces item B, and deletes item C, in tha
- You have an Azure Cosmos DB for NoSQL container that App1 writes to by using transactional batches of up to 40 operations. App1 logs one alert for every operation result that is not successful. After
- You have an Azure Cosmos DB for NoSQL container named orders. App1 executes a transactional batch of five operations for one partition key value. The batch fails, and the per-operation results show HT
- CreateTransactionalBatch builds work that runs only when ExecuteAsync is called
In .NET, call container.CreateTransactionalBatch(partitionKey), add operations such as CreateItem or ReplaceItem, then call ExecuteAsync. Use IsSuccessStatusCode and GetOperationResultAtIndex to inspect execution results. Constructing the batch or appending an operation does not submit it to the service.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. App1 executes a transactional batch by using the .NET SDK and immediately reads GetOperationResultAtIndex<Order>(0).Resource to log the cr
- You have an Azure Cosmos DB for NoSQL container named sales that uses /storeId as the partition key. In App1, a .NET method runs the following code: var batch = container.CreateTransactionalBatch(new
- Python transactional batches use operation tuples and one partition key
The Python SDK's execute_item_batch accepts a list of operation tuples and a shared partition_key value. Each tuple contains an operation type, its positional arguments, and supported per-operation options. CosmosBatchOperationError exposes the failed operation's index and responses when the transaction fails.
2 questions test this
- You have a Python application that uses the azure-cosmos SDK with a container named catalog partitioned on /category. A nightly job updates items in two categories, road-bikes and helmets, and passes
- You have a Python application that uses the azure-cosmos SDK and a container named products partitioned on /category. The application builds a list named ops and passes it to execute_item_batch with p
- An ETag condition on one batch operation protects the whole transaction's commit
A transactional batch can make an individual operation conditional on an ETag; failure of that precondition prevents the entire same-partition batch from committing. In Python, put the supported if_match_etag option in that operation tuple's options dictionary. This composes optimistic concurrency with the batch's atomic boundary rather than performing a separate version check before the batch.
Trap Checking the ETag in an application read before submitting unconditional batch writes, which leaves a race between the read and the transaction.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named accounts. App1 reads a balance item, checks in code that its _etag still matches the cached value, and then executes a transactional batch that re
- You have an Azure Cosmos DB for NoSQL container named ledger. App1 runs a transactional batch for one partition key value that creates two entry items and replaces a balance item. The replace operatio
- You have a Python application that uses the azure-cosmos SDK with a container named quotas. A transactional batch replaces a tenant's quota item and creates three usage items for the same tenant. You
- Bulk execution needs concurrently submitted item operations to group useful work
With AllowBulkExecution enabled, submit multiple ordinary item-operation tasks before awaiting the complete group, for example by collecting CreateItemAsync tasks and awaiting Task.WhenAll. The SDK groups concurrent operations into service calls and returns each operation's result to its caller. Awaiting each item before submitting the next leaves no concurrent work for that grouping mechanism to exploit.
- Stored procedures provide server-side JavaScript control flow for transactional work
Use a stored procedure when transactional business logic needs to run inside the NoSQL database engine, including decisions based on reads during execution. Stored procedures are JavaScript registered on a container and invoked with one logical partition-key value. A transactional batch is the alternative for a predefined set of point operations in the application's SDK language.
Trap Choosing a C# stored procedure for server-side branching, which the NoSQL JavaScript runtime cannot execute.
2 questions test this
- A loyalty app stores each household's members in one logical partition of an Azure Cosmos DB for NoSQL container. A transfer must read both members' point balances inside the database engine, decide w
- An order service written in C# must create an order item and update the matching inventory item atomically. Both items share the same partition key value in an Azure Cosmos DB for NoSQL container, and
- An exception aborts all writes in a stored-procedure transaction
Stored-procedure and trigger operations run inside an implicit transaction. Successful script completion commits the work, while an exception rolls it all back. Explicit SQL BEGIN TRANSACTION and COMMIT statements are not needed in this JavaScript programming model.
Trap Catching a validation error and returning normally when the intention is to roll back earlier writes, which can allow the implicit transaction to commit.
2 questions test this
- A JavaScript stored procedure registered on an Azure Cosmos DB for NoSQL container creates three items in one logical partition. After the third create callback succeeds, the script reads a configurat
- A stored procedure in an Azure Cosmos DB for NoSQL container creates three line items and then validates the order total. When validation fails, the script catches the error, calls setBody with an err
- Server-side operation acceptance signals when a script must stop queuing work
Server-side collection operations return a Boolean indicating whether the operation was accepted. A false value signals that the script must wrap up instead of queuing more work because execution or throughput boundaries are being approached. Use callback-driven sequencing and a resumable application protocol for work too large for one bounded invocation.
Trap Ignoring false from createDocument and continuing to queue remaining writes, which disregards the bounded execution signal.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named imports. A stored procedure loops through an input array of 1,000 items for one partition key value and calls createDocument for each item, one at
- A bulk-import stored procedure loops through an input array in an Azure Cosmos DB for NoSQL container and calls createDocument for each element. Partway through a large array, createDocument returns f
- Registered triggers run only when the client explicitly requests them
A registered pre-trigger or post-trigger does not automatically execute on every matching write. The client must include the trigger in the operation's request options. This makes triggers unsuitable for enforcing a rule on writes from clients that do not invoke them.
Trap Registering a trigger as the sole universal validator for all client writes, which does not make invocation automatic.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. You register a post-trigger named trgAudit on the container that writes an audit item for each change. Three teams write to orders by usin
- A team registers a pre-trigger named validateOrder on an Azure Cosmos DB for NoSQL container with TriggerOperation.Create. Their own service passes the trigger in ItemRequestOptions.PreTriggers. Weeks
- A UDF computes query values and cannot perform database operations
A JavaScript user-defined function extends NoSQL query logic and is called within queries. It has no access to the context object, so it is compute-only rather than a mechanism for writing additional items. Choose a stored procedure or trigger when server-side data operations are required.
Trap Calling a UDF to update an audit document during a SELECT query, which requires database access unavailable to UDFs.
2 questions test this
- A developer is designing JavaScript user-defined functions for an Azure Cosmos DB for NoSQL container and plans which logic to put in them. The UDFs will be registered on the container and called from
- A reporting dashboard runs a SELECT query with a registered UDF that formats prices from an Azure Cosmos DB for NoSQL container. The compliance team now wants an audit item written to the container ev
- Server-side JavaScript cannot import modules
Azure Cosmos DB's server-side JavaScript runtime does not support importing modules into stored procedures, triggers, or UDFs. Keep required logic within the supported script or execute dependency-heavy logic in application code. A familiar JavaScript language does not imply a full Node.js runtime.
Trap Importing an npm package inside a stored procedure, which assumes Node.js module support unavailable in the database runtime.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named events. A stored procedure that began with const moment = require('moment') failed at run time, so a developer plans to move the date formatting i
- A developer writes a stored procedure for an Azure Cosmos DB for NoSQL container that starts with const _ = require('lodash') to sort and group input items. Registration succeeds, but every execution
- Pre-triggers can modify the request while post-triggers run after the operation
Use a pre-trigger when validation or request-body changes must happen before the item operation. A post-trigger runs after the operation and can access its response message. Triggers take no input parameters of their own, and their registered TriggerOperation must permit the operation with which they are invoked.
Trap Using a Create-only trigger with a replace request, which is outside that trigger's registered operation scope.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named tasks. When App1 creates a task, a createdAt timestamp must be added to the item before it's stored if the incoming item doesn't already contain o
- A trigger named trgStamp was registered on an Azure Cosmos DB for NoSQL container with TriggerType.Pre and TriggerOperation.Create. A new .NET feature now calls ReplaceItemAsync and passes trgStamp in
- Stored procedures use the script context for database work and returned results
A JavaScript stored procedure obtains its execution context with getContext(). Use getCollection() for database operations and their callbacks, and getResponse().setBody(...) to supply the result returned to the caller. Database-operation completion is handled through the server-side callback contract.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named teams. A stored procedure must read two player items in one partition and replace both in a single transaction. The developer wrote var container
- You have an Azure Cosmos DB for NoSQL container named sales. A stored procedure reads the sale items for one store, sums their amounts in a variable named total, and ends with the statement return tot
- CreateStoredProcedureAsync registers a script rather than executing it
In .NET v3, register a stored procedure through container.Scripts.CreateStoredProcedureAsync with StoredProcedureProperties containing its Id and JavaScript Body. Registration makes the named script available on the container. It does not invoke the script's database logic.
2 questions test this
- A .NET v3 deployment tool must add a JavaScript stored procedure named spArchive to an Azure Cosmos DB for NoSQL container so that services can invoke it later. The tool reads the script text from spA
- A release pipeline for an Azure Cosmos DB for NoSQL app calls container.Scripts.CreateStoredProcedureAsync with StoredProcedureProperties whose Body holds a cleanup script that deletes expired drafts.
- ExecuteStoredProcedureAsync invokes a registered script with a partition key and arguments
In .NET v3, call container.Scripts.ExecuteStoredProcedureAsync<T> with the registered procedure id, the partition-key value, and its argument array. The argument values become the JavaScript function's inputs, while T describes the returned result. This is a distinct client operation from registering the script body.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named accounts. A stored procedure is defined as function transfer(fromId, toId, amount). App1 calls Scripts.ExecuteStoredProcedureAsync<string>("transf
- A stored procedure named spTransfer is registered on an Azure Cosmos DB for NoSQL container partitioned by /householdId. A .NET v3 service must run it for household h-42 with three inputs: a sender id
- Queries invoke registered UDFs with the udf qualifier
Call a registered query UDF using udf followed by its registered name, such as udf.Tax(c.income). The expression can appear in a projection or a WHERE predicate. The qualifier distinguishes the custom function from built-in query functions.
Trap Calling ExecuteStoredProcedureAsync to evaluate a UDF in a query filter, which invokes a stored procedure instead of the query's registered scalar function.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named payroll. The JavaScript file for a UDF defines function tax(income), and App1 registers it by using UserDefinedFunctionProperties with Id set to T
- You have an Azure Cosmos DB for NoSQL container named incomes. You register a user-defined function with the id Tax by using Scripts.CreateUserDefinedFunctionAsync. A report then runs SELECT * FROM t
- A server-side script invocation must finish within five seconds
Azure Cosmos DB server-side JavaScript has a five-second execution ceiling. If transactional script work does not finish within that limit, its transaction rolls back. Divide larger work into bounded invocations rather than relying on a longer application-side timeout to extend the service limit.
Trap Increasing CosmosClientOptions.RequestTimeout to allow a longer stored-procedure transaction, which changes client response waiting rather than the server-side script ceiling.
2 questions test this
- A JavaScript stored procedure on an Azure Cosmos DB for NoSQL container runs a long sequence of updates inside one logical partition. In one execution, the script is still working when it reaches the
- A stored procedure in an Azure Cosmos DB for NoSQL container updates every item in a large logical partition in a single call. As the partition grows, executions start failing, and none of their updat
- Repeated execution-boundary violations can make a script inactive
Azure Cosmos DB can mark a server-side script inactive when it repeatedly violates execution boundaries, preventing further execution. Rework the script to honor the boundaries and recreate it as documented. Repeatedly invoking the same overlong logic is not a recovery strategy.
- Queries inside a script may not see changes made earlier by that script transaction
Queries executed inside a stored procedure or trigger may not observe changes to items made by the same script transaction. This applies to both SQL queryDocuments calls and JavaScript language-integrated queries. Do not base later query logic on an assumption that every earlier mutation has become query-visible within that invocation.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named budgets. A stored procedure replaces a budget item with a new amount and then runs queryDocuments in the same execution to sum all budget items fo
- You have an Azure Cosmos DB for NoSQL container named carts. A stored procedure creates a cart item for one partition key value and then uses getContext().getCollection().filter() in the same executio
- One write operation supports at most one pre-trigger and one post-trigger
A write operation can invoke one pre-trigger and one post-trigger. Registering several triggers, or using request properties represented as lists, does not allow chaining multiple triggers of the same type on that write.
- EnableScriptLogging returns server-side script diagnostics with the execution response
Set EnableScriptLogging to true in the stored-procedure request options when database-side script logs are needed. Script logging is disabled by default, and enabled log output is available through the execution response, including the x-ms-documentdb-script-log-results header. Capturing the application's console alone does not request this server-side trace.
- Stored procedures reserve RUs upfront using their prior average charge
A stored-procedure execution reserves an upfront RU amount equal to the script's average consumption in previous invocations. Large variation between invocation costs can therefore affect throughput-budget utilization even when average business demand appears modest. Include this reservation behavior when comparing a script with suitable client-side batch or bulk operations.
- Application-side SDK reads suit large read-only workloads better than stored procedures
When the workload mainly performs many reads or queries without transactional writes, use application-side SDK operations rather than packaging those reads into a stored procedure. Stored procedures and triggers execute on the primary replica and are intended for transactional write logic. The application-side read path is the documented choice for using database throughput efficiently in this read-heavy case.
- Item TTL values have an effect only when TTL is enabled on the container
A missing or null container defaultTtl disables automatic expiration, even when an item has a ttl property. Set defaultTtl to -1 to enable TTL without a default expiration, or to a positive number of seconds for a default lifetime. Enabling the container feature and assigning an item's lifetime are separate steps.
Trap Writing a positive item ttl into a container with defaultTtl unset, which leaves automatic expiration disabled.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named events whose time to live was never configured. The container holds three kinds of items: - Session items that have ttl set to 3600 - Log items th
- An Azure Cosmos DB for NoSQL container holds two million log items, and none of them has a ttl property. To clean up old logs, an administrator sets the container's Time to Live to On (no default), wh
- An item's ttl overrides the container default and minus one prevents expiration
With container TTL enabled, an item's positive ttl value replaces the container's default lifetime for that item. Set ttl to -1 when a particular item must never expire despite a positive container default. Omit the item property when the container default should apply.
Trap Removing an item's ttl to protect it from a positive container default, which makes it inherit that expiration instead.
2 questions test this
- An Azure Cosmos DB for NoSQL container named carts has DefaultTimeToLive set to 86400. A premium customer's cart item is written with a ttl property of 604800 so it lasts longer than standard carts. T
- An Azure Cosmos DB for NoSQL container named events has DefaultTimeToLive set to 2592000, so most items expire 30 days after their last modification. Audit events are stored in the same container and
- TTL is measured from the item's last modification rather than its creation
TTL is expressed in seconds since the item's last modification, represented by its system timestamp. Updating the item resets the expiration interval relative to that new modification time. A frequently updated item can therefore remain alive far longer than its original creation time plus TTL.
Trap Using native TTL as an immutable creation-time retention deadline for an item that is repeatedly updated, which restarts the interval.
2 questions test this
- A records system must permanently delete each contract item from an Azure Cosmos DB for NoSQL container exactly 90 days after the contract was created. Users edit contracts several times during their
- A container in Azure Cosmos DB for NoSQL stores user sessions with DefaultTimeToLive set to 1800. A web app updates each active session item every 5 minutes to record the latest page view. Some sessio
- An item TTL must be minus one or a positive supported integer
An item's ttl must be -1 or a positive nonzero integer no greater than 2,147,483,647. Zero and null are not valid item-expiration configurations. Remove the property to inherit the container default instead of representing inheritance with null.
2 questions test this
- A developer wants archive items in an Azure Cosmos DB for NoSQL container that has DefaultTimeToLive set to -1 to expire after roughly 100 years. The developer computes 3153600000 seconds and writes i
- An Azure Cosmos DB for NoSQL container has DefaultTimeToLive set to 3600. A .NET import job copies items from another system, and some of them carry their own ttl values. For one group of items, the j
- Expired items disappear from queries before background deletion necessarily completes
An item stops appearing in query responses as soon as its TTL expires. Physical deletion is a background task and can be delayed when insufficient RUs are available. Query visibility and completion of storage cleanup are therefore not the same event.
Trap Waiting for a background purge to assume expired items are excluded from queries, which occurs at expiration rather than purge completion.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named sessions in a provisioned throughput account, and the container has DefaultTimeToLive set to 1800. During a load spike, user requests consume all
- You have an Azure Cosmos DB for NoSQL account that uses provisioned throughput. A container named telemetry has DefaultTimeToLive set to 86400, and its RU consumption stays near 100 percent throughout
- TTL deletion uses spare provisioned RUs but is charged as deletes in serverless
On a provisioned-throughput account, TTL background deletion uses leftover RUs not consumed by user requests. On a serverless account, TTL deletion is charged in RUs at the normal delete-operation rate. Include that lifecycle work when comparing serverless costs for short-lived data.
Trap Treating automatic expiration as free delete work in a serverless estimate, which still incurs delete-operation RU charges.
2 questions test this
- A team estimates the monthly cost of a serverless Azure Cosmos DB for NoSQL account that ingests millions of short-lived telemetry items, each with a ttl of 3600. A finance analyst's spreadsheet treat
- You have an Azure Cosmos DB for NoSQL account that uses provisioned throughput. A container named events has 10,000 RU/s of manual throughput and runs at about 70 percent utilization. You plan to set
- TTL cannot be enabled with indexing mode None
TTL requires indexing, so a container with indexing mode None cannot enable TTL, and a TTL-enabled container cannot switch its indexing mode to None. A key-value design that also needs expiration must retain Consistent indexing mode. This compatibility check belongs in the container's lifecycle configuration.
Trap Choosing indexing mode None for a point-read-only container that also requires TTL, which combines incompatible settings.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named events that has DefaultTimeToLive set to 604800. Before a one-time import of 50 million items, an engineer plans to set the container's indexing m
- A key-value cache container in Azure Cosmos DB for NoSQL is accessed only with point reads, so its designer set the indexing mode to none. A new requirement says cache items must expire automatically
- If-Match uses the previously read ETag to prevent a lost update or delete
Every item has a server-generated _etag that changes when the item changes. Supply the previously read ETag as If-Match, such as ItemRequestOptions.IfMatchEtag in .NET, to make a replace or delete conditional on that version still being current. This checks concurrency without requiring an application-wide lock.
Trap Using the session token as the write's If-Match value, which confuses read-session progress with an item's version identifier.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named contracts. In App1, a .NET app, an approver opens a contract by using ReadItemAsync, reviews it for several minutes, and then deletes it. Other us
- You have a support application that uses an Azure Cosmos DB for NoSQL container named tickets. Two agents can open the same ticket, edit it, and save it with ReplaceItemAsync. Sometimes, the second sa
- HTTP 412 requires reconciling with the latest item before retrying
A stale If-Match ETag causes HTTP 412 Precondition Failed, so the rejected write has not overwritten the newer version. Refetch the current item, reapply the intended change under the business rules, and retry with its current ETag. Repeating the same stale conditional request does not resolve the conflict.
Trap Applying an HTTP 429-style blind backoff loop to an unchanged HTTP 412 request, which leaves its stale ETag unchanged.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders. App1 replaces orders by using If-Match with the ETag from an earlier read. Under load, some replaces return HTTP 412, and App1 wraps the c
- You have an Azure Cosmos DB for NoSQL container named stock. App1 decrements an item's quantity only if enough stock remains, and it writes by using If-Match with the ETag from its read. When a write
- You have an Azure Cosmos DB for NoSQL container named carts that stores shopping carts for a retail site. App1 reads a cart, applies a change requested by the shopper, and then calls ReplaceItemAsync
- Stored procedures implicitly check ETags for the items they write
The database implicitly checks ETags for written items touched by a stored procedure. If it detects a conflict, the whole stored-procedure transaction rolls back and reports an error. The application must reapply and retry the transaction rather than assuming earlier writes committed.
Trap Retrying only the final write after a stored-procedure concurrency conflict, which ignores rollback of the entire transaction.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named accounts. A stored procedure reads three items in one logical partition and replaces all three. While it runs, another client updates the second i
- You have an Azure Cosmos DB for NoSQL container named payroll. App1 executes a stored procedure that writes a batch of salary items for one department. Occasionally, the procedure fails with a concurr
- HTTP 449 is retryable write contention rather than a stale-ETag failure
HTTP 449 is a transient write-only error that SDKs retry with incremental backoff. Persistent high concurrency against the same item can make it frequent, so application retries should avoid synchronization, for example through randomized backoff. Unlike HTTP 412, it is safe to retry without treating it as a rejected stale-version condition.
Trap Treating HTTP 449 as an insert identity conflict requiring a new id, which confuses transient contention with HTTP 409.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container used by App1. App1 logs four write failures that the SDK returned: a 409 from a create, a 412 from a conditional replace, a 413 from a large upsert, and
- You have an Azure Cosmos DB for NoSQL container named inventory that serves an online store. During flash sales, diagnostic logs show HTTP 449 Retry With responses on writes to a small number of popul
- If-None-Match validates whether a cached item version is unchanged
When an application already has an item version and needs to validate its cache, supply that version's ETag through ItemRequestOptions.IfNoneMatchEtag on ReadItemAsync. A matching item ETag returns HTTP 304 Not Modified; a different ETag returns the existing item with HTTP 200. This condition compares one item's version, not a change-feed checkpoint.
Trap Using IfMatchEtag for read-cache validation, because that condition protects version-dependent mutations rather than requesting an unchanged-item 304 response.
Design and implement data models and partitioning strategies
Read full chapterCheat sheet
Sharp facts the exam loves — scan these before test day.
- Document boundaries should follow business read and write patterns
Design a NoSQL item around the data the application reads, writes, and processes together rather than copying a relational table layout unchanged. A self-contained business entity can be retrieved and updated with fewer requests. Schema flexibility does not remove the need to model access patterns and expected growth.
Trap Copying every relational table into a separate container without reviewing access patterns, which preserves relational reconstruction work the NoSQL query engine does not perform.
2 questions test this
- You have a container named container1 in an Azure Cosmos DB for NoSQL account. You are porting a relational schema that has a Products table and a ProductSizes table. Every product query in App1 retur
- You are migrating App1 from a relational database to an Azure Cosmos DB for NoSQL account named account1. The source schema stores customers, customer addresses, and customer phone numbers in three no
- Related entity types can share a container and partition key
When a parent and its separately stored children are commonly accessed together, store both item types in one container with the same parent-based partition-key value. Add a type discriminator so parent-only queries can select the required items. A separate container per entity type is not mandatory in a schema-agnostic database.
Trap Creating one container per related entity type merely to represent different JSON shapes, which loses the intended shared-container access pattern.
3 questions test this
- You are designing a container named posts in an Azure Cosmos DB for NoSQL account for a blogging application named App1. The container will store posts, comments on posts, and likes on posts. App1 mus
- You are designing an Azure Cosmos DB for NoSQL data model for a shopping application named App1. When a customer checks out, App1 must update the customer's cart item and create an order item in one a
- You have an Azure Cosmos DB for NoSQL container named container1 that uses /customerId as the partition key. Container1 stores customer profiles and customer orders in the same logical partitions. App
- Frequently replaced attributes can be separated from large static data
When a small set of frequently updated attributes and a large static entity are read and written independently, consider storing them as separate items. Full replacements then rewrite the smaller mutable item rather than the combined payload. Patch can reduce update payload, but it does not by itself make independently accessed data one natural read unit.
Trap Embedding a large rarely read static object in every frequently replaced status item, which increases the size of the write unit without serving the access pattern.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container in which each vehicle item holds an 800-KB specification and a 1-KB status object. A dashboard reads only the status, 2,000 times per second, and App1 r
- You are designing an Azure Cosmos DB for NoSQL data model for a fleet-tracking application named App1. Each vehicle has a 400-KB specification document that rarely changes and a 1-KB status object wit
- Numbers beyond safe double-precision boundaries should be stored as strings
Azure Cosmos DB stores JSON numbers using IEEE 754 double-precision semantics. Convert identifiers or numeric values that might exceed safe interoperable precision to strings before storage. This is especially important for partition-key fields because their values cannot later be corrected in place.
Trap Storing an arbitrarily large exact numeric identifier as a JSON number, which can lose precision across JSON implementations.
2 questions test this
- You are designing an Azure Cosmos DB for NoSQL container named container1 for App1. Each item includes an accountNumber property that will be used as the partition key. Account numbers are 25-digit in
- You have an Azure Cosmos DB for NoSQL account named account1. You plan to create a container named devices that uses /serialNumber as the partition key. Serial numbers are 20-digit integers that some
- A NoSQL item's UTF-8 JSON representation must fit within 2 MB
A NoSQL item's maximum size is 2 MB measured as the UTF-8 length of its JSON representation. Model growing entities so the complete document remains within that limit, including embedded arrays and objects. Splitting a large entity into related items changes both retrieval work and transaction placement requirements.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1. App1 writes an audit item that embeds the full change history of each customer record. After several months, some writes fail with HTT
- You have an Azure Cosmos DB for NoSQL container named container1 that stores product items for App1. Product managers plan to add high-resolution images, encoded as base64 strings, directly to each pr
- You are designing an Azure Cosmos DB for NoSQL data model for a document-management application named App1. Each item contains extracted text in several languages, and some of the text uses multibyte
- Date-time text and numeric Unix timestamps require deliberate representation choices
Azure Cosmos DB for NoSQL stores dates using JSON primitives rather than a native DateTime type. UTC ISO 8601 strings are the recommended representation for sortable date-time text, while Unix timestamps can represent elapsed seconds as numbers. Keep query arguments and conversions aligned with the chosen representation instead of treating strings and numeric timestamps as interchangeable.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1. App1 records a lastSync value returned by the GetCurrentTimestamp function, and a query must return items whose system-generated _ts p
- You have an Azure Cosmos DB for NoSQL container named telemetry. Each item stores an eventTime property as a Unix timestamp in seconds, which matches the system _ts property. The following query retur
- You are designing an Azure Cosmos DB for NoSQL container named orders for App1. Each order item stores an orderDate value. App1 runs range queries, such as all orders placed between two dates, and sor
- Append-only event items preserve mutation history for later projection
When historical mutations must remain available, model each mutation as a new event item rather than overwriting the same current-state item. Change-feed consumers can project those events into current-state materialized views. The retained event items supply the history; ordinary replacement of a current-state item does not create that event archive automatically.
Trap Overwriting one entity item and treating its latest-version change feed as an immutable event log, which can omit intermediate states and does not retain a separate item per mutation.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named accounts. App1 updates each account item in place, and an Azure Functions app reads the change feed in latest version mode to build an audit trail
- You are designing an event-sourced order system named App1 that uses Azure Cosmos DB for NoSQL. App1 appends an event item, such as OrderCreated or ItemShipped, to a container named events for every c
- Snapshots plus deltas reduce repeated full-version storage at the cost of reconstruction work
Use periodic full snapshots with incremental deltas when historical states are needed but storing every complete version is expensive. Reconstruct a requested historical state from the nearest preceding snapshot and the later deltas through the target time. This trades smaller frequent writes and lower version storage for replay work during historical reads.
- Maintaining frequently read aggregates on writes trades write work for cheaper reads
When an application repeatedly reads a parent's child count or a similar aggregate, store the calculated value and maintain it when the contributing items change. This shifts computation to the write path so common reads need not recalculate the aggregate. If the source items and aggregate item share one container and the same complete partition-key value, update them in one transaction to keep the stored summary consistent with the source change.
Trap Embedding every child in the parent just to display a count when the child collection is unbounded, because the parent then grows with the entire collection instead of retaining a bounded summary.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named library that is partitioned by /authorId. Each author item stores a countOfBooks property, and each book is stored as a separate item with the sam
- You are designing a container named posts in an Azure Cosmos DB for NoSQL account. The container is partitioned by /postId and stores post items and comment items that are distinguished by a type prop
- Embed bounded one-to-few data that is commonly read together
When related data is contained, bounded, and commonly queried together, embed it in the parent item. This makes the combined entity available through one read and is particularly suitable for infrequently changing one-to-few relationships. Relationship cardinality and growth matter more than a blanket rule to normalize everything.
Trap Referencing a few stable contact details that every person read requires, which adds round trips without avoiding meaningful growth or update cost.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named products. Each product has a list of technical specifications, typically 10 to 20 name-value pairs, that are set when the product is created and a
- You are designing an Azure Cosmos DB for NoSQL data model for a human resources application named App1. Each employee has up to three email addresses and up to two phone numbers, and these contact det
- Unbounded child collections should be modeled as separate referenced items
When a parent's related collection can grow without a practical bound, store children separately and reference the parent. An ever-growing embedded array makes the parent increasingly expensive to transmit and eventually threatens the item-size limit. One-to-many relationships therefore require an explicit growth assessment rather than automatic embedding.
Trap Embedding every historical comment inside a popular post, which creates an unbounded mutable parent item.
2 questions test this
- You are designing an Azure Cosmos DB for NoSQL data model for a support portal named App1. Each support ticket can receive any number of status updates over its lifetime, and some tickets remain open
- You have an Azure Cosmos DB for NoSQL container named posts. Each post item embeds every comment ever written on that post. Popular posts now receive thousands of comments, the writes that add a comme
When many items share a frequently changing entity, reference one authoritative item rather than embedding a mutable copy in every consumer. Updating that authoritative item avoids rewriting every duplicate. The trade-off is extra application reads to assemble the full result.
Trap Embedding a changing stock quote in every portfolio holding it, which multiplies updates across all copies.
3 questions test this
- You are designing an Azure Cosmos DB for NoSQL data model for a trading application named App1. Thousands of user portfolio items hold the same stocks, and each stock's price changes hundreds of times
- You are designing an Azure Cosmos DB for NoSQL data model for a retail application named App1. A promotion object, including its discount and banner text, applies to 20,000 product items and changes s
- You have an Azure Cosmos DB for NoSQL container in which 10,000 dashboard items each embed a copy of a shared systemStatus object. A monitoring job changes the status every 30 seconds. Each status cha
- Place a parent reference on each child to avoid an unbounded parent reference array
Even an array of identifiers can grow without bound. When one publisher can have indefinitely many books, store the publisher identifier on each book rather than a growing list of all book identifiers on the publisher. This keeps the parent stable while allowing more child items to be added.
Trap Replacing embedded child objects with an unlimited array of child ids in the same parent, which preserves the unbounded-parent problem.
3 questions test this
- You are designing an Azure Cosmos DB for NoSQL data model for App1, a publishing platform. Publishers release an unbounded number of books, and publishers and books are stored as separate items. Addin
- You have an Azure Cosmos DB for NoSQL container named books that is partitioned by /id. Each book item stores a publisherId property that references a publisher item, and publisher items contain no li
- You have an Azure Cosmos DB for NoSQL container that stores category items and product items. Each category item holds a productIds array, and categories gain products without limit. A product belongs
- A hybrid model can embed a bounded recent subset while referencing the full collection
When most reads need only a few recent children, keep a bounded recent subset in the parent and store the complete child collection separately. The common read remains self-contained without allowing the embedded array to grow forever. The application must maintain any deliberately duplicated values consistently with its requirements.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named posts that is partitioned by /postId. Each post item embeds its five most recent comments, and every comment is also stored as a separate item in
- You are designing an Azure Cosmos DB for NoSQL data model for a blog application named App1. Posts can receive an unlimited number of comments. The post page loads the post and its three most recent c
- Document references do not create foreign-key constraints
A property containing another item's identifier is a relationship convention, not a database-enforced foreign key. Application code or suitable same-partition server-side logic must validate existence when that integrity rule is required. Creating a referenced item does not automatically establish cascading updates or deletes.
Trap Relying on a parentId property to reject orphan children automatically, which adds no foreign-key enforcement.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders that is partitioned by /customerId and stores both order items and customer items. Each order item has a customerRef property that holds th
- You have an Azure Cosmos DB for NoSQL container named tasks that stores project items and task items. Each task item contains a projectId property that holds the id of its project item. A tester creat
- Many-to-many models should match both relationship access directions
For many-to-many relationships, evaluate bounded reference arrays or duplicated read-optimized projections that match the required lookup directions. For example, authors can reference their books while books reference their authors when those collections remain bounded. This makes the related identifiers available directly from the entity being read.
Trap Copying a relational join table into relationship-only documents by default, which adds intermediary lookups even when bounded direct references satisfy both access patterns.
4 questions test this
- You have an Azure Cosmos DB for NoSQL container that stores course items and student items for App1. A course has at most 40 students, and a student takes at most eight courses. The roster page must s
- You are designing an Azure Cosmos DB for NoSQL data model for App1, which stores authors and books as separate items. A book has at most 10 authors, and an author has at most 60 books. Authors and boo
- You are migrating a relational Students, Courses, and Enrollments schema to Azure Cosmos DB for NoSQL. A student enrolls in at most eight courses, and a course has at most 40 students. The enrollment
- You are designing an Azure Cosmos DB for NoSQL data model in which products and tags have a many-to-many relationship. A product has at most 10 tags, but one tag can apply to millions of products. The
- A hybrid reference can duplicate stable display fields while retaining an authoritative item
When common reads always display a related entity's relatively stable name or thumbnail, duplicate those selected fields alongside its reference. Keep the complete authoritative entity separate for other reads and updates. This reduces common-read round trips at the cost of refreshing the duplicated fields when they change.
Trap Keeping only the related id when every list read needs its stable display fields and extra lookups must be minimized, which forces additional reads to assemble each display result.
3 questions test this
- You are designing a book catalog in Azure Cosmos DB for NoSQL. To avoid extra reads on list pages, each book item will store its authors' id, name, and thumbnail URL, while the full author items stay
- You have an Azure Cosmos DB for NoSQL container named products. Each product item stores the id of its brand, and a brands container holds the name, logo URL, and long marketing content for each brand
- You have an Azure Cosmos DB for NoSQL container that stores book items and author items. Each author item includes a 300-KB biography. The book list page shows each author's name and photo URL next to
- A good partition key balances actual storage and RU demand as well as cardinality
Choose a key with many possible values that distributes both storage and request activity across those values. High cardinality alone is insufficient if most traffic still targets one value. Review the busiest tenants or entities and their data growth rather than considering only the total count of distinct values.
Trap Approving a high-cardinality key solely from its distinct-value count, which can hide a single overwhelmingly busy value.
2 questions test this
- You are reviewing a proposed partition key of /tenantId for a container that will hold data for 5,000 tenants. The design document lists only the number of distinct tenantId values as evidence that th
- You are evaluating /customerId as the partition key for a container named orders that has 2 million distinct customers. Analysis shows that one marketplace customer generates 60 percent of all writes,
- A read-heavy partition key should align with frequent equality filters
For a read-heavy container, choose a high-cardinality key that commonly appears as an equality predicate in the workload's WHERE clauses. This lets the service route requests to the relevant partitions. A key that distributes writes well but is absent from normal filters can be a poor fit for the read pattern.
Trap Choosing a random GUID that no normal query knows merely for even writes, which does not align with the dominant read pattern.
2 questions test this
- You are designing a container named readings for App1. App1 runs about 50,000 queries per second, almost all filtering on sensorId with an equality predicate, and about 500 writes per second spread ac
- You have a read-heavy Azure Cosmos DB for NoSQL container that stores 300 GB of user profile data and has 40,000 RU/s provisioned. Most requests are queries that use an equality filter on userId, such
- Partition-key definitions and existing item key values cannot be changed in place
A container's partition-key definition is fixed at creation, so changing it requires a new container and data movement. An existing item's partition-key value is also immutable: moving the item requires a create with the new value and deletion of the original. Those operations cannot form one atomic cross-partition transaction.
Trap Replacing an item with a new partition-key value to move it atomically, which cannot change its partition address in place.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named profiles that is partitioned by /region. Profiles are read by region in regional reports. A user moves from the EU region to the US region, and Ap
- You have an Azure Cosmos DB for NoSQL container named orders that has been partitioned by /orderDate for two years and now has hot partitions. You decide that /customerId is a better partition key for
- Using id as the partition key favors independent point reads and writes
Using /id as the partition key gives each uniquely identified item its own logical partition and makes its full point-read address easy to derive. This suits independent item reads and writes, but queries on other properties do not share a useful grouping key. Multi-item transactional operations also cannot group distinct ids when each id is its partition value.
Trap Using /id for an order aggregate that requires atomic writes across different line-item ids, which puts those items in different logical partitions.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named profiles that is partitioned by /id and has 60 physical partitions. App1 point-reads profiles by id, which works well. A new feature must find a p
- You are designing an Azure Cosmos DB for NoSQL container for a session-state store named App1. App1 writes and reads each session item by its id at about 100,000 operations per second at peak. It neve
- A date-only key can concentrate current ingestion into one hot value
A write-heavy stream partitioned only by the current date directs concurrent writes for that date to one logical partition. Similarly, low-cardinality status or country keys provide only a few buckets and can concentrate demand. Choose additional distinguishing values when expected per-value traffic or storage approaches logical-partition limits.
Trap Selecting the current day as the sole key because dates increase over time, which does not distribute writes arriving on the same day.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named tickets that is partitioned by /status, which has four possible values. The container stores 70 GB of data and has 40,000 RU/s provisioned, and mo
- You are designing a container for an order-ingestion service named App1 that writes 30,000 orders per second, almost all for the current day. A developer proposes /orderDate as the partition key, argu
- Partition-key value length is a byte limit rather than a character count
A partition-key value supports up to 2,048 bytes when large partition keys are enabled, or 101 bytes without that capability. Validate derived keys using their encoded byte length, particularly when concatenating fields. Multibyte text can consume more bytes than its visible character count.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container that was created without support for large partition keys and holds 2 TB of data. You plan to switch to a synthetic partition key whose UTF-8 values rea
- You are writing a validation step for App1 that rejects synthetic partition key values that Azure Cosmos DB won't accept. The keys concatenate customer names that can contain multibyte characters, and
- You are designing a container whose partition key concatenates a customer name and a product name. A validation script measures each key with a string length function and reports a maximum of 1,900 ch
- A full logical partition is limited to 20 GB and 10,000 RU/s
A full logical partition groups items with the same complete partition-key value and has a standard 20-GB storage limit. Its throughput cannot exceed 10,000 RU/s because it resides on one physical partition. Increasing total container capacity does not remove these per-value constraints.
Trap Increasing overall container RU/s to let one unchanged full key consume more than 10,000 RU/s, which cannot bypass its partition boundary.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named devices that is partitioned by /deviceId. Each device writes about 2 GB of telemetry per month, and the items are retained indefinitely. An Azure
- You have an Azure Cosmos DB for NoSQL container named container1 that has 50,000 RU/s of provisioned throughput and is partitioned by /storeId. During sales events, requests for a single storeId value
- Physical partitions provide up to 50 GB and 10,000 RU/s each
Azure Cosmos DB manages physical partitions, each of which can host multiple logical partitions. A physical partition supports up to 50 GB of storage and 10,000 RU/s, so total storage and provisioned throughput both influence how many are required. Logical partitions sharing a physical partition also share that partition's available throughput.
Trap Assuming each logical partition receives the full container allocation, which ignores its co-resident logical partitions and physical capacity.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container that has 18,000 RU/s of provisioned throughput spread across three physical partitions. One physical partition hosts the three largest logical partition
- You plan to load 400 GB of data into a new Azure Cosmos DB for NoSQL container that has 20,000 RU/s of provisioned throughput. The data uses a high-cardinality partition key that distributes storage a
- A physical partition split never divides one full logical partition
As storage or throughput grows, Azure Cosmos DB can split physical partitions without making the container unavailable. It remaps complete logical partitions to the resulting physical partitions. A single hot full key stays together, so forcing more physical partitions does not distribute that key's traffic.
Trap Splitting a physical partition to divide one hot logical key across both children, which preserves that key on one child.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container that is partitioned by /deviceId. One device's logical partition needs 14,000 RU/s during calibration runs and is rate limited. An operator plans to rai
- You have an Azure Cosmos DB for NoSQL container that stores 45 GB of data in one physical partition and uses a partition key with thousands of evenly used values. You expect the data to grow to 120 GB
- You have an Azure Cosmos DB for NoSQL container that is partitioned by /storeId. After provisioned throughput was raised, physical partition P1, which hosted the logical partitions for stores S1 and S
- Azure Cosmos DB distributes logical keys by their hashes rather than by visible value order
Azure Cosmos DB hashes partition-key values and distributes the hash space across physical partitions. Similar-looking or adjacent values therefore do not imply adjacent storage placement. There is no fixed container-wide limit on the number of distinct logical partition keys, allowing growth through additional well-distributed values.
Trap Predicting physical placement from alphabetically adjacent tenant names, which ignores hash-based distribution.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container partitioned by /tenantName. A capacity planner assumes that tenants named contoso1 through contoso9 will be stored on the same physical partition, since
- You are designing an Azure Cosmos DB for NoSQL container for App1 that will be partitioned by /userId. App1 expects 50 million users within two years, and each user stores less than 5 MB of data. An a
- Hierarchical prefixes can exceed logical-partition limits while complete keys remain bounded
Hierarchical partition keys support up to three levels and let a prefix such as a tenant span multiple full logical partitions. That prefix can therefore exceed 20 GB and 10,000 RU/s. The complete combination of all configured key components still defines one logical partition and retains its limits.
Trap Assuming HPK removes the storage limit from each complete tenant-user-session combination, which remains one logical partition.
2 questions test this
- You plan to migrate a container that is partitioned by /tenantId to a new container that uses the hierarchical partition key /tenantId, /userId. Writes for several large tenants currently fail after t
- You have an Azure Cosmos DB for NoSQL container named sessions that uses the hierarchical partition key /tenantId, /userId, /sessionId. Tenant1 is expected to store 400 GB of data. One user in Tenant1
- Hierarchical key order should match the leading filters in common queries
Put the most useful common query prefix first in a hierarchical partition key. For a TenantId, UserId, SessionId hierarchy, a TenantId filter or TenantId plus UserId filter targets the relevant subset of physical partitions. Filtering only UserId or SessionId omits the leading prefix and requires full cross-partition routing.
Trap Putting cityId first when most queries know only customerId, which leaves the dominant queries without a leading key prefix.
2 questions test this
- You are designing an Azure Cosmos DB for NoSQL container for App1. Most queries filter on customerId, some also filter on cityId, and no query filters on cityId alone. You plan to use a two-level hier
- You have an Azure Cosmos DB for NoSQL container that uses the hierarchical partition key /tenantId, /userId, /sessionId. The container has 200 physical partitions. A reporting query filters only on a
- A hierarchical key definition uses ordered paths with MultiHash and version two
Define an HPK container with an ordered paths array, kind MultiHash, and version 2. The array order defines the hierarchy rather than combining values into one concatenated string. In Python, PartitionKey can take a list of paths with kind='MultiHash'; in .NET, ContainerProperties accepts partitionKeyPaths.
Trap Defining several unordered Hash paths and expecting hierarchical prefix behavior, which needs the ordered MultiHash definition.
2 questions test this
- You are writing an Azure Resource Manager template that creates an Azure Cosmos DB for NoSQL container named container1. The container must use a hierarchical partition key with tenantId as the first
- You are developing a .NET application named App1 that uses the Azure Cosmos DB .NET SDK v3. App1 must create a container named orders with a hierarchical partition key of /customerId followed by /orde
- A point read on an HPK container requires every key component
To point-read an item from an HPK container, provide its id and all configured key components in hierarchy order. In .NET, build the complete PartitionKey with PartitionKeyBuilder; in Python, provide the ordered component values. A prefix is sufficient for a targeted query, not for uniquely addressing a point read.
Trap Supplying only TenantId to point-read an item in a three-level hierarchy, which is a prefix rather than its full partition address.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named sessions that uses the hierarchical partition key /tenantId, /userId, /sessionId. App2 receives messages that contain only an item id and its tena
- You have an Azure Cosmos DB for NoSQL container that uses the hierarchical partition key /TenantId, /UserId, /SessionId. App1 uses the .NET SDK v3 and must perform a point read of an item. App1 knows
- Low first-level cardinality can limit early HPK ingestion parallelism
Hierarchical partitioning tries to colocate a first-level key's data until storage growth causes splits. A small number of first-level values can therefore constrain initial ingestion to a small number of physical partitions even when lower levels have many values. For write-heavy ingestion, choose high-cardinality leading values or assess a synthetic-key alternative rather than assuming lower-level cardinality immediately provides parallelism.
Trap Relying on millions of second-level user ids to guarantee immediate ingestion distribution for one small first-level tenant, which can remain colocated before storage-driven splits.
2 questions test this
- You have a multitenant application named App1 that writes IoT events to Azure Cosmos DB for NoSQL. App1 serves eight tenants, and ingestion must sustain a high write rate from the first day. Queries a
- You are designing an Azure Cosmos DB for NoSQL container for a telemetry platform named App1. App1 has five enterprise tenants, each with millions of devices, and must load 2 TB of historical data for
- An item identifier at the final HPK level can subdivide a growing lower-level group
If TenantId and UserId together may exceed one logical partition's storage budget, add a high-cardinality final component such as the item id. This allows the tenant-user prefix to span more full keys. The extra subdivision changes which items can participate in one transaction, so retain shared full keys wherever atomic multi-item work is required.
Trap Adding a unique item id as the last key component while assuming different item ids remain one transaction group, which separates their complete keys.
3 questions test this
- You are designing a container that will use a hierarchical partition key that starts with /tenantId, /userId. Some users will accumulate data without any upper bound, and each user's data must be able
- You plan to create an Azure Cosmos DB for NoSQL container that uses the hierarchical partition key /tenantId, /userId, /id. App1 uses transactional batches to update a user's profile item and settings
- You plan a container with the hierarchical partition key /tenantId, /userId for App1. Every user stays well below 20 GB of data. App1 must update a user's profile item and settings item in one transac
- .NET clients require SDK version 3.33.0 or later for HPK operations
Azure Cosmos DB .NET SDK support for hierarchical partition keys requires version 3.33.0 or later. The supporting SDK is required for CRUD and query operations as well as container creation, so verify the application's data clients before directing them to an HPK container.
Trap Upgrading only the container-provisioning application while retaining unsupported data clients, which leaves ordinary CRUD and query access without the required HPK SDK support.
2 questions test this
- Your company has two .NET applications that use Azure Cosmos DB .NET SDK v3 version 3.30.0. Tool1 creates containers, and App1 performs create, read, update, delete, and query operations on items. You
- You have a .NET application named App1 that uses Azure Cosmos DB .NET SDK v3 version 3.32.1. App1 must start reading and writing items in an existing container that another team created with a hierarc
Use a partition-key-per-tenant container when each tenant fits within a full logical partition and the service can share throughput among tenants without guaranteed per-tenant reservations. This is cost-efficient for many small tenants and keeps one container's capacity configuration to manage. A tenant key is a data-placement choice, not a reserved capacity allocation for that tenant.
Trap Promising each tenant a fixed RU/s reservation merely because it has a distinct TenantId value, which does not reserve a share of the shared container.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named tenants that is partitioned by /tenantId and has 40,000 RU/s of provisioned throughput. The container stores data for 400 tenants. A sales manager
- You are designing a B2C SaaS application named App1 that will store data for 20,000 small tenants in Azure Cosmos DB for NoSQL. Each tenant stores less than 1 GB, most operations are scoped to one ten
- A few disproportionately demanding tenants can be isolated while smaller tenants remain pooled
When a few tenants consistently require much greater capacity or independent account-level configuration, evaluate separate accounts for those tenants while retaining smaller tenants in a shared container. This hybrid model targets the exceptional workload without multiplying resources for every small tenant. Additional key levels alone do not provide independent account settings or a dedicated tenant resource boundary.
Trap Adding a lower HPK level to provide a large tenant an independent default consistency setting, which remains an account-level choice.
2 questions test this
- You have a multitenant application named App1 that stores data for 3,000 tenants in one Azure Cosmos DB for NoSQL container partitioned by /tenantId. Two enterprise tenants consistently consume far mo
- You have an Azure Cosmos DB for NoSQL account that stores data for 500 tenants in one container partitioned by /tenantId. One large tenant requires its data to be replicated to a second Azure region,
- A synthetic key materializes several values into one partition-key property
When no existing property offers the required grouping and distribution, construct a synthetic partition-key property in application code. Concatenating a device identifier with a date creates a per-device-per-date bucket and lets a request knowing both values derive its address. The service does not concatenate arbitrary document fields merely because the application queries them together.
Trap Configuring a synthetic key path without populating its combined property on new items, which leaves the intended derived address absent.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container that uses /partitionKey as its partition key. App1 sets each item's partitionKey by using the following code. item.partitionKey = item.deviceId + "-" +
- You have an Azure Cosmos DB for NoSQL container named shipments that uses /pk as the partition key. Each shipment item has a carrierId property and a shipDate property in the yyyy-MM-dd format. App1 m
- You plan to create an Azure Cosmos DB for NoSQL container named meters for App1. Each item has meterId and readingDay properties. One meter can produce 30 GB of data over its lifetime, and partitionin
- A random suffix spreads writes but makes exact read routing harder
Append a random suffix when a low-cardinality base value would otherwise concentrate writes and write parallelism is the priority. The suffix creates more full key values. A reader that knows only the base value cannot reconstruct the original random suffix, so it needs a stored address or additional lookup work.
Trap Choosing a random suffix while requiring a reader to derive the complete key from the base value alone, which discards information needed for direct routing.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named orders that is partitioned by orderDate with a random suffix from 1 to 400 appended, such as 2026-10-27.153. Write throughput meets requirements.
- You have an Azure Cosmos DB for NoSQL container named container1. Writes use a partition key that consists of a date and a random suffix from 1 to 100. A second application named App2 receives item ID
- A calculated suffix combines write distribution with reproducible read routing
When the reader knows a stable property such as a vehicle identifier, calculate a suffix from that property and append it to the base key. A deterministic hash-based suffix spreads writes while allowing the application to recompute the same key later. This is preferable to a random suffix when exact lookup routing must be derivable.
Trap Using a fresh random suffix on the read path, which is unlikely to reproduce the address chosen during the write.
3 questions test this
- You have an Azure Cosmos DB for NoSQL container named container1 that uses a partition key made of a date and a suffix from 1 to 400. On the write path, App1 sets the suffix to a random number. Point
- You are designing a container named trips that will receive about 20,000 writes per second, all for the current date. App1 must read all trips for a given VIN on a given date by using a single-partiti
- You have an Azure Cosmos DB for NoSQL container named trips whose partition key value is the trip date followed by a suffix from 1 to 400 that writers calculate from a hash of each trip's VIN. App1 ru
- A concatenated synthetic key does not supply hierarchical prefix routing
A synthetic value such as tenantId-userId is one ordinary partition-key value. A query knowing only tenantId cannot use it as a native HPK prefix; it must know complete derived values or perform broader routing. Choose HPK when leading-component queries are a key requirement and its distribution trade-offs fit the workload.
Trap Expecting a string prefix filter on a concatenated key to behave like an HPK tenant prefix, which uses a different partitioning mechanism.
2 questions test this
- You have an Azure Cosmos DB for NoSQL container named sessions that uses the hierarchical partition key /tenantId, /userId. A developer proposes adding a property named tenantUser that stores a concat
- You have an Azure Cosmos DB for NoSQL container named container1 that uses /pk as the partition key. App1 sets pk to a concatenated tenantId-userId value, such as contoso-user42. A new report must ret
- Cost estimation needs operation rates and document sizes rather than transaction counts alone
Describe each data type's document size, population, and rates of reads, writes, updates, deletes, and queries in the Azure Cosmos DB Cost Estimator. A business transaction may contain several database operations, so size throughput from those operations and their individual charges. The estimator can accept rates per second or per month, which must match the units of the input workload.
Trap Entering business transactions per second as point reads when each transaction also performs writes and queries, which underrepresents the workload.
2 questions test this
- You are using the Azure Cosmos DB Cost Estimator to size a container for an ordering application named App1. At peak, App1 processes 200 checkouts per second. Each checkout performs two point reads, o
- You are entering a workload in the Azure Cosmos DB Cost Estimator. Your monitoring data reports that the application performs 26 million writes per month, spread evenly across the month. You want to e
- Mixed document shapes should be represented separately in a workload estimate
The Cost Estimator supports multiple data types with separate sizes, item counts, and operation rates. Import sample JSON or configure each document type instead of treating tiny status items and large entity documents as one uniform shape. This makes comparisons between embedded and referenced designs reflect their actual read and write mix.
Trap Sizing a mixed workload entirely from its smallest sample document, which ignores expensive larger document operations.
2 questions test this
- You are using the Azure Cosmos DB Cost Estimator to compare an embedded data model and a referenced data model for App1. You have sample JSON documents for each design, and you want the estimator's do
- You are estimating costs for a product catalog application named App1 by using the Azure Cosmos DB Cost Estimator. The container holds 2 million 1-KB inventory status items that are updated 500 times
- Peak capacity and total consumed work answer different pricing questions
Provisioned-throughput sizing must accommodate the operation mix at the required per-second peak, whereas serverless estimates depend on consumed RUs over time. A workload's peak and total monthly work can favor different capacity models. Compare both rather than selecting a model from peak requests alone.
Trap Comparing serverless and manual costs using only peak RU/s, which omits the activity duration and total consumed work.
2 questions test this
- You are comparing capacity modes for a reporting API named App1 by using the Azure Cosmos DB Cost Estimator. App1 is busy for about one hour each business day, when it needs up to 3,000 RU/s, and it's
- You are comparing capacity modes for an order-processing API named App2 in the Azure Cosmos DB Cost Estimator. App2 consumes between 1,800 and 2,200 RU/s around the clock, every day, in a single regio
- A complete cost estimate includes storage, regions, and the selected pricing options
Throughput is only one component of workload cost. Include data storage, region count and location, backup choices, and applicable discounts in the estimator's configuration. Compare the resulting itemized breakdown instead of assuming a cheaper operation pattern always produces the lowest total monthly cost.
Trap Comparing database designs only by write RU charge while omitting duplicated storage and region costs, which leaves out material cost components.
2 questions test this
- Your company has an Enterprise Agreement discount and plans to buy a 3-year Reserved Capacity commitment for a new Azure Cosmos DB for NoSQL account. The account will use manual provisioned throughput
- You are comparing two Azure Cosmos DB for NoSQL data models for App1 in the Azure Cosmos DB Cost Estimator. Model A duplicates product data into three containers to cut write RUs, and Model B keeps on
- Background consumers and expected growth belong in capacity estimates
Include change-feed consumers and other background database work alongside foreground application operations. The current estimator has a Change Feed Consumers option and growth projections for storage and compute. A design that fits today's foreground peak can still be undersized after background processing or retained data grows.
Trap Sizing all throughput from API traffic while treating change-feed readers as free, which omits their database requests.
2 questions test this
- You are sizing an Azure Cosmos DB for NoSQL container in the Azure Cosmos DB Cost Estimator. In addition to App1's API traffic, three Azure Functions apps will read the container's change feed to upda
- You prepared an estimate in the Azure Cosmos DB Cost Estimator for a container that stores 200 GB today. You expect storage to grow by 8 percent each month and request volume to grow by 4 percent each
- Cost Estimator projections should be checked against measured requests and current prices
The Azure Cosmos DB Cost Estimator provides a projected monthly cost, not a contractual quote. Its query-complexity presets and operation hints are estimates, so validate representative workload charges before final sizing. Use current regional pricing rather than copying dollar figures from an older illustrative example.
Trap Treating a generic query-complexity preset as the guaranteed charge of every production query, which substitutes an estimate for workload measurement.
3 questions test this
- You are sizing App1 in the Azure Cosmos DB Cost Estimator and select the filter query complexity preset of about 10 RU. In a test environment with representative data, App1's most frequent query, whic
- Your team plans to reuse a cost comparison from an Azure Cosmos DB article written two years ago that lists dollar amounts for serverless and provisioned throughput. App1 will run in a region whose pr
- The Azure Cosmos DB Cost Estimator projects that App1 needs 12,000 RU/s, based on the default query complexity preset and the built-in RU hints. No production traffic has been measured yet. Before you
- An alternate partitioned copy trades extra storage and RU work for another access path
When independent access patterns cannot share one useful partition key, evaluate an additional copy organized by another key. Global secondary indexes are documented as automatically synchronized alternate-key containers with eventual consistency and additional storage and RU costs. Include those costs and the allowed freshness in the data-model decision rather than treating the alternate layout as free.
Trap Adding an alternate-key synchronized container while budgeting only the original container's storage and work, which omits the extra copy.
2 questions test this
- You plan to add a global secondary index to a container named orders so that a support portal can find orders by email address without cross-partition queries. The portal must show an order within sec
- You have an Azure Cosmos DB for NoSQL container named orders that is partitioned by /customerId. A new dashboard must query orders by productId, which currently causes cross-partition queries. You pla
- Vector workload estimates need embedding storage and vector operation inputs
For a vector-enabled workload, enable the Cost Estimator's Vector Operations inputs in addition to ordinary document operations. Include vector dimensions and index type, vector writes and queries per second, and partitions scanned per query. These inputs account for embedding storage and vector-operation work that a CRUD-only estimate omits.
2 questions test this
- You are estimating the cost of adding semantic search to App1 in the Azure Cosmos DB Cost Estimator. App1 will store embeddings for 5 million documents, insert 50 vectors per second, and run 300 simil
- You are estimating costs for a retrieval-augmented generation application named App1 in the Azure Cosmos DB Cost Estimator. App1 stores 1536-dimension embeddings with each document, uses a DiskANN ind
- An integrated-cache estimate includes dedicated gateway compute
When estimating a design that uses the integrated cache, include the dedicated gateway SKU and instance count. The gateway is a separate compute component even when cache hits reduce database RU consumption. A throughput-and-storage-only comparison does not capture that complete design cost.
2 questions test this
- You are modeling an integrated cache design for App1 in the Azure Cosmos DB Cost Estimator. App1 connects through a dedicated gateway, and 90 percent of its point reads, each for a 1-KB item, are expe
- You plan to add the integrated cache to a read-heavy Azure Cosmos DB for NoSQL workload named App1, and you want to compare the total cost with and without it in the Azure Cosmos DB Cost Estimator. Mo
- Storage sizing must include the index as well as document data
Azure Cosmos DB's total consumed storage combines data size and index size. When all properties are indexed, the index can occupy more space than the document data itself. Include both footprints when estimating storage capacity and cost rather than sizing only from the stored JSON payloads.
Implement change feed
Read full chapterCheat sheet
Sharp facts the exam loves — scan these before test day.
- Change-feed ordering is guaranteed within a partition key rather than globally
The change feed provides modification ordering per partition-key value, not a total order across all keys. Changes sharing a modification time within transactional or grouped work may be delivered in any order within that group. A consumer combining different partition ranges must not infer one global event sequence from arrival order.
Trap Using arrival order from independent feed ranges as the global business-event order, which has no cross-key ordering guarantee.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named orderEvents is partitioned by /eventId, which is unique for every event. A change feed consumer must process the events
- You have an Azure Cosmos DB for NoSQL account named account1. An application writes an order header and its line items to a container named orders in one transactional batch for the same partition key
- Latest-version mode exposes the newest item state rather than every mutation
Latest-version mode captures creates and updates, but an item updated several times between reads may appear only in its newest version. Hard deletes are not captured, and a deleted item is no longer available from this mode. Use it for maintaining current state when intermediate mutations and delete events are unnecessary.
Trap Using latest-version mode as a complete mutation audit, which can omit intermediate versions and does not record hard deletes.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A cache service reads a container named products in latest version mode and copies each changed item into a key-value cache. Product manag
- You have an Azure Cosmos DB for NoSQL account named account1. A container named shipments is read by a change feed processor in latest version mode every 30 seconds. An item's status changed from pack
- You have an Azure Cosmos DB for NoSQL account named account1. A container named reservations is read by a change feed processor in latest version mode that polls every five minutes. A customer created
- A soft-delete marker lets a latest-version consumer observe deletion intent
When a latest-version consumer must react to deletion intent, write a marker such as deleted=true before eventual physical deletion. The marker is an update the feed can expose. If TTL later removes the item, ensure the consumer processes the marker before expiration because the deleted item will disappear from the latest-version feed.
Trap Setting a soft-delete marker and immediately deleting the item before the consumer can read it, which removes the state that latest-version mode exposes.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. A container named profiles is synchronized to a search index by a change feed processor in latest version mode.
- You have an Azure Cosmos DB for NoSQL account named account1. To signal deletions to a latest version consumer, code for a container named accounts first patches deleted=true onto an item and then imm
- A patched item appears in the change feed as an item version rather than a patch diff
Change-feed processing returns the changed document even when the write was a partial Patch. A latest-version consumer receives the full resulting item, not just the list of paths or Increment operations sent by the writer. Process that state accordingly rather than reapplying the original update operation.
Trap Applying the original increment again when processing a patched item from the feed, which mistakes resulting state for an unapplied patch command.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A search indexer reads a container named articles in latest version mode and expects complete documents. To reduce payload sizes, the writ
- You have an Azure Cosmos DB for NoSQL account named account1. A writer updates items in a container named products by using partial document update with an Increment operation on /stock. A latest-vers
- Different applications can consume the same container in different change-feed modes
A container's change feed can serve multiple independent applications, including applications selecting different modes. Each individual change-feed application reads in one mode. Adding a consumer does not consume and remove events for the other applications as a competing-message queue would.
Trap Deploying a second independent consumer and expecting it to receive only changes the first consumer has not taken, which treats the feed as a destructive queue.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named orders already has a fulfillment application that reads its change feed. The analytics team plans a second application w
- You have an Azure Cosmos DB for NoSQL account named account1. One .NET worker for a container named assets must backfill a projection from the beginning of the container and must also record every del
- Latest-version mode supports beginning, time, now, and checkpoint starting positions
A latest-version reader can start from the container's beginning, a specified time, now, or a saved checkpoint. This mode has no fixed history-retention window, but it exposes surviving item states rather than an immutable event archive. Time-based starts have approximately five-second precision.
Trap Treating a beginning read as recovery of every original item version, which latest-version retention does not preserve.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. A container named catalog has existed for three years. A new reporting projection must be built from every item
- You have an Azure Cosmos DB for NoSQL account named account1. A latest version pull reader for a container named trades is configured with ChangeFeedStartFrom.Time set to exactly 09:30:00 UTC so that
- The response feed ETag sequences the feed while the item ETag identifies an item version
In latest-version responses, item metadata includes _etag and _ts, with _lsn added for change-feed transaction sequencing. The response's feed ETag serves a different purpose from the item's _etag. Do not substitute an item-version ETag for a feed-position bookmark.
Trap Persisting the last item's _etag as the pull reader's continuation token, which confuses item identity with feed progress.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A Python worker reads a container named orders with query_items_change_feed in latest version mode. After each run it must persist a bookm
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed consumer for a container named tickets updates each received ticket with an escalation flag. Another service can modify
- Latest-version mode does not provide an operation-type filter
Latest-version mode does not directly filter the feed to a specific mutation type. If a workflow needs to distinguish business changes, add a suitable marker to items and inspect it while processing. For native create, replace, and delete metadata, evaluate all versions and deletes mode instead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named orders is read by a latest version change feed processor. A notification function must react only when an order's status
- You have an Azure Cosmos DB for NoSQL account named account1 that uses continuous backup and is enabled for all versions and deletes mode. A billing consumer for a container named subscriptions must c
- Latest-version change feed is enabled by default for NoSQL accounts
Latest-version change feed is available by default in Azure Cosmos DB for NoSQL. A consumer can use this mode without enrolling the account in the additional feature required for all versions and deletes.
Trap Enabling continuous backup as a prerequisite for a latest-version consumer, because that backup prerequisite belongs to all versions and deletes mode.
- Multi-write change-feed ordering uses crts rather than the local write timestamp
In a multi-region write account, _ts records when an item was written in its local region. The crts value records when the absence of a conflict was confirmed or a conflict was resolved in the hub region, and change-feed ordering follows crts. Treat the two timestamps as different stages of a write's progress rather than using _ts to reconstruct the feed sequence.
- All versions and deletes mode requires continuous backup and account feature enablement
Use all versions and deletes mode when every intermediate create or update and delete must be observed. This preview mode is supported for NoSQL accounts and requires continuous backup plus enablement of the all-versions-and-deletes account feature. Current documentation describes enabling the feature on an existing account rather than during account creation.
Trap Selecting this feed mode on a periodic-backup account without changing prerequisites, which does not have the required continuous change history.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that was created with the continuous 30-day backup tier. A .NET 3.60.0 application calls GetChangeFeedIterator with ChangeFeedMode.AllVersi
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. An auditing service must read every create, every intermediate update, and every delete in a container named ord
- All-versions-and-deletes reads are bounded by continuous-backup retention
All versions and deletes mode can read only changes within the account's continuous-backup retention window. Attempting to resume from changes outside that window returns an error. A consumer outage longer than retention cannot be repaired merely by retaining its old continuation token.
Trap Keeping an old token indefinitely as guaranteed access to every historical mutation, which does not extend the account's retained history.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses the continuous 7-day backup tier. A Python worker reads a container named payments with query_items_change_feed in AllVersionsAnd
- You have an Azure Cosmos DB for NoSQL account named account1 that uses the continuous 7-day backup tier. A compliance consumer reads a container named claims in all versions and deletes mode and store
- All versions and deletes mode starts from now or a retained checkpoint
An all-versions-and-deletes reader starts from now or resumes from a valid previous checkpoint within retention. Starting from the container's beginning or from an arbitrary historical timestamp is not supported. Design initial synchronization separately from ongoing retained-change consumption when those start restrictions matter.
Trap Using ChangeFeedStartFrom.Beginning to backfill all-versions-and-deletes history, which that mode does not support.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with continuous backup and all versions and deletes mode enabled. A Java change feed processor in all versions and deletes mode already pro
- You have an Azure Cosmos DB for NoSQL account named account1 that is enabled for all versions and deletes mode. A brand-new .NET worker with no saved continuation token is assigned one FeedRange, stor
- Delete records identify the removed item but do not include its previous body
All-versions-and-deletes create and replace records contain the current item image plus metadata such as operationType. A delete record carries identifying metadata including id, partitionKey, and previousImageLSN, not the deleted item's previous body. Retain earlier create or replace versions when downstream logic will need the deleted content.
Trap Reading previousImageLSN as if it were the deleted document's body, which is a reference to earlier sequence progress rather than the image itself.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named invoices is read in all versions and deletes mode by an archiving service. When an invoice is deleted, the service must
- You have an Azure Cosmos DB for NoSQL account named account1. An application reads a container named orders, partitioned by /customerId, in all versions and deletes mode. When an order is deleted, the
- You have an Azure Cosmos DB for NoSQL account named account1. A Python worker reads a container named profiles with query_items_change_feed in AllVersionsAndDeletes mode and receives each change as a
- TTL delete events are emitted when expired items are purged
All versions and deletes mode captures TTL deletions and includes timeToLiveExpired metadata to distinguish them. The delete event is not guaranteed immediately at the expiration deadline; it appears when the service purges the item. A lifecycle consumer must allow for that background-deletion delay.
Trap Using the feed's TTL delete event as an exact expiration-time timer, which is delayed until physical purge.
3 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named sessions has a default TTL of 3,600 seconds, and users can also sign out, which deletes their session item. An auditing
- You have an Azure Cosmos DB for NoSQL account named account1. Items in a container named carts expire through TTL, and a cleanup service reads all versions and deletes events to release reserved stock
- You have an Azure Cosmos DB for NoSQL account named account1 that uses provisioned throughput. A container named tokens expires items with TTL, and a security service reads all versions and deletes ev
- All-versions-and-deletes requests use Gateway regardless of the client's configured mode
Requests to read all versions and deletes mode use Gateway mode even if the SDK client is configured for Direct. Account for that route when planning consumer connectivity. Changing the generic client connection mode does not force this feed operation onto the Direct data path.
Trap Assuming a Direct-configured client makes every all-versions-and-deletes read a backend TCP operation, which this feed mode overrides.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET service shares one CosmosClient configured for Direct mode for low-latency point reads and adds an all versions and deletes reader
- You have an Azure Cosmos DB for NoSQL account named account1. One .NET service uses a single CosmosClient created with the SDK's default connection mode for point reads and also reads a container name
- Partition-merge history can make an account ineligible for all versions and deletes
Current all-versions-and-deletes limitations exclude accounts with partition merge enabled and accounts that have ever merged a partition. Disabling the feature after a merge does not erase that historical restriction. Check eligibility before depending on this mode for an audit workflow.
Trap Disabling partition merge after a previous merge and assuming eligibility is restored, which overlooks the account's merge history.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. While the account used periodic backup, an engineer enabled partition merge, merged two fragmented containers, and then disabled the merge
- You have four Azure Cosmos DB for NoSQL accounts that use periodic backup. account1 has partition merge enabled, account2 merged a container last year and then disabled merge, account3 has never enabl
- All versions and deletes requires a supporting SDK and a change-event response type
The documented .NET support for all versions and deletes begins with SDK 3.60.0, while Python support begins with 4.9.1b1. In .NET, process ChangeFeedItem<T> events so the application can inspect Current and Metadata, instead of treating every event as a plain item T. Delete handling must branch on metadata because a current document is not supplied.
Trap Reusing a plain-item deserializer for every delete event, which does not match the event's metadata-oriented shape.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that is enabled for all versions and deletes mode. You are completing this .NET code for a container named orders: FeedIterator<TARGET> it
- You have an Azure Cosmos DB for NoSQL account named account1 that is enabled for all versions and deletes mode. A .NET application that references Microsoft.Azure.Cosmos 3.45.0 reads a container named
- Azure Functions change-feed mode support depends on the programming model
The Azure Functions trigger supports latest-version mode across its programming models and languages. All versions and deletes mode requires the .NET isolated worker model with Microsoft.Azure.Functions.Worker.Extensions.CosmosDB version 4.16.1 or later. Select a consumer whose language and extension support the required feed mode rather than assuming generic trigger support covers every mode.
Trap Selecting a Python Functions trigger for all versions and deletes because Python can consume latest-version changes, which does not satisfy the documented .NET isolated-worker requirement for the other mode.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with continuous backup and all versions and deletes mode enabled. A .NET isolated worker Azure Functions app references Microsoft.Azure.Fun
- You have an Azure Cosmos DB for NoSQL account named account1 with continuous backup and all versions and deletes mode enabled. A team maintains Azure Functions apps written in Python and wants a new C
- The processor manages polling and checkpoints while pull mode leaves those responsibilities to the application
Choose the change feed processor when automatic polling, persisted progress, load balancing, and recovery are desired. The pull model gives the application direct control but requires it to manage those responsibilities. Azure Functions change-feed triggers use the processor underneath rather than constituting a third low-level reading mechanism.
Trap Choosing pull mode to avoid writing checkpoint and load-balancing code, which is functionality the processor supplies.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A team replaced a .NET change feed processor that reads a container named orders with change feed pull model iterators, so that it control
- You have an Azure Cosmos DB for NoSQL account named account1. An architect describes three independent ways to read a container named events: the change feed processor, the pull model, and an Azure Fu
- The change feed processor library is available for .NET and Java rather than Python
The change feed processor is included in the .NET v3 and Java v4 SDK families. Python and Node.js applications use the pull model for direct SDK consumption rather than instantiating this processor library. Select a supported consumption model before porting a processor-based sample to another SDK.
Trap Porting GetChangeFeedProcessorBuilder directly into a Python SDK application, which has no matching processor implementation.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A Python team must port a .NET sample that uses GetChangeFeedProcessorBuilder to read a container named readings. The Python service must
- You have an Azure Cosmos DB for NoSQL account named account1. Four teams plan to consume the change feed of a container named orders: one uses the .NET v3 SDK, one the Java v4 SDK, one the Python SDK,
- A processor is built from the monitored container and must be started
For latest-version mode in .NET, call GetChangeFeedProcessorBuilder on the monitored container with a processor name and delegate. Configure WithInstanceName and WithLeaseContainer, call Build, then StartAsync. All versions and deletes uses GetChangeFeedProcessorBuilderWithAllVersionsAndDeletes instead.
Trap Building the processor from the lease container and expecting it to monitor a different data container, which selects the wrong feed source.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. In a .NET worker service, the constructor calls GetChangeFeedProcessorBuilder<Item>("inventoryProc", HandleAsync) on a container named inv
- You have an Azure Cosmos DB for NoSQL account named account1 with containers named orders and leases. A developer wrote leasesContainer.GetChangeFeedProcessorBuilder<Order>("ordersProc", HandleChanges
- Processor delivery is at least once, so effects should tolerate replay
The processor resumes from persisted lease progress and can deliver a batch again after failure. Make downstream effects idempotent or deduplicate them using a suitable application identity. Automatic checkpointing is not an exactly-once guarantee for effects in another system.
Trap Incrementing an external total unconditionally for every delivered change, which can count a replayed batch twice.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor for a container named payments sends a confirmation email for each changed item. After the delegate threw an unhan
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor delegate for a container named payments adds each payment amount to a daily total in another container. After a ho
- The processing delegate must finish its work before returning successfully
The processor updates lease progress after the delegate successfully completes. Await all required asynchronous work before returning rather than launching untracked background tasks. Otherwise, the checkpoint can advance before effects are durable and a later failure may leave work unprocessed.
Trap Starting fire-and-forget tasks inside the delegate and returning immediately, which permits checkpoint advancement before the tasks finish.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You are reviewing a .NET change feed processor for a container named stock, and you must explain to the team at what point in the processi
- You have an Azure Cosmos DB for NoSQL account named account1. A processor delegate for a container named orders starts Task.Run(() => PublishAsync(change)) for each change and returns immediately to k
- Persisting failed changes separately can prevent an endlessly retried poison batch
An unhandled processor-delegate exception causes the affected range to resume from its last persisted point and retry the batch when saved progress exists. If the first-ever delegate execution fails before progress is saved, retry uses the initial starting configuration and might not include that batch. If a change cannot be processed, durably record it in an error queue or container under a deliberate failure-handling policy. Silently swallowing it loses the opportunity to repair it, while continually throwing can stall that range.
Trap Catching and discarding every failed event just to advance the feed, which records no recoverable failure information.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. One malformed document in a container named invoices makes a processor delegate throw an unhandled exception every time its batch is deliv
- You have an Azure Cosmos DB for NoSQL account named account1. A brand-new change feed processor for a container named orders started with default settings, and its very first delegate execution threw
- Processor start-time options affect initial lease creation rather than later resumes
By default, a newly initialized processor starts from its initialization time rather than replaying old data. For latest-version mode, WithStartTime can choose an earlier time, including DateTime.MinValue.ToUniversalTime() for the beginning. Once lease state exists, changing that option does not override the saved progress.
Trap Changing WithStartTime on a processor with existing leases to force a replay, which resumes from persisted lease state instead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You are deploying a new change feed processor in latest version mode, with a new processor name and an empty lease container, to build a f
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor for a container named sales has run in latest version mode for six months. To reprocess last week's changes, a dev
- Keep a global endpoint when changing a processor's preferred region
Use the account's global endpoint for the client serving a change feed processor and change ApplicationRegion or ApplicationPreferredRegions to redirect regional traffic. Processor lease identity is scoped to the configured endpoint. Replacing the global endpoint with a different regional endpoint can create independent lease documents instead of preserving progress.
Trap Changing the client to a region-specific endpoint to retain the same processor checkpoint, which changes the endpoint-scoped lease identity.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 replicated to West US 2 and East US 2. A .NET change feed processor for a container named orders runs in East US 2 but reads through West U
- You have two Azure Cosmos DB for NoSQL accounts named account1 and account2, each replicated to West US 2 and East US 2. A new .NET change feed processor monitors a container in account1 and stores it
- The Azure Functions trigger supplies change-feed processing without self-managed workers
Choose the Azure Functions change-feed trigger when processor-based scaling and reliable change detection are wanted without maintaining worker infrastructure. Implement the function's processing logic while the hosted trigger supplies the worker integration. This is a hosted consumption choice, not a different change-feed data model.
Trap Choosing a custom pull reader solely to avoid hosting processor workers while still requiring automatic polling and balancing, which leaves those responsibilities with the application.
- WithPollInterval controls the processor's wait after finding no changes
Configure WithPollInterval on the change feed processor builder to set how long it waits before checking again when no changes are available. This tunes idle polling responsiveness and the associated read work. It is separate from the intervals used to acquire or renew leases.
Trap Shortening the lease-acquisition interval to control empty-feed polling, which changes lease distribution checks rather than the processor's no-change wait.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET processor for a container named archive, which receives only a few changes per hour, issues frequent empty change feed reads that c
- You have an Azure Cosmos DB for NoSQL account named account1. A container named alerts is quiet for long periods, and after a quiet spell the first new change takes noticeably longer than expected to
- Processor lifecycle handlers report lease acquisition and release
Register WithLeaseAcquireNotification and WithLeaseReleaseNotification handlers when an application needs to observe a processor host starting or stopping work on a lease. These notifications identify ownership transitions during processor operation. They do not measure the number of unprocessed changes.
Trap Using the change-feed backlog estimator as a lease-transition callback, which reports estimated progress lag rather than acquisition and release events.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. Operators of a change feed processor for a container named shipments want an alert each time a lease moves between hosts during scale-out
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed processor for a container named carts keeps a per-lease in-memory cache on each host. Whenever a host stops processing
- WithErrorNotification exposes processor errors for source-aware handling
Register WithErrorNotification to observe exceptions encountered by the change feed processor host. The handler can distinguish an unhandled user-delegate failure from a failure accessing the monitored container, such as a connectivity error. Use that distinction to investigate the processing code or the source-access path appropriately.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed processor for a container named devices sometimes stops making progress, and nothing appears in the logs because the de
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed processor for a container named invoices registers WithErrorNotification. Operators want errors thrown by the team's ow
- Lease documents persist progress and coordinate ownership for feed ranges
A processor's lease container stores per-range progress and ownership rather than copies of the business documents. Each range advances separately, and the complete set of leases represents processor progress. WithLeaseContainer selects that state store in the .NET builder.
Trap Using the lease container as the destination for the application's materialized business view, which confuses coordination state with processing output.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor for a container named telemetry uses a lease container named leases that was configured with WithLeaseContainer. A
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed processor that runs on three instances reads a container named orders and writes a summary per customer to a container
- A partitioned lease container uses id as its partition key
Create a partitioned lease container with the /id partition-key definition required for lease storage. The lease container may be in the monitored account or a different account. It need not share the business data's partition-key path.
Trap Copying the monitored container's /tenantId partition-key definition to the lease container, which does not meet the lease document layout.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named orders is partitioned by /tenantId. You are manually creating a partitioned lease container for an Azure Functions trigg
- You have two Azure Cosmos DB for NoSQL accounts named account1 and account2. A container named orders in account1 runs near its provisioned RU/s, and the team doesn't want lease maintenance traffic to
Instances in one deployment unit use the same processorName and lease-container configuration, with a unique WithInstanceName value for each instance. That shared identity lets the library distribute leases between them. Independent workflows can instead share the lease container with different processor names, giving each its own progress rather than making their workers cooperate on one checkpoint set.
Trap Giving every scale-out worker a different processorName, which creates independent consumers instead of sharing one processing workload.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET change feed processor for a container named orders must scale out from one virtual machine to three virtual machines. The three ins
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor named fulfillment reads a container named orders and uses a lease container named leases. You are adding an email
- Useful processor parallelism is bounded by the available leases
A lease has only one owner at a time within a deployment unit. Adding workers beyond the lease count does not create more independently assignable ranges. The processor redistributes leases as workers join or leave and creates additional lease work as the monitored container splits.
Trap Adding more worker instances than leases to split one lease among them simultaneously, which violates exclusive lease ownership.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor deployment for a container named iotData runs eight instances, and the container's storage and throughput have dou
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed processor deployment for a container named events has six leases. To speed up processing, operators started ten instances wi
- Both feed reads and lease maintenance need sufficient throughput
Reading the monitored container consumes RUs, and maintaining lease ownership and checkpoints consumes RUs in the lease container. Throttling either resource can delay processing; lease throttling can even stop it. More workers increase potential lease-maintenance demand rather than providing cost-free parallelism.
Trap Increasing worker count to solve a throttled lease container without adding coordination capacity, which can increase its maintenance load.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed deployment of 30 instances reads a container named orders, and its lease container is provisioned at 400 RU/s. The lease con
- You have an Azure Cosmos DB for NoSQL account named account1. You are estimating the cost of adding a change feed processor to a container named catalog, which already has provisioned throughput for i
- A shorter lease-acquisition interval accelerates balancing at additional RU cost
The default lease-acquisition interval is 17 seconds. At each acquisition check, a host queries lease state to assess distribution and possible ownership changes. Reducing the interval makes rebalancing more responsive but increases lease-container query work.
Trap Reducing the feed poll interval to accelerate lease balancing, which controls feed polling rather than ownership-acquisition checks.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. Operators add instances to a change feed processor deployment for a container named orders during sales events. New instances take up to a
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET processor for a container named devices calls WithLeaseConfiguration and lowers acquireInterval from the default of 17 seconds to 5
- Lease renewal writes occur even when there are no new business changes
A host renews owned leases by replacing lease documents, with a default renewal interval of 13 seconds. These writes continue even when the feed has no new data. Reducing the interval increases coordination work and must remain compatible with the lease-expiration interval.
Trap Budgeting zero lease-maintenance RUs during an idle monitored workload, which still requires ownership renewals.
- Lease expiration governs when another host can recover abandoned work
The default lease-expiration interval is 60 seconds. After a host stops renewing a lease, another host can acquire it once expiration and the relevant checking intervals allow. A shorter expiration can improve recovery speed, but it must not be set below the renewal interval.
Trap Setting expiration shorter than normal lease renewal to speed recovery, which lets an actively owned lease expire between renewals.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A processor for a container named orders calls WithLeaseConfiguration with expirationInterval set to 10 seconds and leaves renewInterval a
- You have an Azure Cosmos DB for NoSQL account named account1. When a host in a change feed processor deployment for a container named payments crashes, other hosts take over its leases only after a mi
- Pull mode can read changes for one partition-key value
Choose pull mode when a consumer needs only one customer's partition-key changes rather than the whole container. In .NET, provide FeedRange.FromPartitionKey with the chosen ChangeFeedStartFrom value; Python accepts partition_key on query_items_change_feed. The change feed processor does not offer single-partition-key processing.
Trap Selecting the processor for a report that must consume only one known customer's partition feed, which does not support that scope.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named orders is partitioned by /customerId and holds millions of customers. A .NET report must consume only the changes for th
- You have an Azure Cosmos DB for NoSQL account named account1. A Python service calls container.query_items_change_feed(start_time="Beginning", partition_key="tenant7") on a container named events that
- HTTP 304 means no current changes while an empty HTTP 200 page does not
A change-feed pull iterator represents an ongoing feed, so HasMoreResults remains true. When no new changes are currently available, the service returns HTTP 304 NotModified; the application can wait and poll again or end a bounded catch-up read. An empty HTTP 200 page is not sufficient evidence that the feed is caught up.
Trap Ending a catch-up read at the first empty HTTP 200 page, which can leave subsequent changes unread.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A nightly .NET job catches up on the change feed of a container named sales and exits its loop on the first response that contains zero do
- You have an Azure Cosmos DB for NoSQL account named account1. A developer reviews a pull-model loop for a container named logs that runs while (iterator.HasMoreResults) and expects the loop to end aut
- Pull consumers should persist their continuation only after processing the corresponding changes
Pull mode exposes a continuation token that bookmarks the iterator's progress and must be persisted by the application when restart recovery is required. Persist it after completing the associated processing so restart does not skip unfinished work. A latest-version change-feed token remains valid while its container exists; all-versions-and-deletes history remains subject to retention.
Trap Saving a newly received token before committing the page's processing effects, which can skip those effects after a crash.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. A quarterly pull-model job reads a container named prices in latest version mode and saves its continuation toke
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET pull-model reader for a container named payments calls ReadNextAsync, immediately writes response.ContinuationToken to a blob, and
- Pull-mode parallelism requires distributing FeedRanges explicitly
GetFeedRangesAsync returns ranges corresponding to the container's physical partitions. A pull application can create an iterator per range and distribute them to threads or machines, but it must coordinate that assignment itself. The processor supplies automatic range balancing when that custom control is unnecessary.
Trap Starting multiple whole-container pull readers and assuming they automatically divide the workload, which duplicates reads instead of assigning ranges.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. An orchestrator calls GetFeedRangesAsync on a container named telemetry and must hand each returned range to a different remote machine ov
- You have an Azure Cosmos DB for NoSQL account named account1. Four worker machines each run container.GetChangeFeedIterator<Order>(ChangeFeedStartFrom.Beginning(), ChangeFeedMode.LatestVersion) agains
- Pull continuation tokens and processor leases are not interchangeable checkpoints
A pull continuation token and a processor lease both track progress, but they cannot be converted into one another. Switching consumption models therefore needs a deliberate starting and reconciliation strategy. Copying a token into a lease document is not a supported way to preserve exact progress.
Trap Migrating a pull reader to the processor by inserting its token as lease state, which relies on an unsupported checkpoint conversion.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A team is replacing a .NET pull-model reader for a container named orders with a change feed processor that uses a new lease container. Th
- You have an Azure Cosmos DB for NoSQL account named account1. A pull-model reader for a container named orders is being replaced with a change feed processor. A developer plans to copy the reader's la
- Change-feed PageSizeHint can be exceeded to preserve transaction scope
ChangeFeedRequestOptions.PageSizeHint influences how many changes a pull response should contain. When preserving stored-procedure transaction scope requires returning a larger atomic group, the response can exceed that hint. Do not size a consumer's buffers on the assumption that the hint is an absolute maximum.
Trap Allocating a fixed buffer exactly equal to PageSizeHint for every response, which can be exceeded by an indivisible transaction group.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A pull-model reader for a container named ledger sets PageSizeHint to 50 and preallocates a fixed array of exactly 50 slots for each respo
- You have an Azure Cosmos DB for NoSQL account named account1. Writes to a container named orders run through a stored procedure that updates up to 150 items in one transaction. A pull-model reader set
- A Python change-feed continuation preserves the previously selected mode
Python uses container.query_items_change_feed to consume changes and supports mode values LatestVersion and AllVersionsAndDeletes. A supplied continuation takes precedence over initial starting settings. Because the continuation contains the previously used mode, supplying it causes that mode to be used rather than a conflicting new mode argument.
Trap Reusing a saved Python token while changing only mode to switch feed modes, which continues in the token's recorded mode.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with all versions and deletes mode enabled. A Python job calls container.query_items_change_feed(continuation=token, mode="AllVersionsAndDe
- You have an Azure Cosmos DB for NoSQL account named account1 that is now enabled for all versions and deletes mode. A Python reader for a container named orders has used latest version mode with a sav
- GetChangeFeedIterator constructs a typed pull reader with a starting position and mode
In .NET, construct a typed pull reader with container.GetChangeFeedIterator<T>, supplying ChangeFeedStartFrom and ChangeFeedMode. These arguments choose where consumption starts and which feed mode is read. Consume the returned feed iterator with ReadNextAsync.
Trap Using GetItemQueryIterator to create a change-feed consumer, which executes item queries rather than reading the selected feed mode.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You inherit a .NET reader for a container named carts that uses SDK 3.30.0 and calls GetChangeFeedIterator<Cart>(ChangeFeedStartFrom.Begin
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET 8 service must read the latest-version change feed of a container named orders from the beginning, deserializing each change into a
- GetChangeFeedStreamIterator reads change-feed responses without typed deserialization
Use container.GetChangeFeedStreamIterator with the chosen ChangeFeedStartFrom and ChangeFeedMode when the application needs response streams rather than deserialized entity objects. The stream form allows custom processing without first constructing typed payload objects. Use GetChangeFeedIterator<T> when typed results are wanted.
Trap Choosing GetItemQueryStreamIterator merely because it returns streams, which uses the item-query path rather than the change-feed path.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET relay service for a container named orders currently calls GetChangeFeedIterator<Order> and reserializes every object before forwar
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET relay service reads the latest-version change feed of a container named events and forwards each page's raw JSON to Azure Event Hub
- The change-feed estimator reports pending-change lag rather than an exact processing-time delay
Use the change-feed estimator to assess how far processor progress lags behind the container's latest changes. It estimates pending changes for both feed modes and is not guaranteed to be an exact outstanding-event count. A growing estimate indicates that arrival rate exceeds the deployment's sustained processing capacity.
Trap Interpreting EstimatedLag as milliseconds of guaranteed processing latency, which measures an approximate pending-change backlog instead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed estimator push delegate for a processor on a container named orders sends a value of 1,200 to a dashboard, where an operator
- You have an Azure Cosmos DB for NoSQL account named account1. A change feed estimator for a processor that reads a container named clicks reports 2,000 at 09:00, 9,000 at 11:00, and 18,000 at 13:00 du
- An estimator must use the processor's name and lease configuration
To measure a particular deployment unit, create its estimator with the same processor name and lease container. A push estimator can notify a delegate at a chosen interval, with a documented default interval of five seconds. Different processor identities represent different saved progress and therefore different backlog estimates.
Trap Giving the estimator a new processor name to distinguish it operationally, which points it away from the checkpoint set being measured.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A processor named ordersProcessor reads a container named orders with a lease container named leases. A monitoring service builds an estim
- You have an Azure Cosmos DB for NoSQL account named account1. A .NET processor named invoiceSync reads a container named invoices and stores state in a lease container named leases. An operations team
- On-demand estimation identifies each lease's lag and current owner
Use GetChangeFeedEstimator and GetCurrentStateIterator for detailed on-demand state in .NET. Each ChangeFeedProcessorState includes the lease token, EstimatedLag, and InstanceName of its owner. This distinguishes an isolated stalled range or host from a broadly underpowered deployment.
Trap Using only one aggregate backlog number to identify the responsible worker, which omits the per-lease ownership information.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A processor deployment for a container named payments runs on six hosts, and the total estimated backlog is high. Operators suspect that o
- You have an Azure Cosmos DB for NoSQL account named account1. You created ChangeFeedEstimator estimator = monitoredContainer.GetChangeFeedEstimator("payProcessor", leaseContainer); for a container nam
- One independent estimator can monitor the deployment but its measurements consume RUs
The estimator can run independently of the processor deployment, and one instance can monitor all its leases and workers. Each measurement consumes RUs from the monitored and lease containers. Increasing measurement frequency adds database work, so choose a cadence appropriate to the operational need.
Trap Running a high-frequency estimator on every worker as a requirement for monitoring, which duplicates work that one independent estimator can perform.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A single change feed estimator runs on its own instance to monitor a processor deployment that reads a container named orders and stores i
- You have an Azure Cosmos DB for NoSQL account named account1. A processor deployment for a container named shipments runs on 12 instances in Azure Kubernetes Service. The team wants backlog monitoring
- A copy job needs an existing destination container with the desired new settings
Create the destination container before starting a copy job, with the desired partition key, unique keys, throughput granularity, and other settings. Copy jobs support changes that cannot be applied in place, including repartitioning or adopting HPK. The job copies data into that configured resource rather than editing the source definition.
Trap Starting a copy job expecting it to create the destination and infer its new partitioning policy, which requires the target to exist first.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You run az cosmosdb copy create to copy a container named orders into a destination container named ordersV2 that will use a new partition
- You have an Azure Cosmos DB for NoSQL account named account1. A container named sessions is partitioned by /tenantId, and a few tenants are approaching the 20 GB logical partition limit. You plan to u
- Offline copy requires source operations to stop before the job starts
For an offline copy, pause applications and clients operating on the source, start the job, and wait for completion before resuming against the intended container. Offline copy uses latest-version change feed. Updates and deletes made after the job starts may not be captured reliably, so it is not a live synchronization contract.
Trap Continuing source writes throughout an offline copy and assuming cutover consistency, which can leave missing or duplicate destination data.
- Online copy adds incremental change capture after its source prerequisites are enabled
Online copy uses all versions and deletes change feed to replicate incremental changes while copying. The source needs continuous backup, the all-versions-and-deletes feature, and the EnableOnlineContainerCopy capability. Wait at least 30 minutes after enabling that capability before creating the online job.
Trap Selecting --mode Online on a source without all-versions-and-deletes readiness, which omits the change history the online mechanism needs.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses continuous backup. You need to copy a container named orders to a new container with a minimal write outage by using an online co
- You have an Azure Cosmos DB for NoSQL account named account1 that uses continuous backup and all versions and deletes mode. A script adds the EnableOnlineContainerCopy capability with az cosmosdb upda
- Online-copy cutover requires stopping source updates and explicitly completing the job
When processed count catches up with total count, stop source updates and allow the documented five-to-ten-minute flush interval. Call az cosmosdb copy complete to finish the online job and flush remaining changes, then redirect clients as required. A temporarily caught-up counter is not itself the final cutover operation.
Trap Redirecting writes as soon as processed count matches total count while the source remains active, which skips the controlled stop-and-complete cutover.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. An online container copy job named job1 copies a container named carts to a container named carts2. The output of az cosmosdb copy show re
- You have an Azure Cosmos DB for NoSQL account named account1. An online container copy job from orders to ordersV2 is running, and az cosmosdb copy show now reports that the processed count is greater
- Copy speed depends on source capacity, destination capacity, and allocated copy compute
A copy job reads using source throughput and writes using destination throughput, with platform-allocated server-side compute also limiting progress. Documentation recommends target throughput of at least twice the source throughput. Increasing only one side cannot remove a bottleneck on the other side or in the copy workers.
Trap Scaling only source throughput to accelerate a destination-throttled copy, which leaves its write bottleneck unchanged.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You are planning a container copy job from a container named products, which is provisioned at 10,000 RU/s, to a new container named produ
- You have an Azure Cosmos DB for NoSQL account named account1. A container copy job from a container named events, provisioned at 20,000 RU/s, into a container named eventsV2, provisioned at 5,000 RU/s
- Copy jobs have distinct CLI commands for creation, inspection, pausing, and cancellation
Install the cosmosdb-preview Azure CLI extension to use the documented copy commands. Use az cosmosdb copy create with --src-nosql and --dest-nosql database/container identifiers, show for one job, and list for the account's jobs. Pause and resume preserve an ongoing job, while cancel abandons it; --mode Online explicitly selects online copying.
Trap Using cancel as a temporary pause before resuming the same job, which confuses abandonment with pause and resume.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A long-running container copy job named job1 must be halted during a quarterly finance close so that its reads and writes don't compete wi
- You have an Azure Cosmos DB for NoSQL account named account1 with the EnableOnlineContainerCopy capability enabled. A script runs az cosmosdb copy create --job-name job2 --src-account account1 --dest-
- Copy jobs run consecutively within an account and operate at container scope
An account can contain several copy jobs, but they execute consecutively rather than all running simultaneously on independent worker sets. Copying an entire database requires a job for each container. Job names must be unique within the account.
Trap Creating many jobs in one account to force simultaneous copy-worker execution, which the consecutive scheduling model does not provide.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You need to copy an entire database named sales, which contains five containers, into a new database named salesV2 in the same account by
- You have an Azure Cosmos DB for NoSQL account named account1 that contains a database named sales with four containers. To copy the whole database, you created four offline container copy jobs in acco
- Copy jobs preserve remaining item TTL but do not copy the container TTL policy
Copy jobs copy item-level TTL values and recalculate them to preserve remaining time until expiration. Container-level TTL settings are not copied and must be configured independently on the destination. Copied items then follow the destination's container-level TTL configuration.
Trap Assuming copied items automatically enable the source's default TTL policy on the target, which is not copied with the data.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named sessions has a container-level default TTL of 86,400 seconds, and its items don't set their own ttl. After a container c
- You have an Azure Cosmos DB for NoSQL account named account1. In a container named tokens, each item sets its own ttl. An item that was written with a ttl of 30 days has 10 days of its lifetime remain
- Repartitioning can make previously valid item identities collide
Before copying to a different key, check that every destination partition-key and id combination is unique. Items with the same id in separate source partitions can map to one destination partition and cause an insertion conflict. New-key groups must also remain within full logical-partition storage limits.
Trap Checking uniqueness only under the source partition key before repartitioning, which can miss identities that collide in the new layout.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A container named staff is partitioned by /department, and ids are unique only within each department. A copy job writes the items to a ne
- You have an Azure Cosmos DB for NoSQL account named account1. A copy job that repartitions a container named telemetry from /deviceId to /siteId fails with a 403 error, substatus 1014, stating that a
- Partition merge is an eligibility constraint for copy jobs
Current copy-job preview limitations exclude accounts with merge partition enabled. Check capability compatibility before scheduling a migration that relies on these jobs. A supported container layout does not by itself establish that the account is eligible for the preview service.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. Partition merge was enabled last year, several containers were merged, and the feature was then disabled. You mu
- You have an Azure Cosmos DB for NoSQL account named account1 that uses periodic backup. Partition merge is currently enabled on account1 to reduce fragmentation of several containers. You must use a c
- Online-copy enablement adds source replace and delete RU overhead
The documented EnableOnlineContainerCopy mechanism retains previous and current versions for source replace and delete operations. Those operations incur an additional size-dependent RU surcharge documented as 50 to 100 percent over base write charges; creates are unaffected. Budget source capacity for that added work during the online-copy design.
Trap Sizing online-copy source writes using only their original replace and delete charges, which omits version-retention overhead.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You plan an online container copy job for a container named ledger and must enable the EnableOnlineContainerCopy capability first. The sou
- You have two Azure Cosmos DB for NoSQL accounts named account1 and account2. You plan an online container copy job from a container named ledger in account1 to a container named ledger2 in account2, a
- Copy-job eligibility depends on support in the account's write region
A container copy job runs in a write region, and the account's write-region placement must meet the preview's supported-region requirements. For a multi-write account, the job runs in one of its write regions. Check the current supported-region list before relying on otherwise valid source and destination settings.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 with a single write region and two read regions. You plan to create container copy jobs on account1. The documentation lists the regions in
- You have an Azure Cosmos DB for NoSQL account named account1 that is configured with multi-region writes in East US, West Europe, and Japan East. You plan container copy jobs for account1 and must con
- A write-region change fails incomplete copy jobs
When an account's write region changes, its incomplete container copy jobs fail. Recreate those failed jobs so they execute in the new current write region.
Trap Issuing copy resume after a write-region change has failed the job, which does not recreate it in the new write region.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1 that has a single write region. A manual failover moved the write region from North Europe to West Europe while a container copy job was ru
- You have an Azure Cosmos DB for NoSQL account named account1 with East US as its write region and West US as a read region. An offline container copy job named job7 was halfway through copying a conta
- Cross-account copy creation identifies both source and destination accounts
The documented az cosmosdb copy create command identifies the accounts with --src-account and --dest-account. Its --src-nosql and --dest-nosql values then identify the database and container on each side. Database and container names alone do not specify a cross-account copy route.
2 questions test this
- You have two Azure Cosmos DB for NoSQL accounts named source1 and target1 in the same resource group. You are writing az cosmosdb copy create to copy container orders in database sales on source1 to c
- You have two Azure Cosmos DB for NoSQL accounts named source1 and target1. Your az cosmosdb copy create command already sets --src-account source1, --dest-account target1, and --src-nosql database=sal
- Cross-account copy requires destination access for the source account's selected identity
Before starting a cross-account copy job, configure the source account's selected managed identity with the documented read-write access to the destination account. The setup can use a system-assigned or user-assigned identity. This cross-account authorization prerequisite is unnecessary for a copy within the same account.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. You plan a container copy job that copies a container named orders to a new container named ordersV2 in the same account. A colleague prep
- You have two Azure Cosmos DB for NoSQL accounts named source1 and target1 in different subscriptions. You will run container copy jobs from source1 to target1. Security requires a managed identity, no
- Changing source identity during online copy can leave separate destination documents
During online container copy, changing an item's source id can leave two destination documents corresponding to the distinct id values. Keep identities stable during synchronization and include identity changes in migration validation. This issue differs from two unchanged source identities colliding under a new destination partition key.
- Container copy jobs have no guaranteed completion-time SLA
Container copy jobs currently operate on a best-effort basis without an SLA for how long they take to finish. Plan validation and cutover around observed job completion rather than a promised fixed migration duration.
2 questions test this
- You have an Azure Cosmos DB for NoSQL account named account1. A vendor contract for migrating a 2-TB container named telemetry must state the guaranteed completion time that Microsoft provides for a c
- You have an Azure Cosmos DB for NoSQL account named account1. You must plan the cutover for an online container copy job that moves a container named catalog to a container named catalogV2 with a new
- The platform can release copy compute after about fifteen minutes of inactivity
The platform allocates server-side compute for copy jobs and can deallocate idle instances after approximately 15 minutes. That interval describes idle worker cleanup, not a deadline for finishing an active copy job.
Design and implement Azure Cosmos DB solutions by using AI-assisted tools
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Secure, optimize, and deploy database solutions
Implement database security controls
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Implement availability and recovery solutions
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Optimize and remediate database performance
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Manage and monitor fleets across accounts and subscriptions
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Implement AI and analytics capabilities in database solutions
Design and implement AI retrieval
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Design and implement agent memory stores
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.
Design and implement operational analytics on Azure Cosmos DB
Read full chapterUnlock with Premium — includes all practice exams and the complete study guide.