Back to exam

DP-420 Cheatsheet

Designing and Implementing Cloud-Native Applications Using Microsoft Azure Cosmos DB

Download free PDF

Design and implement data models

Resources and access patterns

  • **Account → database → container → item** is the resource hierarchy. Containers define partitioning, indexing, unique keys and retention; provisioned throughput can belong to a database or container.
  • **Model for reads and writes**, rather than copying relational tables. Identify common filters, data read together, update frequency, growth and required transaction boundaries.
  • **Embed** bounded, closely related data read together, such as an order and its lines. **Reference** independently queried, frequently changing or unbounded relationships.
  • **Denormalization** reduces read requests but creates duplicate data to maintain. Keep an authoritative copy and propagate changes to read models with an idempotent change feed consumer.
  • **Mixed entity types** can share a container using a type discriminator and suitable partition key. Store document versions as separate items when embedded history would grow without bound.

Logical and physical partitions

  • **Logical partition:** items with the same complete partition key value. Its normal storage limit is **20 GB**, and transactions remain within it.
  • **Physical partitions** are managed by the service, each supporting up to **50 GB** and **10,000 RU/s**. Multiple logical partitions can share one physical partition.
  • **id + partition key** identifies an item. The same id can exist under different partition key values; a point read supplies both values.
  • **Partition key design** favors high cardinality, stable values and even storage and traffic distribution. A unique value is not automatically the best choice if queries need another grouping.
  • **Hot partitions** occur when one key or range dominates traffic. Raising total throughput may leave other partitions idle; inspect per-partition consumption and reconsider key distribution.

Synthetic and hierarchical keys

  • **Synthetic keys** concatenate properties into a stored value, such as deviceId plus day. Deterministic buckets preserve targeted reads while limiting long-lived partition growth.
  • **Random suffixes** spread writes but require fan-out reads unless the suffix is known. A current date alone concentrates all current writes into one hot key.
  • **Hierarchical partition keys** use ordered paths such as tenantId, userId and sessionId. Prefix filters route to the relevant subset; the full key identifies the logical partition.
  • **Tenant prefixes** can span multiple physical partitions through subpartitioning. Choose lower levels to distribute large tenants; the complete key still determines transaction scope.
  • **PartitionKeyBuilder** constructs an SDK key from hierarchical components in order. Changing an existing key definition requires a new container and migration or a supported copy workflow.

Uniqueness and data boundaries

  • **Unique key policies** enforce uniqueness within a logical partition and are defined at container creation. A company partition plus unique email permits the same email in different companies.
  • **Composite unique keys** constrain the combined tuple, not each property separately. Paths and string values are case sensitive; missing paths participate as null values.
  • **Referential integrity** is application-managed. Colocate related items under the same complete partition key when atomic updates are required; cross-container projections converge asynchronously.
  • **Item size** is limited to **2 MB**. Unbounded comments, users or version arrays can exceed this limit even when their parent relationship seems natural.

Capacity and throughput choices

  • **Request units (RUs)** express operation cost; **RU/s** expresses throughput capacity. Item size, indexes, query complexity and read consistency affect RU consumption.
  • **Manual throughput** suits steady demand. **Autoscale** adjusts provisioned RU/s between 10% of its configured maximum and that maximum; it does not scale to zero.
  • **Serverless** charges for consumed RUs and storage, fitting intermittent traffic with long idle periods. Evaluate its capacity and regional capabilities against workload requirements.
  • **Shared database throughput** forms a common pool for participating containers, without a fixed equal share per container. Dedicated container throughput isolates a workload from that pool.
  • **Provisioned cost** includes reserved capacity even when idle, storage and regional replication. Free-tier discounts apply to eligible accounts; choose database or container throughput deliberately.
  • **Throughput migration** switches manual and autoscale modes; a separate update sets the desired maximum. Burst capacity can absorb brief spikes from accumulated unused capacity, without replacing sustained provisioning.

SQL projection, arrays and aggregates

  • **SELECT** projects properties; **SELECT VALUE** returns the expression itself. Use aliases and **WHERE** filters to return only the required items and fields.
  • **JOIN x IN c.array** expands an array inside each item. It does not join containers; multiple array joins form a cross product and an empty array removes that combination.
  • **ARRAY_CONTAINS** tests membership; its third argument enables partial object matching. **EXISTS** with a correlated subquery tests whether any array element meets a condition.
  • **ARRAY_LENGTH** counts array elements. **COUNT**, **SUM** and **AVG** aggregate matching rows; **GROUP BY** creates groups. Filter joined elements before aggregation when the condition applies to each element.
  • **TOP** limits results. Add **ORDER BY ... DESC** for the greatest values; ascending is the default. Define tie-break ordering when predictable ranking matters.
  • **IS_NUMBER**, **IS_DEFINED** and **IS_NULL** distinguish types, absent properties and explicit null. A quoted number is a string; missing and null are different states.

Parameters, dates and pagination

  • **Parameterized queries** bind values such as @accountNumber through QueryDefinition.WithParameter. Avoid concatenating user input into SQL text.
  • **GetCurrentDateTime()** returns the current UTC ISO 8601 string; **GetCurrentTimestamp()** returns a numeric epoch timestamp. Store dates consistently for comparisons.
  • **DateTimePart** extracts date components; **DateTimeFromParts** can construct a period boundary such as the first day of a year. Keep date formats and time zones consistent.
  • **FeedIterator** reads query pages until HasMoreResults is false. **MaxItemCount** is an upper bound, so pages can contain fewer items or be empty.
  • **Continuation tokens** bookmark progress. To supply a fixed-size application page, collect service pages until the requested count or exhaustion, retaining any buffered remainder and continuation state.

SDK operations and concurrency

  • **CosmosClient** should be long lived and reused. Prefer asynchronous APIs, colocate compute with its database region and avoid repeated client creation or metadata lookups.
  • **Create** inserts a new item; **replace** overwrites an existing item; **upsert** creates or replaces. **Patch** changes selected paths using operations such as set, replace, increment and remove.
  • **Optimistic concurrency** uses the last-read _etag with IfMatchEtag. A mismatched version returns **412 Precondition Failed**; reread and reconcile before retrying.
  • **TransactionalBatch** groups point operations for one container and one complete partition key. All succeed or all roll back; attach ETag conditions to protect individual writes.
  • **Bulk execution** improves throughput across many independent operations; it does not make them one transaction. Use transactional batch when atomicity is required.
  • **RequestCharge** on item responses gives point-operation cost. Sum FeedResponse.RequestCharge across all query pages to obtain total query RUs.

Server-side JavaScript

  • **Stored procedures** execute JavaScript transactionally within one logical partition. Use getContext(), the collection API and callbacks; exceptions roll back the transaction.
  • **Bounded execution** limits server-side work. A false return from a collection operation means it was not accepted; stop or arrange a resumable design instead of assuming completion.
  • **Pre-triggers** validate or modify the request before an operation; **post-triggers** run afterward within the transaction. Register the trigger and explicitly include its name in the request.
  • **Triggers are opt-in**, so they are not a universal security boundary. **UDFs** compute scalar values in queries; prefer built-in functions where they meet the need.

Design and implement data distribution

Five consistency levels

  • **Strong** returns the latest committed version globally. **Bounded staleness** preserves order while bounding lag by time or versions.
  • **Session** provides read-your-writes and monotonic reads within a session. **Consistent prefix** preserves write order without a bounded lag; **eventual** guarantees convergence without ordering.
  • **Consistency order:** strong → bounded staleness → session → consistent prefix → eventual. Request-level settings can weaken reads below the account default, not strengthen them.
  • **Writes follow account replication guarantees** even when a request selects weaker read consistency. Strong and bounded-staleness reads generally cost twice the RUs of session or weaker reads.
  • **Session tokens** carry partition-scoped progress. SDK clients manage them automatically; share the relevant token through a trusted user session when reads move across devices or app instances.

Regions, routing and failover

  • **Single-write accounts** accept writes in one region and replicate to read regions. **Multi-region writes** permit local writes in configured regions and require conflict resolution.
  • **ApplicationRegion** or a preferred region list guides SDK routing with endpoint discovery. Region availability affects the chosen endpoint; the account endpoint remains stable across failover.
  • **Service-managed failover** promotes an available region according to failover priority for a single-write account. Preferred client read regions and server failover priority serve different purposes.
  • **Manual failover** changes the priority-zero write region, for example with az cosmosdb failover-priority-change. Merely adding a read region does not enable multi-region writes.
  • **Regional resilience** needs data replicas, client retry behavior and reachable application instances. More regions add cost; cross-region coordination can increase strong-consistency write latency.

Multi-region conflict handling

  • **Last writer wins (LWW)** uses _ts by default. A custom numeric resolution path can select the greatest business value, such as a policy year.
  • **Custom resolution** uses application semantics implemented by a merge stored procedure. Create the container with its conflict policy; policy changes can require a new container and migration.
  • **Conflict records** remain for application handling when custom resolution is absent or fails. Poll the conflicts feed explicitly; it is distinct from the change feed.
  • **Merge parameters** distinguish incomingItem, existingItem and conflictingItems. A null incomingItem represents a delete; isTombstone indicates a conflict with a previously deleted item.
  • **Regional testing** should deliberately route a client to the target region and verify diagnostics. Testing single-write promotion additionally requires a planned failover; preferred reads alone do not move the writer.

Integrate an Azure Cosmos DB solution

Change feed semantics

  • **Latest-version change feed** supplies created and updated items with their properties, rather than a field-level diff. It does not expose ordinary hard deletes or guarantee every intermediate update.
  • **Ordering** is guaranteed within a partition key value, not globally across the container. Design handlers for **at-least-once** delivery and make side effects idempotent.
  • **Soft deletion** writes a flag such as IsDeleted before eventual removal. Keep tombstones long enough for consumers to observe them; do not rely on TTL deletion as a latest-version feed event.
  • **All versions and deletes mode** is a separate capability with its own prerequisites and retention constraints. Choose the feed mode explicitly when every version or delete must be observed.
  • **Materialized views** maintained from the feed serve aggregates or alternate partition keys cheaply. Updates across source and projection containers are asynchronous, so plan replay and reconciliation.

Processors, leases and Functions

  • **Change feed processor** coordinates workers and checkpoints through a lease container. Workers in one group share the processor name and lease configuration, with unique instance names.
  • **Independent consumers** need separate lease namespaces, such as different lease prefixes. Sharing a consumer group distributes changes among workers rather than delivering every change to each worker.
  • **Pull model** makes the app responsible for reading and persisting continuation tokens. Use **FeedRange** to divide work across parallel readers and handle range changes.
  • **Azure Functions Cosmos DB trigger** wraps change feed processing. FeedPollDelay controls polling delay after draining changes; batch size and checkpoint settings govern different behaviors.
  • **Change feed estimator** measures pending work. Investigate worker CPU, handler time, source and lease RU throttling, and partition distribution before scaling processors.

Operational and analytical paths

  • **Synapse Link** exposes a container analytical store separately from transactional operations. Enable the account capability and analytical store on the container for this integration.
  • **cosmos.olap** reads analytical data with supported Synapse Spark integration. **cosmos.oltp** uses the transactional path and its throughput for operational reads and writes.
  • **Serverless SQL OPENROWSET** can query the analytical store with the CosmosDB provider. Store reusable secrets in a scoped credential; on-demand compute is charged when queries run.
  • **Analytical TTL** controls analytical retention independently of transactional TTL. Schema inference and analytical-store property or nesting limits can affect which fields appear; validate projected data.

Search, streams and ingestion

  • **Azure AI Search** uses a Cosmos DB data source, search index and indexer. Map fields and schedule incremental ingestion; the search index is separate from the Cosmos DB indexing policy.
  • **Searchable** enables text search, **filterable** enables exact filters, and **retrievable** permits a field in results. Wildcard, prefix and regular-expression syntax differs from analyzer configuration.
  • **Data Factory Copy** supports scheduled ingestion, including insert and upsert. Mapping data flow write throughput budget controls allocated write RUs; batch size controls objects per batch.
  • **Stream Analytics** processes event streams and can write JSON to Cosmos DB. A stream input differs from reference data: stage reference snapshots in a supported reference-data source.
  • **Kafka source connector** reads Cosmos DB into Kafka; a **sink connector** writes Kafka messages to Cosmos DB. Match topic mappings, key/value converters and schemas to the message format; Avro is binary.
  • **IoT Hub routing** uses a Cosmos DB custom endpoint plus routing rules to send matching telemetry. Configure endpoint identity permissions and a partition strategy for device traffic.

Optimize an Azure Cosmos DB solution

Indexing policies and paths

  • **Consistent indexing** updates indexes with item writes. **None** disables indexing for key-value or bulk-load scenarios; restore consistent mode and await index transformation before indexed queries.
  • **Opt-out:** include /* and exclude unused paths. **Opt-in:** exclude /* and explicitly include queried paths. More specific paths take precedence.
  • **Index paths:** `/?` targets a scalar value, `/*` targets descendants, and `/[]/` addresses array elements. Match property names and nesting exactly.
  • **Range indexes** support equality, range predicates and single-property ordering. Excluding unused, frequently updated properties reduces index storage and write cost.
  • **TTL requires consistent indexing.** A key-value container needing TTL can keep consistent mode, no included paths and an excluded /* path instead of using indexingMode none.

Composite and spatial indexes

  • **Composite indexes** support ORDER BY on multiple properties. Match property sequence and sort direction; reversing every direction is supported by the same index.
  • **Equality fields first, range field last** is a useful composite filter pattern. Multiple range filters can benefit from separate composites sharing the equality prefix.
  • **Equality plus ordering** can benefit from adding the equality field to ORDER BY, followed by the sorted field, with a matching composite index.
  • **Spatial indexes** cover supported GeoJSON shapes such as Point, LineString, Polygon and MultiPolygon. ST_DISTANCE, ST_WITHIN and ST_INTERSECTS express spatial predicates.
  • **Index changes** trade write work and storage for query efficiency. Compare request charge and index metrics with representative queries; an extra index is not automatically a saving.

Query cost and client performance

  • **Point reads** use id and the full partition key without SQL execution. A query filtering the same fields remains a query and has different cost.
  • **Partition-key equality** targets one logical partition. Filters on key prefixes or a finite IN list can reduce routing scope; unrelated filters still fan out.
  • **Query metrics** separate retrieved and output item counts, index lookup and execution time. High retrieved counts with few results suggest inefficient filtering or scans.
  • **MaxConcurrency** controls parallel partition requests; **MaxBufferedItemCount** controls client buffering. Tune latency and memory with representative load; lower concurrency does not inherently lower total RUs.
  • **Projection** reduces returned payload. Large scans, joins and repeated aggregations may need a better data model, subqueries or a precomputed view rather than more throughput.

Integrated cache and connection modes

  • **Integrated cache** runs on a dedicated gateway with item and query caches. Cache hits consume **zero RUs**, but gateway compute still costs money.
  • **Cache access** requires the dedicated gateway endpoint, gateway connection mode, and supported session or eventual request consistency. Stronger reads bypass it.
  • **MaxIntegratedCacheStaleness** sets acceptable cached-data age, not guaranteed residency. Cache entries can be evicted; repeated eligible reads and sufficient memory improve hit rates.
  • **Gateway mode** sends HTTPS requests through a gateway, simplifying restricted-network connectivity. **Direct mode** connects to replicas over TCP and generally minimizes data-access overhead.
  • **HTTP 429** signals exhausted available throughput. Honor RetryAfter and bounded SDK retries; reduce query/write cost, smooth bursts or raise capacity when demand remains too high.

Maintain an Azure Cosmos DB solution

Time to live and retention

  • **DefaultTimeToLive = null** or absent disables TTL for the container, so item ttl values have no effect. **-1** enables TTL with no default expiration.
  • **Positive container TTL** sets default lifetime in seconds. An item ttl overrides it; item **-1** prevents that item from expiring while TTL is enabled.
  • **Expiration starts at _ts**, the last modification time, rather than the last read. An update resets the countdown; 3,600 means one hour and 7,200 means two hours.
  • **Expired items** disappear from query results before background physical cleanup necessarily finishes. Disable container TTL when all per-item expirations must be ignored.

Metrics, logs and alerts

  • **Normalized RU consumption** shows usage relative to available RU/s. Break it down by physical partition and region to find hot partitions hidden by an account average.
  • **Total Request Units** measures consumed RUs; **Provisioned Throughput** describes configured capacity. Inspect status-code dimensions and 429 rates alongside latency to assess throttling.
  • **Data-plane request logs** expose operation, duration, status and request charge. In Log Analytics, filter the time range, aggregate RU charge by operation or query, then sort descending.
  • **CDBControlPlaneRequests** records management changes, such as throughput, containers and regional configuration. Diagnostic settings route logs to Log Analytics; enable full-text query diagnostics only when needed.
  • **Diagnostic detail** separates query text from caller identity. Full-text query diagnostics reveal query text; control-plane audit settings capture principal details for management changes.
  • **Metric alerts** detect utilization thresholds; **log alerts** evaluate KQL. An action group can invoke an Azure Function. A Cosmos DB trigger responds to item changes, not RU thresholds.

Identity and least privilege

  • **Microsoft Entra ID** and managed identities avoid application account keys. Assign native Cosmos DB data roles at the narrowest suitable account, database or container scope.
  • **Built-in Data Reader** reads items and queries. **Built-in Data Contributor** writes items as well; use a custom native data role when fewer operations are required.
  • **Management-plane roles** authorize resource administration. **Cosmos DB Operator** manages supported account resources without key access or item data access; data roles do not replace management roles.
  • **disableLocalAuth** disables key-based authentication. **disableKeyBasedMetadataWriteAccess** blocks key-authenticated metadata writes; use authorized ARM operations for resource creation and management.
  • **Native data-role definitions** are managed through Azure management permissions such as sqlRoleDefinitions/write. Scope a custom Azure role narrowly when delegating role-definition administration.
  • **Account keys** belong in Key Vault secrets. Rotate primary and secondary keys in stages for applications still using them; resource tokens can delegate bounded data access to supported resources.

Network access and encryption

  • **Private endpoints** expose private IPs for account access from a VNet or connected on-premises network. Configure private DNS, routing and public network access together.
  • **Service endpoints** authorize selected VNet subnets against the service public endpoint. Peering does not automatically authorize a peered subnet; add the required subnet rules.
  • **Network access and authorization** are separate checks. A private endpoint alone does not limit access to one VM; use supported network controls and identity permissions for that requirement.
  • **Encryption at rest** is automatic. Account-level customer-managed keys add Key Vault key control; grant the relevant identity Get, Wrap Key and Unwrap Key when using access policies.
  • **Key rotation** needs continued access to old and new key versions. A versionless Key Vault key URI supports automatic adoption; a user-assigned managed identity can be shared by multiple accounts.

Always Encrypted

  • **Always Encrypted** encrypts selected JSON properties in the client SDK before they reach the service. It protects plaintext from the database service, beyond storage encryption.
  • **Key sequence:** create a Key Vault wrapping key, create a wrapped data encryption key in the Cosmos DB database, then create the container with a client encryption policy.
  • **Encryption policy** belongs to the container and maps property paths to encryption keys and types. The policy is immutable; wrapped data encryption keys are database resources.
  • **Deterministic encryption** supports equality comparisons but reveals repeated values. **Randomized encryption** conceals repetitions and does not support filtering on encrypted values.
  • **Encrypted queries** need supported SDK parameter handling. Range predicates and ORDER BY on encrypted values are unsuitable; project away properties the caller cannot decrypt.

Backup, recovery and deployment

  • **Periodic backup** uses an interval and retention window. Restore is support-assisted; interval affects potential data loss. Retention divided by interval estimates retained copies, with charges beyond the included allowance.
  • **Continuous backup** enables self-service point-in-time restore within its configured tier. Identify the deletion event and select a timestamp just before it; the latest restorable time serves a different purpose.
  • **Restore validation** includes data, containers, stored procedures, triggers, UDFs, roles and networking. Do not assume every setting or server-side artifact is included in a chosen restore path.
  • **ARM and Bicep** define account locations, capabilities, database throughput and container policies. Incremental deployment preserves resources omitted from the template but reapplies declared resource properties.
  • **Container resource settings** include indexingPolicy, uniqueKeyPolicy, conflictResolutionPolicy and analyticalStorageTtl. Partition key definition version 2 supports large partition key values.
  • **Cosmos DB Emulator** supports local and CI integration tests without a cloud account. Its default NoSQL endpoint is https://localhost:8081 with a well-known development key; validate feature support for the emulator build.
  • **.NET Aspire integration** can connect an app to Cosmos DB or an emulator for development and CI. Keep secrets outside source control and verify regional performance in Azure rather than inferring it from emulator tests.