Domain 1 β€” Module 6 of 11 55%
6 of 28 overall
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.

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

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.