πŸ”’ Guided

Pre-launch preview. Authorised access only.

Incorrect code

Guided by A Guide to Cloud
Explore AB-900 AI-901 aws-aif-c01
Guided DP-420 Domain 1
Domain 1 β€” Module 7 of 11 64%
7 of 28 overall

DP-420 Study Guide

Domain 1: Design and Implement Data Models

  • Cosmos DB β€” The Big Picture Free
  • Designing Your Data Model Free
  • Partition Key Strategy Free
  • Synthetic and Hierarchical Partition Keys Free
  • Relationships β€” Embedding vs Referencing Free
  • SDK Connectivity and Client Configuration Free
  • SDK CRUD Operations and Transactions Free
  • SQL Queries in Cosmos DB Free
  • SDK Query Pagination and LINQ Free
  • Server-Side Programming Free
  • Transactions in Practice Free

Domain 2: Design and Implement Data Distribution

  • Global Replication and Failover
  • Consistency Levels: Five Choices, Real Trade-Offs
  • Multi-Region Writes and Conflict Resolution

Domain 3: Integrate and Move Data

  • Change Feed with Azure Functions and Processors
  • Analytical Workloads: Synapse Link and Fabric Mirroring
  • Data Movement: ADF, Kafka, and Spark Connectors

Domain 4: Optimize Query and Operation Performance

  • Indexing Policies: Range, Spatial, and Composite
  • Request Units and Query Cost Optimization
  • Integrated Cache and Dedicated Gateway
  • Change Feed Patterns: Materialized Views and Estimator

Domain 5: Maintain an Azure Cosmos DB Solution

  • Monitoring: Metrics, Logs, and Alerts
  • Backup and Restore: Periodic vs Continuous
  • Network Security: Firewalls, VNets, and Private Endpoints
  • Data Security: Encryption, Keys, and RBAC
  • Cost Optimization: Throughput Modes and RU Strategy
  • DevOps: Infrastructure as Code and Deployments
  • Exam Strategy and Cross-Domain Review

DP-420 Study Guide

Domain 1: Design and Implement Data Models

  • Cosmos DB β€” The Big Picture Free
  • Designing Your Data Model Free
  • Partition Key Strategy Free
  • Synthetic and Hierarchical Partition Keys Free
  • Relationships β€” Embedding vs Referencing Free
  • SDK Connectivity and Client Configuration Free
  • SDK CRUD Operations and Transactions Free
  • SQL Queries in Cosmos DB Free
  • SDK Query Pagination and LINQ Free
  • Server-Side Programming Free
  • Transactions in Practice Free

Domain 2: Design and Implement Data Distribution

  • Global Replication and Failover
  • Consistency Levels: Five Choices, Real Trade-Offs
  • Multi-Region Writes and Conflict Resolution

Domain 3: Integrate and Move Data

  • Change Feed with Azure Functions and Processors
  • Analytical Workloads: Synapse Link and Fabric Mirroring
  • Data Movement: ADF, Kafka, and Spark Connectors

Domain 4: Optimize Query and Operation Performance

  • Indexing Policies: Range, Spatial, and Composite
  • Request Units and Query Cost Optimization
  • Integrated Cache and Dedicated Gateway
  • Change Feed Patterns: Materialized Views and Estimator

Domain 5: Maintain an Azure Cosmos DB Solution

  • Monitoring: Metrics, Logs, and Alerts
  • Backup and Restore: Periodic vs Continuous
  • Network Security: Firewalls, VNets, and Private Endpoints
  • Data Security: Encryption, Keys, and RBAC
  • Cost Optimization: Throughput Modes and RU Strategy
  • DevOps: Infrastructure as Code and Deployments
  • Exam Strategy and Cross-Domain Review
Domain 1: Design and Implement Data Models Free ⏱ ~18 min read

SDK CRUD Operations and Transactions

Master all Cosmos DB data operations: Create, Read, Upsert, Replace, Delete, Patch, optimistic concurrency with ETags, TransactionalBatch, bulk mode, and 429 throttling with automatic retries.

CRUD in Cosmos DB

β˜• Simple explanation

Think of Cosmos DB as a smart filing drawer. You can: Create (add a new folder), Read (pull out a specific folder by its label), Upsert (add or update β€” β€œif it exists, replace; if not, create”), Replace (swap the entire folder), Delete (remove it), and Patch (change just one page without touching the rest).

The real superpower is TransactionalBatch β€” do multiple operations as one atomic action: either they all succeed, or none do.

The Cosmos DB SDK provides six core item operations:

  • CreateItemAsync: Insert a new item. Fails with 409 (Conflict) if the id + partition key already exists.
  • ReadItemAsync: Point read by id + partition key. The cheapest operation (~1 RU for 1 KB).
  • UpsertItemAsync: Insert or replace. If the item exists, it’s overwritten; if not, it’s created.
  • ReplaceItemAsync: Replace an existing item. Fails with 404 if the item doesn’t exist.
  • DeleteItemAsync: Remove an item. Fails with 404 if the item doesn’t exist.
  • PatchItemAsync: Partial update β€” modify specific properties without replacing the entire document.

All CRUD operations in C#

Create

var project = new ProjectItem
{
    Id = "proj-001",
    TenantId = "tenant-abc",
    Type = "project",
    Name = "Website Redesign",
    Status = "active"
};

ItemResponse<ProjectItem> response = await container.CreateItemAsync(
    project,
    new PartitionKey("tenant-abc"));

Console.WriteLine($"Created. RU charge: {response.RequestCharge}");
// Fails with 409 Conflict if proj-001 already exists in this partition

Read (point read)

ItemResponse<ProjectItem> response = await container.ReadItemAsync<ProjectItem>(
    id: "proj-001",
    partitionKey: new PartitionKey("tenant-abc"));

ProjectItem project = response.Resource;
Console.WriteLine($"Read '{project.Name}'. RU: {response.RequestCharge}");
// ~1 RU for a 1 KB item β€” the cheapest operation

Upsert

project.Status = "completed";

ItemResponse<ProjectItem> response = await container.UpsertItemAsync(
    project,
    new PartitionKey("tenant-abc"));
// If proj-001 exists β†’ replaced. If not β†’ created. No error either way.

Replace

project.Name = "Website Redesign v2";

ItemResponse<ProjectItem> response = await container.ReplaceItemAsync(
    project,
    id: "proj-001",
    partitionKey: new PartitionKey("tenant-abc"));
// Fails with 404 if the item doesn't exist

Delete

ItemResponse<ProjectItem> response = await container.DeleteItemAsync<ProjectItem>(
    id: "proj-001",
    partitionKey: new PartitionKey("tenant-abc"));
// Fails with 404 if the item doesn't exist

Patch operations

Patch lets you modify specific properties without reading and replacing the entire document:

// Patch: update status and increment a counter
ItemResponse<ProjectItem> response = await container.PatchItemAsync<ProjectItem>(
    id: "proj-001",
    partitionKey: new PartitionKey("tenant-abc"),
    patchOperations: new[]
    {
        PatchOperation.Set("/status", "in-review"),       // Set a value
        PatchOperation.Add("/tags/-", "urgent"),           // Append to array
        PatchOperation.Replace("/name", "Final Design"),   // Replace a value
        PatchOperation.Remove("/tempFlag"),                // Remove a property
        PatchOperation.Increment("/viewCount", 1)          // Increment number
    });
Patch operationWhat it does
SetSets a property value (creates it if missing)
AddAdds to an array (/- = append) or creates a new property
ReplaceReplaces an existing property (fails if missing)
RemoveRemoves a property
IncrementIncrements a numeric value (atomic β€” no read-modify-write race)
MoveMoves a property from one path to another within the document

Why Patch matters: Without Patch, updating one field means reading the entire document, changing it in memory, and replacing it β€” 3 operations and a concurrency risk. Patch does it in 1 operation.

Optimistic concurrency with ETags

Every Cosmos DB item has an _etag property that changes with every update. Use it to prevent lost updates:

// Step 1: Read the item (get current ETag)
ItemResponse<ProjectItem> response = await container.ReadItemAsync<ProjectItem>(
    "proj-001", new PartitionKey("tenant-abc"));

string etag = response.ETag;

// Step 2: Replace with ETag check
try
{
    ProjectItem project = response.Resource;
    project.Status = "approved";

    await container.ReplaceItemAsync(
        project,
        "proj-001",
        new PartitionKey("tenant-abc"),
        new ItemRequestOptions { IfMatchEtag = etag });  // Only if unchanged
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.PreconditionFailed)
{
    // 412 β€” someone else modified the document. Re-read and retry.
    Console.WriteLine("Conflict! Document was modified by another user.");
}

How it works:

  1. Read the item β†’ get its _etag
  2. Send a Replace/Upsert with IfMatchEtag = etag
  3. If the ETag still matches β†’ update succeeds
  4. If someone changed the document β†’ 412 Precondition Failed β†’ re-read and retry
πŸ’‘ Exam tip: ETag and 412

The _etag is a system-generated property that acts as a version stamp. When you pass IfMatchEtag in a request, Cosmos DB compares the ETag before writing. A mismatch means someone else modified the document, and you get a 412 Precondition Failed error. This is optimistic concurrency β€” no locks, just version checks. Know the 412 status code for the exam.

TransactionalBatch

TransactionalBatch provides ACID transactions for multiple operations within a single logical partition:

var project = new ProjectItem
{
    Id = "proj-002", TenantId = "tenant-abc", Type = "project",
    Name = "Mobile App"
};

var firstTask = new TaskItem
{
    Id = "task-101", TenantId = "tenant-abc", Type = "task",
    ProjectId = "proj-002", Title = "Set up CI/CD"
};

TransactionalBatchResponse batchResponse = await container
    .CreateTransactionalBatch(new PartitionKey("tenant-abc"))
    .CreateItem(project)
    .CreateItem(firstTask)
    .PatchItem("proj-001", new[]
    {
        PatchOperation.Increment("/childProjectCount", 1)
    })
    .ExecuteAsync();

if (batchResponse.IsSuccessStatusCode)
{
    Console.WriteLine("All operations succeeded atomically.");
}
else
{
    Console.WriteLine($"Batch failed: {batchResponse.StatusCode}");
    // ALL operations rolled back β€” nothing was written
}

TransactionalBatch rules:

  • All operations must target the same logical partition (same partition key value)
  • Maximum 100 operations per batch
  • Maximum 2 MB total payload
  • All-or-nothing: if any operation fails, the entire batch is rolled back
  • Supports: Create, Read, Upsert, Replace, Delete, Patch

Bulk mode

Bulk mode optimises high-volume writes by batching requests behind the scenes:

CosmosClient bulkClient = new CosmosClient(
    endpoint, key,
    new CosmosClientOptions { AllowBulkExecution = true });

// Create many tasks concurrently β€” SDK batches them automatically
List<Task> tasks = new();
foreach (var item in itemsToInsert)
{
    tasks.Add(container.CreateItemAsync(item, new PartitionKey(item.TenantId)));
}
await Task.WhenAll(tasks);

Bulk mode is NOT transactional β€” items are written independently. Some may succeed while others fail. Use TransactionalBatch when you need atomicity.

Handling 429 throttling

When you exceed provisioned RU/s, Cosmos DB returns 429 Too Many Requests with a Retry-After header:

AspectDetail
Default retries9 retries with exponential backoff
Retry-After headerTells you how long to wait (in ms)
SDK behaviourAuto-retries transparently β€” your code often never sees the 429
Custom configCosmosClientOptions.MaxRetryAttemptsOnRateLimitedRequests = 15
Custom waitCosmosClientOptions.MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(60)
var options = new CosmosClientOptions
{
    MaxRetryAttemptsOnRateLimitedRequests = 15,
    MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromSeconds(60)
};

Ravi’s mistake: Ravi turned off retries (MaxRetryAttemptsOnRateLimitedRequests = 0) thinking it would β€œfail fast.” Instead, his app crashed with hundreds of 429 errors during peak load. The default 9 retries exist for a reason β€” they smooth out temporary spikes.

πŸ’‘ Exam tip: batch vs bulk

TransactionalBatch = ACID, same partition, max 100 ops, all-or-nothing. Bulk mode = NOT transactional, optimises throughput by batching network calls, items can be in different partitions, some may succeed while others fail. The exam loves confusing these two. If the question asks about atomicity β†’ batch. If it asks about throughput optimisation β†’ bulk.

🎬 Video walkthrough

🎬 Video coming soon

SDK CRUD & Transactions β€” DP-420 Module 7

SDK CRUD & Transactions β€” DP-420 Module 7

~18 min

Flashcards

Question

What's the difference between Upsert and Replace?

Click or press Enter to reveal answer

Answer

Upsert: if the item exists, replace it; if not, create it β€” never fails with 404. Replace: overwrites an existing item; fails with 404 if the item doesn't exist. Use Upsert when you're unsure if the item exists.

Click to flip back

Question

What HTTP status code indicates an ETag mismatch in optimistic concurrency?

Click or press Enter to reveal answer

Answer

412 Precondition Failed. This means someone modified the document between your read and your write. The IfMatchEtag condition failed. Your code should re-read the document and retry.

Click to flip back

Question

What are the limits of TransactionalBatch?

Click or press Enter to reveal answer

Answer

Same logical partition (same partition key value), maximum 100 operations, maximum 2 MB total payload, all-or-nothing (ACID). Supports Create, Read, Upsert, Replace, Delete, and Patch operations.

Click to flip back

Question

Is bulk mode transactional?

Click or press Enter to reveal answer

Answer

No. Bulk mode optimises throughput by batching network calls, but each item is written independently. Some items may succeed while others fail. For atomic multi-item writes, use TransactionalBatch instead.

Click to flip back

Question

How many times does the SDK retry 429 errors by default?

Click or press Enter to reveal answer

Answer

9 times with exponential backoff. The SDK uses the Retry-After header to determine wait time. You can customise with MaxRetryAttemptsOnRateLimitedRequests and MaxRetryWaitTimeOnRateLimitedRequests.

Click to flip back

Knowledge check

Knowledge Check

Priya needs to atomically create a project and its first task in the 'workitems' container (both in the same tenant). Which approach is correct?

Knowledge Check

Ravi and Sophie both read the same project document (ETag: 'abc123'). Ravi updates it first. What happens when Sophie tries to Replace with IfMatchEtag = 'abc123'?

Knowledge Check

Priya wants to increment a view counter on a project document without reading it first. Which operation should she use?


Next up: SQL Queries β€” learn the Cosmos DB SQL query language, including SELECT, WHERE, JOIN (intra-document only), cross-partition queries, and composite indexes.

← Previous

SDK Connectivity and Client Configuration

Next β†’

SQL Queries in Cosmos DB

Guided

I learn, I simplify, I share.

A Guide to Cloud YouTube Feedback

© 2026 Sutheesh. All rights reserved.

Guided is an independent study resource and is not affiliated with, endorsed by, or officially connected to Microsoft. Microsoft, Azure, and related trademarks are property of Microsoft Corporation. Always verify information against Microsoft Learn.