January 22nd, 2026
0 reactions

Introducing the Azure Cosmos DB Agent Kit: Your AI Pair Programmer Just Got Smarter

Sajeetharan Sinnathurai
Principal Program Manager

The Azure Cosmos DB Agent Kit is an open-source collection of skills that teaches your AI coding assistant (GitHub Copilot, Claude Code, Gemini CLI) expert-level Azure Cosmos DB best practices.

Install with one command, get production-ready guidance instantly.

The Challenge Every Azure Cosmos DB Developer Faces

You’re building a new application with Azure Cosmos DB. You’ve got your data, you’ve got your queries, but then come the questions that keep you up at night:

  • “Is this the right partition key?”
  • “Why is my query consuming so many RUs?”
  • “Should I embed this data or reference it?”
  • “Am I going to hit a hot partition in production?”

These aren’t trivial questions. Poor decisions here can mean the difference between a blazing-fast application and one that struggles under load or worse, one that becomes prohibitively expensive to run.

Until now, getting these answers meant diving into documentation, searching Stack Overflow, or hoping someone on your team had battle-tested experience.

What if your AI coding assistant already knew the answers?

Introducing the Azure Cosmos DB Agent Kit

The Azure Cosmos DB Agent Kit is an open-source project that extends AI coding agents with deep Azure Cosmos DB expertise.

Built on the Agent Skills format, it works seamlessly with:

  • ✅ GitHub Copilot
  • ✅ Claude Code
  • ✅ Gemini CLI
  • ✅ Any Agent Skills-compatible tool

What’s Inside?

The kit includes 45+ curated rules across 8 categories, each prioritized by real-world impact:

Category What You’ll Learn
Data Modeling Embedding vs. referencing, document size limits, hierarchical data
Partition Key Design High cardinality, avoiding hot partitions, synthetic keys
Query Optimization Cross-partition queries, projection, pagination
SDK Best Practices Connection management, retry logic, async patterns
Indexing Strategies Custom policies, composite indexes, spatial indexing
Throughput & Scaling Autoscale, provisioned RUs, serverless decisions
Global Distribution Multi-region writes, consistency levels, failover
Monitoring & Diagnostics Logging, metrics, troubleshooting

Getting Started in 60 Seconds

Step 1: Install the Skill

Open your terminal and run:

npx add-skill AzureCosmosDB/cosmosdb-agent-kit

That’s it. The skill is now installed in your development environment.

Step 2: Start Coding

The skill activates automatically when you work on Azure Cosmos DB-related tasks. Just ask your AI agent naturally:

Review my Cosmos DB data model for performance issues
Help me choose a partition key for my e-commerce orders collection
Optimize this query that's consuming too many RUs
What's wrong with my Cosmos DB connection code?

Real-World Example: Building a Product Catalog

Let’s walk through a practical example. You’re building a product catalog API and want to ensure you’re following best practices from the start.

Your Initial Code

// cosmosService.js
const { CosmosClient } = require('@azure/cosmos');

const endpoint = process.env.COSMOS_ENDPOINT;
const key = process.env.COSMOS_KEY;

// ❌ Creating new client on every request
async function getProducts(category) {
    const client = new CosmosClient({ endpoint, key });
    const database = client.database('ProductCatalog');
    const container = database.container('Products');

    // ❌ Using SELECT * pulls all properties
    const query = `SELECT * FROM c WHERE c.category = '${category}'`;
    const { resources } = await container.items.query(query).fetchAll();
    return resources;
}

module.exports = { getProducts };

Ask Your AI Agent

Simply prompt: “Review this Azure Cosmos DB service code for best practices issues”

What the Agent Knows (Thanks to the Skill)

The Azure Cosmos DB Agent Kit teaches your AI agent to identify multiple issues:

  1. SDK Anti-pattern: Creating a new CosmosClient on every request wastes resources
  2. Query Optimization: SELECT * pulls unnecessary data, consuming extra RUs
  3. Security Risk: String concatenation in queries can lead to injection attacks
  4. Missing Error Handling: No retry logic for rate limiting (429 errors)

The Improved Code

// cosmosService.js
const { CosmosClient } = require('@azure/cosmos');

const endpoint = process.env.COSMOS_ENDPOINT;
const key = process.env.COSMOS_KEY;

// ✅ Singleton client instance - reuse across requests
const client = new CosmosClient({
    endpoint,
    key,
    connectionPolicy: {
        retryOptions: {
            maxRetryAttemptCount: 5,
            maxWaitTimeInSeconds: 30
        }
    }
});

const database = client.database('ProductCatalog');
const container = database.container('Products');

async function getProducts(category) {
    // ✅ Project only needed fields to reduce RU consumption
    const query = {
        query: `SELECT c.id, c.name, c.price, c.description, c.imageUrl 
                FROM c WHERE c.category = @category`,
        parameters: [{ name: '@category', value: category }]
    };

    try {
        const { resources, requestCharge } = await container.items
            .query(query)
            .fetchAll();

        // ✅ Log RU consumption for monitoring
        console.log(`Query consumed ${requestCharge} RUs`);

        return resources;
    } catch (error) {
        if (error.code === 429) {
            // ✅ Handle rate limiting gracefully
            console.warn('Rate limited, retry after:', error.retryAfterInMs);
            throw new Error('Service temporarily unavailable');
        }
        throw error;
    }
}

module.exports = { getProducts };

Choosing the Right Partition Key

One of the most critical decisions in Azure Cosmos DB is partition key selection. Let’s say you’re designing a multi-tenant SaaS application.

Ask Your Agent

“Help me choose a partition key for a multi-tenant order management system where each tenant has thousands of orders, and we frequently query orders by tenant and date range”

What the Agent Recommends

Based on the skill’s knowledge, your agent will guide you toward:

// ✅ Using Hierarchical Partition Keys for multi-tenant scenarios
const containerDefinition = {
    id: 'Orders',
    partitionKey: {
        paths: ['/tenantId', '/year'],  // Hierarchical partition key
        version: 2
    }
};

// Document structure
const order = {
    id: 'order-12345',
    tenantId: 'tenant-abc',     // First level: tenant isolation
    year: 2026,                  // Second level: time-based distribution
    orderDate: '2026-01-22T10:30:00Z',
    customerId: 'cust-789',
    items: [...],
    total: 299.99
};

Why this works:

  • Tenant isolation: Queries for a single tenant stay within partition boundaries
  • Avoids hot partitions: Orders distribute across time-based partitions
  • Scales beyond 20GB: Hierarchical keys overcome single partition limits
  • Efficient range queries: Date-range queries within a tenant are optimized

The Skill Structure

Curious how the skill works under the hood? Each skill contains:

skills/cosmosdb-best-practices/
├── SKILL.md          # Triggers activation, describes capabilities
├── AGENTS.md         # Compiled rules (what agents read)
├── rules/            # Individual rule files
│   ├── data-modeling.md
│   ├── partition-keys.md
│   ├── query-optimization.md
│   └── ...
└── metadata.json     # Version and metadata

When you work on Azure Cosmos DB code, the AI agent automatically loads the relevant rules and applies them to your context.

We Need Your Expertise!

The Azure Cosmos DB Agent Kit is open source, and we want your contributions!

Have you discovered a best practice we haven’t covered? Maybe you’ve learned something the hard way:

  • A query pattern that dramatically reduced RUs
  • A data modeling approach that scaled beautifully
  • An SDK configuration that improved reliability
  • A monitoring technique that caught issues early

Share it with the community!

How to Contribute

  1. Fork the repository
  2. Add your rule to the appropriate category in /skills/cosmosdb-best-practices/rules/
  3. Submit a PR with a description of the scenario and impact
  4. Help thousands of developers write better Azure Cosmos DB code

Check out AGENTS.md for contribution guidelines.

Get Started Today

npx add-skill AzureCosmosDB/cosmosdb-agent-kit

🌟 Star the repo: github.com/AzureCosmosDB/cosmosdb-agent-kit

💬 Share feedback: Open an issue or discussion

🤝 Contribute: Your best practices can help the entire community

⭐ Leave a Review

Tell us about your Azure Cosmos DB experience! Leave a review on PeerSpot and get a $50 gift. Get started here.

☁️ About Azure Cosmos DB

Azure Cosmos DB is a fully managed, serverless NoSQL and vector database for modern app development, including AI applications. With SLA-backed speed and availability, as well as instant dynamic scalability, it’s ideal for real-time NoSQL and MongoDB applications that require high performance and distributed computing over massive volumes of data.

Try Azure Cosmos DB for free and follow updates on X, YouTube, and LinkedIn.

Author

Sajeetharan Sinnathurai
Principal Program Manager

Principal Product Manager passionate about empowering developers with exceptional tools and experiences. Currently part of the Azure Cosmos DB team, driving developer-focused features like JavaScript SDK, integrations, and tooling for local development etc. Interested in web development or cloud? Let’s connect!

0 comments