DP-420 · CHEAT SHEET
Microsoft Certified: Azure Cosmos DB AI Developer Associate
Key concepts grouped by official exam weight.
Download as PDF (free, no sign-up)1. Design and develop database solutions
40–45%Evaluate resource models and SDK solutions
- Azure Cosmos DB offers five consistency levels: Strong, Bounded Staleness, Session, Consistent Prefix and Eventual. Strong and Bounded Staleness read from two replicas and double the RU cost of reads, while Session guarantees read-your-writes through session tokens. A per-request ConsistencyLevel override can only relax the account default.
- Request units (RUs) normalize the CPU, IO and memory cost of every operation. A point read by id and partition key is the cheapest read, and a query that filters on id and partition key doesn't count as a point read. Write cost depends on item size and indexed properties, and each operation's charge is returned in the SDK response.
- Provisioned throughput can be standard (manual) or autoscale, set on the container (recommended) or shared at database level, and it applies in every region of the account. Serverless fits intermittent traffic in a single region. Burst capacity uses idle capacity for short spikes, and priority-based execution throttles low-priority requests first.
- Account settings include regions, the default consistency level and the backup policy (periodic, or continuous with point-in-time restore). Container settings include the partition key and the unique key policy, which are fixed at creation, and the indexing policy and time to live (DefaultTimeToLive and per-item ttl), which can be changed later.
- Databases and containers are created with CreateDatabaseIfNotExistsAsync and CreateContainerIfNotExistsAsync in .NET, create_database_if_not_exists and create_container_if_not_exists in Python, or az cosmosdb sql commands in the CLI. Changeable properties are updated with replace_container. With Microsoft Entra ID, creating containers is a control plane operation, not a data plane one.
Implement database operations
- Parameterized queries use the @ notation (QueryDefinition.WithParameter in .NET, parameters in Python query_items) and prevent SQL injection. Results arrive in pages capped by MaxItemCount; read until no pages remain, and the continuation token, one per query, lets you resume at any time, except with GROUP BY or DISTINCT without ORDER BY.
- A point read (ReadItemAsync in .NET, read_item in Python) looks up an item by id and the full partition key value, including every level when it is hierarchical, and is the cheapest read: its cost depends on item size and consistency level. A query that filters on id and partition key isn't a point read; ReadManyItemsAsync or read_items read many pairs at once.
- CreateItemAsync fails if the id already exists, ReplaceItemAsync and patch work only on existing items, and UpsertItemAsync creates or replaces. Partial document update (patch) sends only the changed paths with Add, Set, Replace, Remove, Increment and Move, supports a conditional filter predicate and can't touch system properties; delete_item fails if the item doesn't exist.
- Transactional batch (CreateTransactionalBatch in .NET, execute_item_batch in Python) groups operations for one partition key value with ACID guarantees: if one fails, everything is rolled back and the others return 424. Bulk support in SDK v3 (AllowBulkExecution, one task per operation) maximizes throughput across partitions without atomicity and replaces the bulk executor library.
- TTL is set in seconds with DefaultTimeToLive on the container (absent or null: off; -1: on with no default expiry; n: items expire after n seconds) and can be overridden per item with the ttl property, counted from the last modification (_ts). A background task deletes expired items with leftover RUs, although they stop appearing in queries once expired.
Design and implement data models and partitioning strategies
- Start by listing the application's read and write requests and measure each version of the model against them for latency and RUs. For read-heavy workloads, denormalize and duplicate data into containers with a different partition key, kept in sync from the change feed, and keep items that must change together in one logical partition.
- Choose an immutable, string-typed, high-cardinality property that spreads RUs and storage evenly. In large read-heavy containers it should appear as an equality filter in most queries; /id suits workloads of point reads and writes. The key can't be changed in place: the data has to be moved to a new container.
- Embed data in contained or one-to-few relationships that change infrequently, don't grow without bound and are read together; this typically improves reads. Reference for one-to-many or many-to-many relationships, frequently changing data or unbounded collections; this typically improves writes. Hybrid models denormalize only the displayed fields and store precalculated aggregates.
- Provisioned throughput is divided evenly across physical partitions and a logical partition is never split, so a skewed key creates hot partitions that return 429s while capacity sits unused. Detect them with Normalized RU Consumption by PartitionKeyRangeId and CDBPartitionKeyRUConsumption, and watch storage with CDBPartitionKeyStatistics. The lasting fix is to change the key by migrating to a new container.
- Hierarchical partition keys support up to three levels (kind MultiHash), are set when the container is created, and let a prefix such as TenantId exceed logical partition limits. Prefix queries are routed to a subset of partitions and point reads use the full key built with PartitionKeyBuilder. With few tenants or write-optimized workloads, a synthetic key or /id fits better.
Implement change feed
- The change feed is enabled by default, consumes RUs from provisioned throughput and guarantees order only within a partition key value. It is read with Azure Functions, the change feed processor or the pull model, and supports notifications, materialized views, data movement, zero-downtime migrations and event sourcing.
- The change feed processor (.NET and Java only) keeps state in a lease container, polls by itself, distributes work across instances and retries failed batches. The pull model uses continuation tokens that you store, can read a single partition key and lets you control the pace, and parallelizes with FeedRange, but without automatic load balancing or an at-least-once guarantee.
- The lease container stores state and coordinates workers; it can live in the same or another account, and a partitioned one must use /id. Instances of one deployment unit share the processorName and lease container with different instance names, several units or triggers share it with distinct names or LeaseContainerPrefix values, and the global endpoint should be used.
- Latest version mode records creates and updates, only the latest version of each item and no deletes (use a soft delete with TTL), and can start from the beginning. All versions and deletes mode requires continuous backup, is enabled on an existing account, captures deletes with metadata and reads only from now, within the backup retention window.
- Container copy jobs copy items into a new container to change the partition key, unique keys or throughput granularity, or to adopt hierarchical partition keys. Offline copy requires stopping writes on the source; online copy requires continuous backup and all versions and deletes mode, and is finished with az cosmosdb copy complete.
Design and implement Azure Cosmos DB solutions by using AI-assisted tools
- The Azure Cosmos DB Agent Kit provides recipes to review partition keys, queries and SDK code: you supply document shapes, filters, write rates, the indexing policy, RU charges or sanitized diagnostics, never credentials. Its recommendations are suggestions: compare RU, latency and results on the same data and test outside production before applying them.
- The Azure Cosmos DB Agent Kit is installed with npx skills add AzureCosmosDB/cosmosdb-agent-kit or the host's plugin method, and verified by finding the cosmosdb-best-practices skill. It provides guidance, not access: it doesn't authenticate to Azure or query data; the Microsoft Learn MCP server serves documentation. Load only the relevant skill to avoid filling the context.
2. Secure, optimize, and deploy database solutions
30–35%Implement database security controls
- To enforce Microsoft Entra ID you set disableLocalAuth to true (az resource update or Bicep) and validate that a key-based connection fails; applications use a managed identity and DefaultAzureCredential. If keys remain, rotate them by first switching to the other key, and safe key rotation blocks regenerating or disabling keys that are still in use.
- The data plane uses native roles (Cosmos DB Built-in Data Reader and Data Contributor, or custom roles with dataActions) assigned with az cosmosdb sql role assignment create at account, database or container scope. notDataActions isn't supported, readMetadata is always required and SDK queries need executeQuery and readChangeFeed. Azure roles such as Cosmos DB Operator only manage.
- Network access to Azure Cosmos DB for NoSQL is secured with an IP firewall (ipRules), service endpoints with virtual network rules, and private endpoints with Private Link and the privatelink.documents.azure.com zone. Setting publicNetworkAccess to Disabled blocks all public and virtual network traffic. Once a service endpoint is enabled, the source is no longer the public IP.
- Dynamic Data Masking masks policy paths server-side at query time with the Default, MaskSubstring or Email strategies, without changing stored data. It requires Microsoft Entra ID (not keys), and unmasking is granted by the items/unmask action, included in Data Contributor but not Data Reader. Excluded paths require including / and the change feed requires unmask.
Implement availability and recovery solutions
- Periodic backup keeps snapshots at a configurable interval and is restored to a new account only through a support request. Continuous backup gives self-service point-in-time restore to a new account or, for deleted databases and containers, into the same account. Migrating from periodic to continuous is one-way, and a restore does not bring back firewall, private endpoint or role assignment settings.
- The SDK sends reads to the first available region in its preference list (ApplicationPreferredRegions, or ApplicationRegion to order regions by proximity) and never reads from regions missing from that list. With multi-region writes, Strong consistency is not supported and conflicts are resolved by Last Write Wins, on _ts or a custom numeric path, or by a custom policy that can only be set when the container is created.
- Per-partition automatic failover (PPAF) moves only the affected partitions of a single-write-region NoSQL account to another region, following the failover priority order, and fails back on its own. It needs at least one read region, provisioned throughput and a supported SDK; it doesn't support Bounded Staleness, and you disable it to run partition merge or take a region offline.
Optimize and remediate database performance
- To lower a query's RU charge, filter on the partition key, avoid WHERE functions that don't use the index (UPPER, LOWER, GetCurrentTimestamp) and add composite indexes with equality properties first and at most one range filter last. When filtering and sorting on different properties, add the filtered ones to ORDER BY; with JOIN, filter each array in a subquery.
- Query metrics show where time goes (TotalTime, IndexLookupTime, DocumentLoadTime, RuntimeExecutionTime) and whether a scan happened: if Retrieved Document Count exceeds Output Document Count, part of the query didn't use the index. In .NET, Diagnostics.GetQueryMetrics() returns cumulative and per-partition metrics for each page, and they must be aggregated across all round trips.
- Index metrics are enabled per query with PopulateIndexMetrics (populate_index_metrics in Python) and show the utilized and potential single and composite indexes. Potential indexes are recommendations to add and verify, and the high or low impact score depends only on the query shape. They add overhead, so use them only for debugging.
- To tell whether end-to-end latency comes from the service, compare the Server Side Latency Direct or Gateway metric, by connection mode, with what the client measures. SDK diagnostics separate network time (Transit time versus BELatencyInMs), client CPU and thread starvation, and in .NET CosmosThresholdOptions automatically logs operations slower than your objective.
- Azure Monitor supports metric alerts (for example Normalized RU Consumption, or Total Request Units filtered by StatusCode 429), activity log alerts (key rotation) and log search alerts over Log Analytics tables such as CDBPartitionKeyStatistics. Metrics are collected without configuration, while logs need a diagnostic setting. An action group defines the email, SMS or function actions.
Implement Fleet management and monitoring across multiple accounts and subscriptions
- A fleet groups Azure Cosmos DB accounts (one per tenant) into fleetspaces. A fleetspace pool shares RU/s across accounts in different subscriptions and resource groups: each resource uses its dedicated RU/s first and then draws from the pool. All accounts need the same regions and write mode, and pooling pays off with many tenants whose traffic varies.
- Fleet analytics exports hourly usage, provisioning and cost data for every account in a fleet to a Microsoft Fabric lakehouse (OneLake) or ADLS Gen2, as star-schema Delta Lake tables (FactRequestHourly, DimResource and others). You must grant the Cosmos DB Fleet Analytics service principal write access; it is meant for trends, not individual requests.
3. Implement AI and analytics capabilities in database solutions
20–25%Design and implement AI retrieval
- Full-text search needs a full-text policy (fullTextPaths with path and language) and a fullTextIndexes entry on that path. FullTextContains, FullTextContainsAll and FullTextContainsAny filter in WHERE and support fuzzy search with an edit distance, while FullTextScore ranks by BM25 only in ORDER BY RANK or RRF and can't be projected. Facets come from GROUP BY and COUNT.
- The vector embedding policy declares the path, data type (float32, float16, int8 or uint8), dimensions and distance function (cosine, dotproduct or euclidean). The vector index can be flat (exact), quantizedFlat (compressed brute force) or diskANN (approximate and efficient at scale); exclude the vector path from the regular index, and these settings aren't changed in place but dropped and re-added.
- Sharded DiskANN sets vectorIndexShardKey on the diskANN index to build one index per value of a property (tenant, category or the first level of a hierarchical key), lowering RU and latency and improving recall; queries must filter that value in WHERE. Without a shard key there is one index per physical partition. Scope searches to the partition key and avoid fan-out to every partition.
- Vector search is enabled on the account (EnableNoSQLVectorSearch) and runs with VectorDistance in ORDER BY, always with TOP N to avoid inflated RUs and latency. VectorDistance takes a boolean that forces brute force and an options object (distanceFunction, dataType, multipliers, filterPriority); it combines with WHERE filters and partition key scoping. diskANN is approximate and results can vary slightly between runs.
- Hybrid search combines VectorDistance (semantic meaning) and FullTextScore (BM25 keyword matching) with the RRF function in an ORDER BY RANK clause. It needs a vector policy, a full-text policy, a vector index and a full-text index. RRF takes optional weights in the order of its functions, can't be projected or combined with ORDER BY on other properties, and accepts WHERE filters.
Design and implement agent memory stores
- Azure Cosmos DB acts as the durable agent memory store: short-term memory (turns, with TTL) and long-term memory (summaries, facts, preferences). One document per turn is recommended; the partition key can be a GUID (write-heavy logging), threadId, or a hierarchical tenantId/threadId key for multitenancy. The change feed with Durable Functions processes new turns to derive memories.
- Conversation state is stored as one item per turn partitioned by threadId and read with TOP @k, filtering on the thread and ordering by timestamp (or _ts) descending. Item-level TTL expires individual turns; a transactional batch updates a turn and the thread metadata atomically in the same logical partition, and Session consistency needs a reused CosmosClient to read your own writes.
- Semantic memory stores embeddings per turn or per fact and retrieves them with VectorDistance in ORDER BY with TOP, filtered by thread, user or tenant. diskANN suits large scale and quantizedFlat small or filtered sets; vectorIndexShardKey builds one index per tenant. Hybrid search fuses VectorDistance and FullTextScore with RRF.
Design and implement operational analytics on Azure Cosmos DB
- Cosmos DB in Microsoft Fabric uses the same engine as Azure Cosmos DB for NoSQL but is managed inside Fabric: it mirrors data to OneLake automatically, bills in capacity units, supports only Microsoft Entra ID and Gateway mode, and uses autoscale in one region. For multi-region writes, serverless or stored procedures, use Azure Cosmos DB and mirror it into Fabric.
- Mirroring replicates an Azure Cosmos DB for NoSQL database to OneLake in Delta format without consuming RUs or using the change feed. It requires continuous backup and connects with read-write keys or Microsoft Entra ID (readMetadata and readAnalytics). Monitor replication shows status and last refresh time; restarting replication reseeds everything from scratch.
- In the SQL analytics endpoint each mirrored container is a read-only table, and nested data arrives as JSON strings expanded with OPENJSON and CROSS APPLY or OUTER APPLY, with or without a WITH clause. For Spark, a lakehouse shortcut to the mirrored database enables notebooks without touching the account. Joins across mirrored databases use three-part names.
- The Cosmos DB Spark connector (format cosmos.oltp) connects directly to the Cosmos DB endpoint, unlike reading the mirrored copy in OneLake, and supports low-latency reverse ETL; its writes consume RUs. The Catalog API (CosmosCatalog) creates containers and enables spark.sql, and spark.cosmos.write.strategy selects ItemOverwrite or ItemPatch. Cosmos DB in Fabric uses AccessToken auth and Gateway mode.