πŸ”’ 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 6 of 11 55%
6 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 ⏱ ~14 min read

SDK Connectivity and Client Configuration

Set up the CosmosClient in C# and Java, choose between account key and Entra ID authentication, compare direct vs gateway connection modes, and configure preferred regions and diagnostics.

Connecting to Cosmos DB

β˜• Simple explanation

Think of the CosmosClient as a phone. You set it up once (get a phone number, connect to a network), then make as many calls as you want. You don’t buy a new phone for every call β€” that would be expensive and slow.

Direct mode is like calling someone on their personal mobile β€” fast, fewer hops. Gateway mode is like calling through a hotel switchboard β€” works everywhere, but adds a step.

The CosmosClient is the entry point for all SDK operations. It manages connections, routing, caching, and retries. Key design principles:

  • Singleton pattern: Create one instance per account and reuse it for the lifetime of your application. The client is thread-safe.
  • Connection mode: Direct (TCP) for lowest latency, or Gateway (HTTPS) when firewall rules restrict ports.
  • Authentication: Account key (simple) or Microsoft Entra ID (RBAC-based, more secure).
  • Region awareness: Configure preferred regions for multi-region accounts.

Creating the CosmosClient

C# (.NET SDK)

// βœ… Singleton pattern β€” create once, reuse everywhere
CosmosClient cosmosClient = new CosmosClient(
    accountEndpoint: "https://novasaas.documents.azure.com:443/",
    authKeyOrResourceToken: "<your-account-key>",
    clientOptions: new CosmosClientOptions
    {
        ApplicationRegion = Regions.AustraliaEast,
        ConnectionMode = ConnectionMode.Direct,
        ConsistencyLevel = ConsistencyLevel.Session
    });

// Get references (no network call)
Database database = cosmosClient.GetDatabase("novasaas");
Container container = database.GetContainer("workitems");

Java SDK

// Singleton pattern in Java
CosmosAsyncClient client = new CosmosClientBuilder()
    .endpoint("https://novasaas.documents.azure.com:443/")
    .key("<your-account-key>")
    .preferredRegions(Arrays.asList("Australia East", "UK South"))
    .directMode()
    .consistencyLevel(ConsistencyLevel.SESSION)
    .buildAsyncClient();

CosmosAsyncDatabase database = client.getDatabase("novasaas");
CosmosAsyncContainer container = database.getContainer("workitems");

Key point: GetDatabase() and GetContainer() are local proxy objects β€” they don’t make network calls. The first actual network call happens when you read, write, or query.

Authentication: account key vs Entra ID

AspectAccount keyMicrosoft Entra ID (RBAC)
What it isA static key string (primary/secondary)OAuth tokens via Azure AD/Entra
SecurityKey in config = secret to protectToken-based, no secret in code
GranularityFull access (read/write/manage)Fine-grained roles (data reader, contributor, etc.)
RotationManual β€” regenerate and redeployAutomatic via managed identities
Best forDevelopment, quick prototypingProduction, enterprise, zero-trust
// Entra ID authentication with DefaultAzureCredential
using Azure.Identity;

CosmosClient cosmosClient = new CosmosClient(
    accountEndpoint: "https://novasaas.documents.azure.com:443/",
    tokenCredential: new DefaultAzureCredential(),
    clientOptions: new CosmosClientOptions
    {
        ConnectionMode = ConnectionMode.Direct
    });

Ravi’s mistake: Ravi hard-coded the account key in appsettings.json and pushed it to GitHub. The key was exposed for 3 hours before someone noticed. Priya mandated Entra ID with managed identity for all production services β€” no keys in code, ever.

Direct mode vs gateway mode

AspectDirect mode (default)Gateway mode
ProtocolTCP on ports 10000-20000HTTPS on port 443 only
LatencyLower β€” direct connection to backend replicasHigher β€” extra hop through the gateway
Connection countMore connections (one per replica)Fewer β€” multiplexed through gateway
Firewall friendlyRequires opening TCP port rangeβœ… Port 443 only β€” works everywhere
Best forProduction workloads needing lowest latencyRestrictive corporate firewalls, Azure Functions Consumption plan
Default in .NETβœ… Yes (Direct is default)Must be explicitly set
Metadata routingClient caches routing table, connects directly to partition replicasGateway handles all routing
// Gateway mode β€” for restricted environments
var options = new CosmosClientOptions
{
    ConnectionMode = ConnectionMode.Gateway,
    GatewayModeMaxConnectionLimit = 50
};
πŸ’‘ Exam tip: when to choose gateway mode

Direct mode is almost always better for performance. Choose gateway mode when: (1) your firewall blocks TCP ports 10000-20000, (2) you’re running in Azure Functions Consumption plan (which has limited outbound connections), or (3) you’re behind a corporate proxy that only allows HTTPS/443. The exam loves this question β€” if the scenario mentions β€œfirewall restrictions” or β€œport 443 only,” the answer is gateway mode.

Preferred regions

For multi-region accounts, configure the SDK to read from the nearest region:

// Single preferred region
var options = new CosmosClientOptions
{
    ApplicationRegion = Regions.AustraliaEast
};

// Multiple preferred regions (failover order)
var options = new CosmosClientOptions
{
    ApplicationPreferredRegions = new List<string>
    {
        Regions.AustraliaEast,
        Regions.UKSouth,
        Regions.BrazilSouth
    }
};

The SDK automatically routes reads to the nearest available region. If Australia East goes down, it fails over to UK South, then Brazil South.

Rule: Use ApplicationRegion (single region) OR ApplicationPreferredRegions (ordered list) β€” not both. Setting both throws an exception.

SDK diagnostics

When debugging performance issues, Cosmos DB diagnostics provide detailed timing:

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

// Access diagnostics
CosmosDiagnostics diagnostics = response.Diagnostics;
Console.WriteLine($"Request charge: {response.RequestCharge} RU");
Console.WriteLine($"Diagnostics: {diagnostics}");

// The diagnostics JSON includes:
// - Request latency breakdown (transport, backend, retry)
// - Region contacted
// - Number of retries
// - Partition key range ID
πŸ’‘ Exam tip: singleton is critical

The CosmosClient should be a singleton β€” one instance per Cosmos DB account for the entire application lifetime. Creating a new client per request causes: (1) TCP connection storms, (2) increased latency from connection warm-up, (3) socket exhaustion. Use dependency injection (services.AddSingleton<CosmosClient>(...)) in ASP.NET. The exam tests this pattern.

🎬 Video walkthrough

🎬 Video coming soon

SDK Connectivity β€” DP-420 Module 6

SDK Connectivity β€” DP-420 Module 6

~14 min

Flashcards

Question

Why should the CosmosClient be a singleton?

Click or press Enter to reveal answer

Answer

The CosmosClient manages TCP connections, caches routing tables, and handles retries. Creating a new client per request causes TCP connection storms, socket exhaustion, and increased latency. One instance per account, reused for the app's lifetime.

Click to flip back

Question

What protocol does Direct mode use, and what ports?

Click or press Enter to reveal answer

Answer

Direct mode uses TCP on ports 10000-20000. It connects directly to backend partition replicas, skipping the gateway hop. This gives lower latency but requires those ports to be open in your firewall.

Click to flip back

Question

When should you use Gateway mode instead of Direct mode?

Click or press Enter to reveal answer

Answer

Use Gateway mode when: (1) firewall blocks TCP ports 10000-20000, (2) running in Azure Functions Consumption plan, (3) behind a corporate proxy allowing only HTTPS/443. Gateway mode routes all traffic through port 443.

Click to flip back

Question

Can you use both ApplicationRegion and ApplicationPreferredRegions?

Click or press Enter to reveal answer

Answer

No β€” using both throws an exception. Use ApplicationRegion for a single preferred region, or ApplicationPreferredRegions for an ordered failover list. Never both.

Click to flip back

Knowledge check

Knowledge Check

Priya deploys NovaSaaS to a corporate environment where the firewall only allows outbound traffic on port 443. Which connection mode should she use?

Knowledge Check

Ravi creates a new CosmosClient for every HTTP request in his API. What problem will this cause?

Knowledge Check

Priya's app authenticates to Cosmos DB using a managed identity in production. What's the main security advantage over account keys?


Next up: SDK CRUD & Transactions β€” learn all the Create, Read, Update, Delete operations plus TransactionalBatch and optimistic concurrency with ETags.

← Previous

Relationships β€” Embedding vs Referencing

Next β†’

SDK CRUD Operations and Transactions

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.