Generated banner for Cosmosdb Best Practices
Generated logo for Cosmosdb Best Practices

Cosmosdb Best Practices

ClineOfficialCreated by cosmosdb-agent-kitDistributed by Cline

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, SDK usage, and vector search. Use when writing, reviewing, or refactoring code that interacts with Azure Cosmos DB, designing data models, optimizing queries, or implementing high-performance database operations.
— the description by cosmosdb-agent-kit

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured set of 73+ guidelines for working with Azure Cosmos DB. It covers essential topics including data modeling, partition key design, query optimization, SDK usage, indexing, throughput scaling, global distribution, monitoring, design patterns, and vector search. The content is organized into modular rule files to assist developers in writing, reviewing, and refactoring code that interacts with the database.

What it does

  • Provides specific rules for designing efficient data models and choosing partition keys.
  • Offers guidance on optimizing queries and implementing SDK patterns.
  • Details strategies for indexing, throughput management, and global distribution.
  • Includes best practices for implementing vector search and RAG patterns.
  • Supplies diagnostic and monitoring recommendations for database operations.
  • Organizes content into categorized rule files for targeted retrieval.

When to use it

  • When designing data models or selecting partition keys for Cosmos DB.
  • When writing or refactoring application code that uses the Cosmos DB SDK.
  • When optimizing query performance or indexing strategies.
  • When configuring global distribution, throughput, or scaling settings.
  • When implementing vector search or advanced design patterns.

Advantages

  • Modular structure allows for loading only relevant rules for specific tasks.
  • Covers a wide range of operational and architectural concerns.
  • Provides clear examples of incorrect and correct implementation patterns.
  • Prioritizes rules by impact to guide development decisions.

Usage examples

“How should I choose a partition key for my Cosmos DB container?”
The agent will retrieve rules from the partition- prefix to explain high-cardinality, write distribution, and query alignment.
“What are the best practices for using the Cosmos DB SDK?”
The agent will load rules from the sdk- prefix to provide guidance on singleton client usage, async APIs, and retry logic.
“How do I optimize my data model for read-heavy workloads?”
The agent will reference model- prefixed rules to explain denormalization and embedding strategies.
“What should I consider when implementing vector search in Cosmos DB?”
The agent will access vector- prefixed rules to explain embedding policies, index types, and similarity search functions.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/cline/cosmosdb-best-practices/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cosmosdb-best-practices.zip -d .agents/skills

Documentation by cosmosdb-agent-kit

Azure Cosmos DB Best Practices

Comprehensive performance optimization guide for Azure Cosmos DB applications, containing 73+ rules across 10 categories, prioritized by impact to guide automated refactoring and code generation.

73 individual rule files are in the rules/ directory, one file per rule, synced from the AzureCosmosDB/cosmosdb-agent-kit. Load only the relevant rule file(s) when answering a question — do NOT load all files at once.

When to Apply

Reference these guidelines when:

  • Designing data models for Cosmos DB

  • Choosing partition keys

  • Writing or optimizing queries

  • Implementing SDK patterns

  • Reviewing code for performance issues

  • Configuring throughput and scaling

  • Building globally distributed applications

  • Implementing vector search and RAG patterns

Rule Index

Rules are grouped by category prefix. For a given question, load files matching the relevant prefix (e.g., model-*.md for data modeling, sdk-*.md for SDK usage). See rules/_sections.md for category descriptions.

1. Data Modeling — CRITICAL (prefix: model-)
2. Partition Key Design — CRITICAL (prefix: partition-)
3. Query Optimization — HIGH (prefix: query-)
4. SDK Best Practices — HIGH (prefix: sdk-)
5. Indexing Strategies — MEDIUM-HIGH (prefix: index-)
6. Throughput & Scaling — MEDIUM (prefix: throughput-)
7. Global Distribution — MEDIUM (prefix: global-)
8. Monitoring & Diagnostics — LOW-MEDIUM (prefix: monitoring-)
9. Design Patterns — HIGH (prefix: pattern-)
10. Vector Search — HIGH (prefix: vector-)

How to Use

Each rule is a separate file under rules/. When answering a Cosmos DB question, read only the relevant rule file(s) based on the prefix matching the topic:

  • Data modeling question → read rules/model-*.md files

  • Partition key question → read rules/partition-*.md files

  • SDK/client question → read rules/sdk-*.md files

  • etc.

Each rule file contains:

  • Brief explanation of why it matters

  • Incorrect code example with explanation

  • Correct code example with explanation

  • Additional context and references

Source: AzureCosmosDB/cosmosdb-agent-kit

Files

rules/sdk-emulator-ssl.md


title: Configure SSL and connection mode for Cosmos DB Emulator impact: MEDIUM impactDescription: enables local development with all SDKs tags: sdk, emulator, ssl, local-development, certificate, gateway-mode

Configure SSL and Connection Mode for Cosmos DB Emulator

The Azure Cosmos DB Emulator uses a self-signed SSL certificate that requires special handling. Additionally, all SDKs should use Gateway connection mode with the emulator - Direct mode has known issues with the emulator's SSL certificate handling.

General Guidance (All SDKs)
SettingEmulatorProduction
Connection ModeGateway (required)Direct (recommended)
SSL ValidationDisable or import certNormal validation
Endpointhttps://localhost:8081Your account URL
KeyWell-known emulator keyYour account key

Well-known emulator key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==


.NET SDK
var options = new CosmosClientOptions
{
    ConnectionMode = ConnectionMode.Gateway,  // Required for emulator
    HttpClientFactory = () => new HttpClient(
        new HttpClientHandler
        {
            // Accept self-signed certificate from emulator
            ServerCertificateCustomValidationCallback = 
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        })
};

var client = new CosmosClient(
    "https://localhost:8081",
    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
    options
);

Python SDK
from azure.cosmos import CosmosClient
import urllib3

# Suppress SSL warnings for local development only
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Python SDK uses Gateway mode by default
client = CosmosClient(
    url="https://localhost:8081",
    credential="C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
    connection_verify=False  # Disable SSL verification for emulator
)

Node.js SDK
const { CosmosClient } = require("@azure/cosmos");

// Disable SSL verification for emulator (development only!)
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

const client = new CosmosClient({
    endpoint: "https://localhost:8081",
    key: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
    connectionPolicy: {
        connectionMode: "Gateway"  // Recommended for emulator
    }
});

Java SDK (Detailed)

When using the Azure Cosmos DB Emulator with the Java SDK, you must import the emulator's self-signed SSL certificate into the JDK truststore and use Gateway connection mode. Direct mode has persistent SSL issues with the emulator.

Problem (SSL handshake failures):

// Without certificate import, you'll see errors like:
// javax.net.ssl.SSLHandshakeException: PKIX path building failed
// sun.security.provider.certpath.SunCertPathBuilderException: 
//   unable to find valid certification path to requested target

// Direct mode fails even after certificate import:
CosmosClientBuilder builder = new CosmosClientBuilder()
    .endpoint("https://localhost:8081")
    .key("...")
    .directMode();  // Will fail with SSL errors!

Solution - Step 1: Export the emulator certificate:

# The emulator stores its certificate at this path (Windows):
# %LOCALAPPDATA%\CosmosDBEmulator\emulator-cert.cer

# Or export from Windows Certificate Manager:
# certmgr.msc → Personal → Certificates → DocumentDbEmulatorCertificate
# Right-click → All Tasks → Export → DER encoded binary X.509 (.CER)

Solution - Step 2: Import certificate into JDK truststore:

# Find your JDK path first:
# java -XshowSettings:properties -version 2>&1 | Select-String "java.home"

# Import the certificate (run as Administrator):
keytool -importcert `
    -alias cosmosemulator `
    -file "C:\Users\<username>\AppData\Local\CosmosDBEmulator\emulator-cert.cer" `
    -keystore "C:\Program Files\Eclipse Adoptium\jdk-17.0.10.7-hotspot\lib\security\cacerts" `
    -storepass changeit `
    -noprompt

# For other JDK distributions, the cacerts location varies:
# - Oracle JDK: $JAVA_HOME/lib/security/cacerts
# - Eclipse Adoptium: $JAVA_HOME/lib/security/cacerts
# - Amazon Corretto: $JAVA_HOME/lib/security/cacerts

Solution - Step 3: Use Gateway mode with the emulator:

// Gateway mode works reliably with the emulator after certificate import
CosmosClientBuilder builder = new CosmosClientBuilder()
    .endpoint("https://localhost:8081")
    .key("C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")
    .gatewayMode()  // Required for emulator!
    .consistencyLevel(ConsistencyLevel.SESSION);

CosmosClient client = builder.buildClient();
# Spring Boot application.properties for emulator:
azure:
  cosmos:
    endpoint: https://localhost:8081
    key: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==
    database: your-database
    # Note: Spring Data Cosmos uses Gateway mode by default

Alternative - Custom truststore (no admin required):

If you cannot modify the JDK's cacerts (requires administrator access), create a custom truststore instead:

# Step 1: Copy JDK's default cacerts to a local custom truststore
$jdkCacerts = "$env:JAVA_HOME\lib\security\cacerts"
Copy-Item $jdkCacerts -Destination .\custom-cacerts

# Step 2: Extract the emulator's SSL certificate
$tcpClient = New-Object System.Net.Sockets.TcpClient("localhost", 8081)
$sslStream = New-Object System.Net.Security.SslStream($tcpClient.GetStream(), $false, {$true})
$sslStream.AuthenticateAsClient("localhost")
$cert = $sslStream.RemoteCertificate
[System.IO.File]::WriteAllBytes("emulator-cert.cer", $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
$sslStream.Close(); $tcpClient.Close()

# Step 3: Import into custom truststore
keytool -importcert -alias cosmosemulator -file emulator-cert.cer `
    -keystore custom-cacerts -storepass changeit -noprompt
# Step 4: Run your app with the custom truststore
java "-Djavax.net.ssl.trustStore=custom-cacerts" `
     "-Djavax.net.ssl.trustStorePassword=changeit" `
     -jar your-app.jar

⚠️ COSMOS.EMULATOR_SSL_TRUST_ALL does NOT work with Java/Netty:

// WARNING: This property does NOT work with the Java Cosmos SDK!
// The Java SDK uses Netty with OpenSSL, which bypasses Java's SSLContext entirely.
// Setting this property has no effect — SSL handshake will still fail.
System.setProperty("COSMOS.EMULATOR_SSL_TRUST_ALL", "true");  // INEFFECTIVE!

// Also ineffective as a JVM argument:
// -DCOSMOS.EMULATOR_SSL_TRUST_ALL=true  // DOES NOT WORK

// Instead, use one of these approaches:
// 1. Import the emulator certificate into the JDK truststore (Step 2 above)
// 2. Use a custom truststore with -Djavax.net.ssl.trustStore (recommended)

Key Points:

  • Direct connection mode does not work reliably with the emulator even after certificate import

  • Gateway mode is required for local development with the Java SDK and emulator

  • COSMOS.EMULATOR_SSL_TRUST_ALL does NOT work — the Java SDK uses Netty/OpenSSL which ignores Java SSL system properties. You must import the emulator certificate into a JDK or custom truststore

  • The custom truststore approach avoids needing administrator access

  • The emulator's well-known key is: C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==

  • For production, switch back to Direct mode and use your actual Cosmos DB endpoint

Reference: Use the Azure Cosmos DB Emulator for local development

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
cosmosdb-agent-kit
Publisher
Cline (Official)
Distributed by
Cline
Source
cline/skills · skills/cosmosdb-best-practices · commit 2637846
Licence
MIT License (redistribution allowed)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by cosmosdb-agent-kit or Cline.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cosmosdb-best-practices.zip