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
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
| Aspect | Account key | Microsoft Entra ID (RBAC) |
|---|---|---|
| What it is | A static key string (primary/secondary) | OAuth tokens via Azure AD/Entra |
| Security | Key in config = secret to protect | Token-based, no secret in code |
| Granularity | Full access (read/write/manage) | Fine-grained roles (data reader, contributor, etc.) |
| Rotation | Manual β regenerate and redeploy | Automatic via managed identities |
| Best for | Development, quick prototyping | Production, 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
| Aspect | Direct mode (default) | Gateway mode |
|---|---|---|
| Protocol | TCP on ports 10000-20000 | HTTPS on port 443 only |
| Latency | Lower β direct connection to backend replicas | Higher β extra hop through the gateway |
| Connection count | More connections (one per replica) | Fewer β multiplexed through gateway |
| Firewall friendly | Requires opening TCP port range | β Port 443 only β works everywhere |
| Best for | Production workloads needing lowest latency | Restrictive corporate firewalls, Azure Functions Consumption plan |
| Default in .NET | β Yes (Direct is default) | Must be explicitly set |
| Metadata routing | Client caches routing table, connects directly to partition replicas | Gateway 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 minFlashcards
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?
Ravi creates a new CosmosClient for every HTTP request in his API. What problem will this cause?
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.