Study Guide · DP-420

DP-420 Cheat Sheet

835 entries · 12 chapters · 3 domains

Design and develop database solutions

Evaluate resource models and SDK solutions

Read full chapter

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

1 question tests this
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.

1 question tests this
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
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
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
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.

1 question tests this
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.

1 question tests this
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
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
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
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
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
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.

1 question tests this
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.

1 question tests this
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
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
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
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.

1 question tests this
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
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
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
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
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
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
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
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
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
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.

Dedicated container throughput provides isolation that shared database throughput does not

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
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
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
A shared-throughput database normally supports at most 25 shared containers

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 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
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
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
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
Shared-database minimum throughput can also depend on container count

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

1 question tests this
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 chapter

Cheat 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
EXISTS tests an array predicate without expanding parent results

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
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
An aggregate scalar subquery can summarize each item's child collection

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.

1 question tests this
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.

1 question tests this
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
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
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
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
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
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
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
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
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
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.

1 question tests this
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.

1 question tests this
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
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
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
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
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
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
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
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
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.

1 question tests this
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
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
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
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
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
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
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
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
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.

1 question tests this
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
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
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
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
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.

1 question tests this
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
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.

1 question tests this
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.

1 question tests this
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
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
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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 chapter

Cheat 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
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
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
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
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
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
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
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
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
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
Reference frequently changing data that is shared by many entities

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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
.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
A tenant-key shared container suits tenants whose workloads can share one resource

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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 chapter

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

1 question tests this
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
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
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
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
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
Cooperating processor instances share a processor name but have distinct instance names

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

1 question tests this
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.

1 question tests this
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 chapter
  • Agent Kit supplies development guidance rather than executing database operations
  • Agent Skills compatibility determines whether an assistant can use the kit
  • The documented Agent Kit installation uses the skills command through npx
  • Agent Kit is installed in the development environment rather than enabled as an account capability
  • Installed skills activate from relevant Cosmos DB tasks expressed in natural language
  • Agent Kit is designed for progressive on-demand skill delivery
  • Keeping the installed skill current refreshes its development recommendations
  • SKILL.md describes activation while AGENTS.md supplies compiled rules
  • Individual best-practice rules live in categorized rule files
  • The skill's metadata file records its version rather than database configuration
  • Data Modeling and Partition Key Design rules guide early structural reviews
  • Query and indexing rule categories support different parts of an assisted query review
  • The SDK guidance reviews client construction, retries, and error handling as one implementation context
  • Capacity and consistency advice come from dedicated kit rule categories
  • The Cosmos DB MCP toolkit supplies live database discovery and sampled schema context
  • The MCP recent-document tool supplies live content for freshness checks
  • The MCP identifier lookup retrieves a known record for validation
  • MCP search-tool selection depends on keyword matching versus semantic similarity
  • Vector Search rules help a coding assistant generate Cosmos DB retrieval code
  • Full-Text Search rules extend assisted development beyond vector-only patterns
  • The kit includes a LangGraph pattern for wrapping synchronous Cosmos calls in asynchronous workflows
  • Developer Tooling rules cover validation, SDK currency, and emulator configuration
  • Monitoring and Diagnostics rules help add observability to generated applications
  • Agent Kit's Design Patterns guidance covers materialized views and efficient ranking

Unlock with Premium — includes all practice exams and the complete study guide.

Secure, optimize, and deploy database solutions

Implement database security controls

Read full chapter
  • Managed identity authentication removes application-held database secrets
  • disableLocalAuth enforces migration away from account key authentication
  • Rotate the unused key before switching applications and regenerating the active key
  • Safe key rotation blocks regeneration of a key used within the last twelve hours
  • Resource tokens delegate limited access without distributing an account key
  • Resource tokens expire after one hour by default and can last at most five hours
  • Permission resources distinguish read-only access from read-write-delete access
  • A user can have only one permission for a particular resource
  • REST authorization wraps the selected credential in an encoded token string
  • A REST master-token signature is bound to the request method, resource, and date
  • Reading a permission issues a fresh resource token
  • Cosmos DB Built-in Data Reader grants reads and queries without item writes
  • Cosmos DB Built-in Data Contributor authorizes container data operations and item mutations
  • Container-scoped assignments restrict a data role to one container
  • Every SDK data-access role needs the readMetadata action
  • SDK queries require both executeQuery and readChangeFeed permissions
  • Native data-plane custom roles do not support notDataActions
  • Native role definitions and assignments use the cosmosdb sql role command family
  • Item reads and container query execution are separate native data actions
  • Cosmos DB Operator manages accounts without access to data or account keys
  • Managing native data-plane roles requires control-plane permissions
  • Disabling key-based metadata writes moves resource changes to attributable management operations
  • ControlPlaneRequests captures configuration operations rather than item traffic
  • Correlating control-plane diagnostics with the Activity log identifies the caller
  • Passing a Cosmos DB network rule does not grant database authorization
  • IP firewall rules admit public addresses or CIDR ranges rather than private subnet addresses
  • Service endpoint access needs both subnet enablement and a Cosmos DB virtual network rule
  • Enabling a service endpoint changes how Cosmos DB identifies the request source
  • Cross-subscription service endpoint access still requires a common tenant and provider registration
  • Virtual network peering does not inherit a service endpoint allowlist entry
  • The Azure datacenter exception is not restricted to your own subscription
  • Disabling public network access overrides public-source firewall exceptions
  • Firewall and service endpoint rule changes can need fifteen minutes to propagate
  • Portal data browsing must pass the Cosmos DB account firewall
  • Stage the account's subnet rule before enabling the subnet service endpoint
  • Account updates revalidate access to configured service-endpoint subnets
  • Network-rule collection updates must include every admission that should remain
  • Cosmos DB network ACLs filter requests rather than rejecting the connection itself
  • Private endpoints provide private-IP connectivity from connected networks and on-premises
  • NoSQL private endpoints use the Sql subresource and privatelink.documents.azure.com zone
  • A Cosmos DB private endpoint needs global and per-region private addresses
  • Private DNS zone groups maintain Cosmos DB regional records automatically
  • Private Link Direct mode needs the full TCP port range
  • One Cosmos DB account supports at most two hundred private endpoints
  • Client DNS resolution determines whether the account hostname uses Private Link
  • Explicit client allow rules avoid the default interruption when adding a private endpoint
  • Automatic private endpoint approval requires an approval action on the Cosmos DB account
  • A rejected Cosmos DB private endpoint connection must be recreated
  • Dynamic data masking is enabled at the account and configured on containers
  • The default masking strategy depends on the value's type
  • MaskSubstring masks a specified forward range within a string
  • Email masking preserves the first username letter and the domain ending
  • Masking exclusions require an include-all root rule
  • Masking paths address fields in all array elements rather than a numbered element
  • Dynamic data masking requires Microsoft Entra identity authentication rather than account keys
  • Unmasked reads require the unmask data action and ordinary read permissions
  • Dynamic data masking limits read projections but does not encrypt stored data
  • Write operations can expose unmasked values even when reads are masked
  • Change feed access on a masked account requires unmask permission
  • Masking adds processing only when returned data needs masking
  • Masking does not replace restrictions on direct database access
  • Masking the item ID or partition key prevents the Data Explorer document view

Unlock with Premium — includes all practice exams and the complete study guide.

Implement availability and recovery solutions

Read full chapter
  • Periodic backup uses support-assisted snapshot recovery rather than self-service point-in-time restore
  • Periodic mode takes a full backup every four hours and retains two backups by default
  • Periodic backup scheduling has bounded interval and retention settings
  • Deleted periodic-backup containers and databases retain existing snapshots for thirty days
  • Periodic backup defaults to geo-redundant storage but can remain within one region
  • The first two periodic backup copies are included and extra copies are billed
  • Periodic recovery restores a new single-region account in the source write region
  • Retained native backups cannot be modified, directly deleted, or disabled by customers
  • Native background backups do not consume the application's provisioned RUs
  • CosmosBackupOperator authorizes periodic-backup restoration requests
  • Continuous backup offers fixed seven-day, thirty-day, and thirty-five-day retention tiers
  • Seven-day continuous backup has no backup-storage charge but restores are billed in every tier
  • Migration from periodic to continuous backup cannot be reversed
  • An unspecified migration tier defaults to thirty-day continuous backup
  • Continuous backup is local to each configured account region
  • The latest restorable timestamp is specific to the resource and region
  • Continuous backup normally persists mutations asynchronously within one hundred seconds
  • Continuous backup supports NoSQL, MongoDB, Gremlin, and Table accounts but not Cassandra
  • Customer-managed-key migration needs a Key Vault-authorized default identity
  • A new-account restore recovers data and index properties rather than all application artifacts
  • Restoring to a new account does not recreate the source security perimeter or regional topology
  • A shared-throughput database must be restored as a whole
  • Restore targets stay within the source subscription and eligible backup regions
  • Disable TTL during restore when recovered items must not expire immediately
  • Continuous restore requires source restore permission and destination account creation permission
  • Source restore privileges are scoped to a restorable account or subscription rather than a resource group
  • Periodic recovery generates new account keys for the restored account
  • Periodic restoration excludes documents deleted by expired TTL
  • Periodic restoration does not restore materialized views
  • Account-level continuous recovery specifies the source instance and a new destination account
  • Restore discovery requires read permissions on the restorable source resources
  • An ARM-based restore also needs destination deployment permissions
  • Keep relevant IAM policies unchanged while continuous restoration runs
  • Multi-write recovery includes only mutations confirmed by the hub at the restore point
  • Restoring a multi-write collection resets its custom conflict policy to timestamp-based LWW
  • A restored collection may still be rebuilding its consistent index
  • Continuous restore does not guarantee historical throughput configuration
  • A new account restored from continuous backup retains the source consistency setting
  • Same-account restore recovers deleted resources rather than rolling back a live corrupted container
  • The restorable event feed identifies the deleted resource version and valid restore time
  • Same-account NoSQL restore uses the database restore or container restore command
  • Restore a missing parent database before its deleted child container
  • One account permits at most three active same-account restore operations
  • Deleting the source account can fail an in-progress restore
  • A same-account restored container becomes Online only after asynchronous recovery completes
  • The InAccount Restore Deleted Activity-log operation identifies same-account recovery
  • Additional read regions add regional cost rather than free replica capacity
  • Multi-region writes serve active writers near their regional application instances
  • A newly added region becomes available only after existing data has replicated there
  • Availability-zone protection is configured independently for each account region
  • Healthy regions need capacity for traffic redirected from a failed region
  • Secondary read regions do not become local writers in a single-write account
  • Existing-region zone protection generally requires a regional migration procedure
  • Serverless zone redundancy must be selected at account creation
  • Multi-write accounts and autoscale collections are exempt from the zone-redundancy premium
  • Region removal must preserve an eligible writer and at least one account region
  • Multi-write outage recovery routes reads and writes to healthy regions
  • Concurrent regional writes can produce insert, replace, and delete conflicts
  • Last-writer-wins chooses the highest conflict-resolution value
  • A delete wins a last-writer-wins delete conflict regardless of the numeric path
  • A custom merge stored procedure applies application-defined conflict semantics on the server
  • Custom resolution without a merge procedure sends conflicts to the conflict feed
  • Custom conflict resolution must be chosen when a NoSQL container is created
  • Service-managed failover promotes a secondary region according to account priorities
  • Change write region is a planned operation that requires healthy communicating regions
  • Avoid unrelated control-plane changes to an affected account during regional recovery
  • Strong-configured regional failover preserves acknowledged writes while weaker configurations can lose unreplicated writes
  • An account-level failed-over write region does not automatically reclaim writes on recovery
  • Read-region outages are normally handled by SDK regional routing rather than promoting a new writer
  • Forced failover takes an unavailable region offline without waiting for service-managed recovery
  • A secondary-region outage can block writes in a two-region Strong account
  • An extended read-region outage can exhaust Bounded Staleness write availability
  • Session, Consistent Prefix, and Eventual regional-outage RPO is less than fifteen minutes
  • Bounded Staleness regional-outage RPO follows its configured K and T bounds
  • A regional recovery drill uses forced failover and restores the intended failover configuration afterward
  • Regional offline and online operation metrics identify the region and operation status
  • The conflict feed exposes unreplicated writes after ordinary write-region recovery
  • PPAF requires a provisioned NoSQL account with one writer and at least one read region
  • PPAF does not support Bounded Staleness or switching between Strong and non-Strong while enabled
  • Every application instance must use a PPAF-capable SDK before account enablement
  • PPAF must be disabled before partition merge or region-offline operations
  • PPAF is an account feature in the Business Critical tier
  • PPAF's documented connection-mode prerequisite is Direct
  • PPAF is currently available in Azure public-cloud regions
  • PPAF redirects only affected partitions and leaves healthy writers in place
  • PPAF selects a recovery replica using account priorities and replica freshness
  • PPAF-capable SDKs refresh partition-to-region routing without changing the account endpoint
  • PPAF automatically fails back with incremental catch-up rather than a full rebuild
  • PPAF reconciles weaker-consistency divergence with timestamp-based last-writer-wins by default
  • PPAF can temporarily downshift a two-region Strong write quorum during failure
  • PartitionWriteGlobalStatus shows where write partitions currently reside
  • PPAF failure simulation affects a bounded subset of a container's partitions
  • PPAF enables a client-side partition circuit breaker for read availability

Unlock with Premium — includes all practice exams and the complete study guide.

Optimize and remediate database performance

Read full chapter
  • Partition-targeted queries avoid paying for every physical partition's index work
  • Indexed normalized values avoid applying UPPER or LOWER to every candidate document
  • STARTSWITH is the better match when a search requires only a string prefix
  • Filtering array subqueries before JOIN reduces intermediate cross-products
  • MaxConcurrency reduces fan-out latency without changing which partitions must execute
  • MaxBufferedItemCount controls how much query prefetch can hide page-consumption latency
  • Query Advisor returns query-plan advice on the first .NET query round trip
  • High-cardinality GROUP BY can remain expensive even when its filter uses indexes
  • Case-insensitive STARTSWITH and STRINGEQUALS use expanded index scans
  • More provisioned throughput can reduce query latency dominated by throttling waits
  • Time filters should avoid repeatedly evaluating nonstatic clock functions
  • Ordering by the searched string can make scan-based string filters cheaper
  • An indexed aggregate can still load documents to evaluate its filters
  • EnableScanInQuery permits full scans of filter paths excluded from indexing
  • Smaller continuation-token limits can increase query duration and RU consumption
  • Excluding unqueried paths reduces index maintenance work for writes
  • The indexing root must be included or excluded to define the policy's default behavior
  • Indexing paths distinguish scalar values, array elements, and whole subtrees
  • More precise indexing paths override broader include or exclude rules
  • Index path names are case-sensitive and must match stored JSON names
  • Partition routing does not automatically supply an index for the partition-key property
  • Spatial query acceleration requires an explicit spatial index for the required geometry types
  • Tuple indexes optimize filters on multiple fields in the same array element
  • Range indexes support scalar filtering and single-property ordering
  • A multi-property ORDER BY needs a composite index with the same path sequence
  • A composite index supports its configured sort directions and their complete reversal
  • Composite filter indexes put equality properties before the range property
  • Each composite index optimizes at most one range filter
  • Adding equality-filter fields to ORDER BY can enable a cheaper composite-index plan
  • Filtered SUM and AVG queries can benefit from a composite ending in the aggregate property
  • Composite index paths have an implicit scalar ending and cannot use a subtree wildcard
  • A filter composite is not used if it includes a property absent from the query's filters
  • A composite index can combine a root property with a joined array value
  • Index transformations run online but consume spare provisioned RUs
  • Add and finish a replacement index before removing the old index
  • Group index removals into one policy update to preserve complete results during transformation
  • Temporarily disabling indexing can accelerate a bulk load that does not need indexed queries
  • An exclude-root consistent policy preserves TTL without indexing application paths
  • GetQueryMetrics exposes typed server-side query metrics from a response's diagnostics
  • Query measurements must include every continuation rather than just the first page
  • A large gap between retrieved and output document counts signals wasted document loading
  • Query timing components identify whether loading, index lookup, or execution dominates
  • Per-partition query metrics isolate an expensive physical partition hidden by aggregates
  • A function in SELECT does not disable the filter's index access merely because it would scan in WHERE
  • Projecting only needed fields can reduce query output work without reducing document loading
  • Using an index does not establish that the query's access method is cheap
  • PopulateIndexMetrics requests the query's index usage and recommendations
  • Index metrics are disabled by default and should be enabled selectively
  • Utilized indexes are evidence about the measured query rather than the whole workload
  • Potential index recommendations must be tested against the actual data
  • Index impact scores reflect query shape rather than measured data selectivity
  • Using the integrated cache requires a dedicated gateway endpoint and Gateway mode
  • Only Session and Eventual read requests can use the integrated cache
  • Integrated cache hits cost zero RUs and favor repeat-heavy read workloads
  • MaxIntegratedCacheStaleness controls acceptable age at read time rather than a global cache TTL
  • The query cache stores result sets rather than tracking changes to individual matching items
  • Dedicated gateway nodes have independent caches sharing item and query capacity within each node
  • BypassIntegratedCache avoids cache use and population without bypassing the dedicated gateway
  • A cached Session read must satisfy the requesting client's session token
  • Cache eviction and gateway CPU distinguish memory-size problems from request-volume problems
  • ReadMany populates the query cache while bulk and transactional batch requests do not populate the item cache
  • DedicatedGatewayRequests verifies gateway use independently of cache hits
  • Staleness-driven eviction can indicate that the integrated cache is oversized
  • Server-side latency does not measure the application's complete operation latency
  • Use the Direct or Gateway server-side latency metric that matches the connection path
  • SDK diagnostics should be captured for slow successes as well as exceptions
  • The diagnostic string is for inspection rather than a stable parsing interface
  • High transit time with low BELatencyInMs points away from backend execution
  • Thread-starvation markers and delayed system-history samples identify a client scheduling bottleneck
  • Maximum client CPU is more useful than average CPU for latency troubleshooting
  • Read hedging reduces tail latency by accepting the fastest regional response
  • Database and container existence checks belong outside the item-operation hot path
  • SNAT exhaustion can cause transport timeouts from private-IP application hosts
  • A long Pipelined stage identifies delay writing the request to its TCP socket
  • Many callsPendingReceive can justify more TCP channels to reduce head-of-line blocking
  • Metric, Activity log, and log-query alerts address different monitoring requirements
  • Logical-partition storage alerts use PartitionKeyStatistics diagnostic logs
  • Alert dimensions keep a local performance problem from being diluted by account-wide aggregation
  • Static thresholds enforce a specified boundary while dynamic thresholds learn metric behavior
  • Action groups define notifications or automation separately from the alert condition
  • ReplicationLatency measures regional replication lag rather than application request latency
  • ServiceAvailability reports account request availability as a percentage
  • A throttling-count alert uses TotalRequests filtered to status code 429
  • DataUsageV2 and IndexUsageV2 measure stored data and index bytes for storage alerts
  • Choose Resource Health for an account and Service Health for broader incidents
  • Diagnostic settings route selected Cosmos DB log categories to Log Analytics
  • Resource-specific mode separates diagnostic categories into CDB tables
  • Join data-plane requests to query runtime statistics to associate RU charge with query text
  • Diagnostics full-text query logging is required to see deobfuscated query content
  • KQL percentiles expose tail request durations that a mean can hide
  • Partition-key RU and storage investigations require different diagnostic tables
  • Legacy diagnostic fields often need numeric conversion before filtering or aggregation
  • Partition-key storage statistics report sampled outliers rather than every logical partition
  • Aggregated request categories consolidate telemetry into five- or fifteen-minute records
  • Blocked-request logs identify the source address to investigate before changing an allowlist

Unlock with Premium — includes all practice exams and the complete study guide.

Manage and monitor fleets across accounts and subscriptions

Read full chapter
  • Fleets retain account-per-tenant isolation while centralizing capacity and observability
  • The fleetspace is the sharing boundary for pooled throughput
  • A fleetspace can group accounts from different subscriptions and resource groups
  • An account can belong to only one fleetspace and one fleet at a time
  • A fleet resource's management region does not determine its accounts' data regions
  • Fleet membership does not require enabling a throughput pool
  • A fleetspace account resource registers an existing database account with a fleetspace
  • The current fleetspace API kind is NoSQL
  • Resources consume dedicated RU capacity before drawing extra capacity from the fleetspace pool
  • Pooling works best when many tenants have different activity peaks
  • Accounts sharing a throughput pool must have matching regional configurations
  • A pooled fleetspace cannot mix single-write and multi-write account configurations
  • Fleetspace regions and service tier cannot be changed after creation
  • A pool autoscales between its configured minimum and a maximum no greater than ten times that minimum
  • Pool throughput starts at one hundred thousand RU per second and uses thousand-RU increments
  • Fleetspace dedicatedRUs and maxConsumableRUs describe different capacity quantities
  • Pooled capacity is deployed and updated on the fleetspace resource
  • Pool capacity is not shared across Azure regions
  • Pool billing uses each region's highest scaled throughput during the hour
  • A physical partition can draw at most five thousand extra pooled RUs by default
  • Default fleet limits cap accounts per fleetspace and total pool throughput
  • FleetspaceAutoscaledThroughput shows the pool's scaled capacity
  • Capacity Type separates requests and RUs served by dedicated throughput from pooled throughput
  • PhysicalPartitionThroughput provides the dedicated baseline needed to diagnose a pooled partition limit
  • Fleet analytics supports hourly cross-account trends rather than request-level incident diagnosis
  • Fleet analytics exports open Delta tables to OneLake or ADLS Gen2
  • A Fabric destination needs a OneLake workspace backed by licensed or trial capacity
  • The Cosmos DB Fleet Analytics service principal needs Contributor on the Fabric workspace
  • An ADLS fleet analytics destination needs hierarchical namespace and blob data-write permissions
  • Fleet analytics can take an hour to begin populating an authorized destination
  • Fleet analytics retention and analysis costs belong to the customer's destination
  • Joining hourly tables to DimResource supplies account and subscription context
  • FactRequestHourly supports ranking accounts by request volume over a chosen time window
  • FactRequestHourly distinguishes total RU usage, peak request charge, payload totals, and response status
  • FactResourceUsageHourly compares provisioned capacity with observed utilization
  • Storage maxima describe a footprint rather than additive hourly consumption
  • FactAccountHourly exposes fleet-wide backup and key-rotation configuration history
  • FactMeterUsageHourly and DimMeter connect measured consumption to pricing meters
  • Fleet analytics tables can be queried through a Fabric SQL endpoint or a Delta-capable Spark reader

Unlock 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 chapter
  • Efficient full-text retrieval needs matching policy and index paths
  • Full-text analysis follows the language configured for the text path
  • English stopwords are removed during both indexing and search
  • Full-text matching uses linguistic tokens rather than raw character equality
  • Additional full-text languages require the multilingual preview feature
  • Fuzzy full-text predicates tolerate at most two edits
  • Full-text array paths have conflicting documentation
  • FullTextContains filters documents by a lexical term or phrase
  • FullTextContainsAll requires every supplied term without requiring adjacency
  • FullTextContainsAny expresses alternative acceptable lexical matches
  • FullTextScore ranks by BM25 and is not a projected score column
  • Required text matches and relevance preferences can use different terms
  • A full-text prefilter can narrow a subsequent literal substring check
  • Splitting a long BM25 search phrase can reduce query cost
  • Search facets are aggregations over the full-text matching set
  • FullTextScore is not supported in queries that use JOIN
  • Full-text query cost depends on selectivity and indexed workload size
  • Vector indexing starts with enabling the account's NoSQL vector feature
  • Each vector path declares the embedding length expected at that path
  • Vector element precision trades storage against retrieval fidelity
  • Vector similarity can use cosine, dot product, or Euclidean distance
  • Different embedding properties can have independent vector policies
  • Vector policies do not support wildcard paths or vectors nested inside arrays
  • Container vector feature enablement is not reversible
  • The application generates embeddings before storing searchable vector properties
  • Embedding dimensionality trades retrieval quality against storage and comparison cost
  • Dimensionality reduction can shrink embeddings after generation
  • The flat vector index provides exact search within a 505-dimension limit
  • QuantizedFlat suits smaller searches over compressed vectors
  • DiskANN favors efficient approximate search over large candidate sets
  • QuantizedFlat and DiskANN fall back to scanning below 1000 indexed vectors
  • Vector indexing is not supported with shared throughput
  • The vector index quantizer can be product or spherical
  • VectorIndexShardKey partitions the DiskANN index by an item property
  • Omitting the shard key creates one DiskANN index per physical partition
  • A shard-focused vector query filters the shard property to its target value
  • Shard DiskANN on the attribute that consistently bounds semantic retrieval
  • Vector sharding does not replace other retrieval eligibility filters
  • VectorDistance can both rank retrieval results and expose their numeric score
  • Vector retrieval queries should explicitly bound their result count with TOP
  • VectorDistance's optional Boolean selects brute-force evaluation
  • VectorDistance accepts calculation overrides in its fourth argument
  • Increasing SearchListSizeMultiplier trades query cost for DiskANN recall
  • QuantizedVectorListMultiplier adjusts the quantized candidate search list
  • FilterPriority tunes the balance between filtering and DiskANN search
  • QuantizationByteSize changes the index's compression and accuracy trade-off
  • IndexingSearchListSize trades index-build effort for DiskANN accuracy
  • Excluding raw embedding elements from ordinary indexing reduces vector write cost
  • Repeated DiskANN queries can return slightly different approximate results
  • Vector performance and recall tests need realistic model embeddings
  • Very large vector ingestion bursts can lengthen vector index build time
  • VectorDistance expects one-dimensional numeric vectors
  • Hybrid search fuses semantic and lexical rankings with RRF
  • RRF weights correspond positionally to the scoring functions
  • RRF can fuse multiple lexical relevance signals
  • RRF can combine searches across different embedding properties
  • RRF belongs in ORDER BY RANK without an ordinary secondary property sort
  • Hybrid retrieval needs both vector and full-text configuration
  • RAG supplies retrieved content to the language model at request time
  • Cosmos DB can keep grounding content and its vector representation together
  • RAG chunks should preserve a useful concept without overwhelming model limits
  • Chunk boundaries should reflect the source document's structure
  • Query and content embeddings must use the same embedding model
  • Embedding preprocessing must be consistent between queries and chunks
  • Chunk metadata supports retrieval beyond the embedding alone
  • The RAG orchestrator selects a bounded set of relevant grounding results
  • RAG answer freshness depends on the data available to retrieval
  • Evaluate retrieval quality separately from generated-answer quality
  • Choose an embedding model by its fit to the corpus and retrieval tasks
  • Chunk overlap repeats boundary text to preserve context across cuts
  • Semantic chunking groups conceptually related content using embeddings
  • Text representations make media retrievable while source links preserve access to the original
  • Translate vague retrieval queries into context-aware searches without changing intent
  • Decompose multipart questions when different parts need separate retrieval evidence
  • HyDE uses a generated hypothetical answer as the vector retrieval probe
  • A model-based reranker refines a broader retrieval set before grounding
  • Negative retrieval tests check behavior when the corpus cannot answer
  • Agentic RAG can revise retrieval decisions using intermediate evidence
  • Scanned or complex-layout grounding documents need text and layout extraction
  • Answer completeness measures whether every part of the request is addressed
  • Context utilization shows how much retrieved material contributes to an answer
  • Answer relevance measures whether the response addresses the actual question

Unlock with Premium — includes all practice exams and the complete study guide.

Design and implement agent memory stores

Read full chapter
  • Agent memory must be persisted outside process memory to survive a restart
  • A thread-based memory key fits conversation-local reads
  • Tenant and thread hierarchy fits multitenant conversation memory
  • Per-item GUID memory keys favor write-heavy logging over conversation replay
  • Short-term working memory and long-term knowledge need different retention policies
  • Restart-safe agent persistence includes the complete session state
  • A custom history provider loads context and stores new messages separately
  • A shared history provider must keep conversation-specific keys in session state
  • A session should use one authoritative conversation-history model
  • Tool-calling runs can need history persistence before the overall run finishes
  • Serialized sessions must be restored with compatible agent and provider configuration
  • Resume shared application conversations through an owner-bound server-side mapping
  • One document per complete exchange is the recommended general chat-memory model
  • One response per item suits per-utterance retrieval and analytics
  • One thread per item is suitable only for deliberately bounded conversations
  • Conversation memory should preserve who produced each message
  • Summary memory can consolidate older exchanges without retaining every detail in active context
  • Recent conversation context is retrieved by thread and explicit sequence
  • Persisted chat history affects an answer only when it is supplied as model context
  • The active model context can be smaller than the durable conversation history
  • Durable working memory can include intermediate task and tool state
  • Audit history can be persisted without adding it all to future prompts
  • Semantic memory retrieves relevant earlier information beyond the recent window
  • Long-term user knowledge must be recalled at a scope broader than one thread
  • A memory embedding should represent the unit the agent needs to recall
  • Semantic memory can require freshness without switching to a purely chronological search
  • Memory retrieval can require an explicit mention rather than semantic closeness
  • A semantic cache reuses a prior completion for a sufficiently similar request
  • Semantic cache keys must include enough conversation context to disambiguate follow-ups
  • A semantic cache acceptance threshold balances hit rate against relevance
  • Semantic cache entries can expire independently of durable conversation history
  • A freshness predicate can exclude old cache entries while retaining them for analysis
  • Cache-hit metadata can support selective retention of frequently reused answers

Unlock with Premium — includes all practice exams and the complete study guide.

Design and implement operational analytics on Azure Cosmos DB

Read full chapter
  • Fabric Cosmos DB is an operational database, whereas mirroring exposes an existing source for analytics
  • Cosmos DB in Fabric usage is billed through Fabric capacity
  • Cosmos DB in Fabric requires autoscale containers
  • Fabric container throughput defaults differ between portal and SDK creation
  • A Fabric Cosmos DB database has a default quota of 25 containers
  • Choose Azure Cosmos DB when the application requires a multiregion deployment
  • Fabric Cosmos DB does not support Cosmos DB stored procedures, triggers, or UDFs
  • Cosmos DB in Fabric automatically mirrors every database to OneLake
  • Fabric Cosmos DB preserves a Cosmos-compatible operational API
  • An account-key-only application cannot move unchanged to Cosmos DB in Fabric
  • A requirement to retain Direct connections excludes Cosmos DB in Fabric
  • A customer-managed-key requirement excludes the current Fabric-native Cosmos DB service
  • Fabric tenant Private Link does not supply Cosmos-artifact-level Private Link
  • Cosmos DB in Fabric requires an eligible capacity-backed environment
  • Choosing Cosmos DB in Fabric preserves native AI retrieval capabilities
  • Fabric item permissions span the workspace's Cosmos DB artifacts
  • A Fabric capacity region must also support the Cosmos DB workload
  • Azure Cosmos DB mirroring requires a supported continuous-backup source
  • Cosmos DB mirroring supports NoSQL source accounts, not every Cosmos API
  • Mirroring is configured for an individual database with optional container selection
  • Mirroring isolates analytics from the source transactional RU workload
  • Mirroring uses a backup-based initial backfill and then live incremental changes
  • Database mirroring can pick up container lifecycle changes
  • A single mirrored copy can serve multiple Fabric analytical consumers
  • Free mirroring replication does not make analytical queries free
  • Explicit source deletes and source TTL deletions are treated alike by mirroring
  • A mirroring source connection needs supported read-write-key or organizational credentials
  • An Entra-authenticated mirror needs metadata-read and analytics-read source permissions
  • Mirror creation requires an eligible workspace and its Admin or Member role
  • The mirroring interface cannot select a virtual network data gateway connection
  • Ongoing mirroring runs in Fabric Replicator rather than through the gateway
  • Mirroring follows the current write region after a supported source fails over
  • A history of disabling analytical store can make an account ineligible for mirroring
  • Sharing mirror analytics does not require sharing the source database
  • Cosmos DB mirroring does not support customer-managed keys on the OneLake copy
  • Gateway-based Cosmos DB mirroring requires a same-region Fabric workspace
  • Monitor replication exposes both database and table synchronization state
  • Running with warning means replication continues despite nonfatal errors
  • An unchanged last-refresh timestamp can be normal for an idle source
  • Rows replicated counts applied changes rather than only current live rows
  • Stopping and restarting Cosmos DB mirroring reseeds the target tables
  • Workspace monitoring provides mirroring operation logs in a dedicated table
  • A key-authenticated mirror connection must be updated after key rotation
  • Initial mirrored type inference can reflect an older backup image
  • The Paused replication state can reflect a paused Fabric capacity
  • A container stuck with no replicated rows can be restarted by reselection
  • Missing SQL tables or columns can require endpoint schema refresh
  • New JSON properties become columns while missing properties appear as null
  • Renaming a JSON property leaves both old and new mirrored columns
  • Mirroring upcasts compatible property types and represents incompatible values as null
  • Case-distinct JSON property names can receive suffixed mirrored columns
  • The SQL string limit depends on when the mirrored table was created
  • The SQL analytics endpoint queries mirrored tables but does not write back
  • Fabric's source Data Explorer queries the source account rather than the mirror
  • Mirrored container tables support relational analytical joins
  • OPENJSON expands nested source data represented as JSON strings
  • OUTER APPLY preserves source rows that have no nested matches
  • AS JSON preserves a nested fragment for another expansion step
  • Bounded string types can improve typed JSON expansion performance
  • OPENJSON's default schema supports exploration of unknown nested properties
  • A OneLake shortcut exposes mirrored Cosmos DB tables to a Lakehouse notebook
  • Spark over a mirrored table and Spark through cosmos.oltp use different data paths
  • A Spark query can distinguish OneLake replication from SQL endpoint visibility issues
  • Mirroring converts operational JSON into Delta tables for analytical access
  • Direct Spark connector operations need the operational resource configuration
  • The Spark connector can infer a combined schema by sampling existing items
  • The Spark connector writes analytical results back through the operational API
  • A Spark write DataFrame must identify the destination items
  • ItemOverwrite controls replacement of matching items even in APPEND mode
  • CosmosCatalog enables Spark SQL resource management and table references
  • Spark catalog container creation declares the destination partition path and offer
  • The Spark connector libraries must match the notebook runtime
  • The Fabric Cosmos DB connector needs its Fabric-specific resolution settings
  • Connector partial updates use ItemPatch and explicit column operations
  • RawJson patch mapping treats a string column as JSON content
  • Spark explode expands an embedded document array into rows for aggregation

Unlock with Premium — includes all practice exams and the complete study guide.