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://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/pattern-efficient-ranking.md


title: Use count-based or cached rank approaches instead of full partition scans for ranking impact: HIGH impactDescription: reduces rank lookups from O(N) partition scans to O(1) or O(log N) operations tags: pattern, ranking, leaderboard, performance, query-optimization

Efficient Ranking in Cosmos DB

When implementing leaderboards or rankings, avoid scanning an entire partition to determine a single player's rank. Full partition scans for rank lookups are an anti-pattern that becomes unsustainable at scale.

Problem: Full partition scan to find rank

// Anti-pattern: Reads ALL entries in a partition to find one player's rank
// At 500K players, this consumes thousands of RU and takes seconds
public async Task<int> GetPlayerRankAsync(string leaderboardKey, string playerId)
{
    var query = new QueryDefinition(
        "SELECT c.playerId, c.bestScore FROM c WHERE c.type = @type ORDER BY c.bestScore DESC"
    ).WithParameter("@type", "leaderboardEntry");

    var allEntries = new List<LeaderboardEntry>();
    using var iterator = _container.GetItemQueryIterator<LeaderboardEntry>(
        query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(leaderboardKey) });

    while (iterator.HasMoreResults)
    {
        var response = await iterator.ReadNextAsync();
        allEntries.AddRange(response); // Loading ALL entries into memory!
    }

    // O(N) scan to find player
    return allEntries.FindIndex(e => e.PlayerId == playerId) + 1;
}

This approach:

  • Reads every document in the partition (potentially 500K+ documents)

  • Consumes thousands of RU per request

  • Has multi-second latency

  • Loads all entries into memory

Solution 1: COUNT-based rank query (simplest)

// Count players with higher scores to determine rank
// Single query, ~3-5 RU regardless of partition size
public async Task<int> GetPlayerRankAsync(string leaderboardKey, string playerId, int playerScore)
{
    var countQuery = new QueryDefinition(
        "SELECT VALUE COUNT(1) FROM c WHERE c.type = @type AND c.bestScore > @score"
    )
    .WithParameter("@type", "leaderboardEntry")
    .WithParameter("@score", playerScore);

    using var iterator = _container.GetItemQueryIterator<int>(
        countQuery, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(leaderboardKey) });

    var response = await iterator.ReadNextAsync();
    return response.Resource.FirstOrDefault() + 1; // Rank = count of players above + 1
}

Solution 2: Cached rank offsets with Change Feed

For extremely high-volume leaderboard reads, pre-compute and cache rank data:

// Maintain a rank cache that is periodically updated
// Leaderboard entry includes pre-computed rank
public class RankedLeaderboardEntry
{
    [JsonPropertyName("id")]
    public string Id { get; set; }  // playerId

    [JsonPropertyName("leaderboardKey")]
    public string LeaderboardKey { get; set; }

    [JsonPropertyName("rank")]
    public int Rank { get; set; }  // Pre-computed rank

    [JsonPropertyName("bestScore")]
    public int BestScore { get; set; }

    [JsonPropertyName("displayName")]
    public string DisplayName { get; set; }
}

// Change Feed processor periodically recomputes ranks
// Run on a schedule (e.g., every 30 seconds) for near-real-time rankings
public async Task RecomputeRanksAsync(string leaderboardKey)
{
    var query = new QueryDefinition(
        "SELECT c.id, c.playerId, c.bestScore, c.displayName FROM c " +
        "WHERE c.type = @type ORDER BY c.bestScore DESC"
    ).WithParameter("@type", "leaderboardEntry");

    int rank = 0;
    using var iterator = _container.GetItemQueryIterator<LeaderboardEntry>(
        query, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey(leaderboardKey) });

    while (iterator.HasMoreResults)
    {
        var batch = await iterator.ReadNextAsync();
        foreach (var entry in batch)
        {
            rank++;
            entry.Rank = rank;
            await _container.UpsertItemAsync(entry,
                new PartitionKey(leaderboardKey));
        }
    }
}

// Then rank lookup is a simple point read: O(1), 1 RU
public async Task<int> GetPlayerRankAsync(string leaderboardKey, string playerId)
{
    var response = await _container.ReadItemAsync<RankedLeaderboardEntry>(
        playerId, new PartitionKey(leaderboardKey));
    return response.Resource.Rank;
}

Solution 3: Approximate ranking with score buckets

For leaderboards where approximate rank is acceptable:

// Maintain score distribution buckets for O(1) approximate ranking
// Partition key: /leaderboardKey, id: "bucket-{range}"
public class ScoreBucket
{
    [JsonPropertyName("id")]
    public string Id { get; set; }  // e.g., "bucket-9000-10000"

    [JsonPropertyName("leaderboardKey")]
    public string LeaderboardKey { get; set; }

    [JsonPropertyName("minScore")]
    public int MinScore { get; set; }

    [JsonPropertyName("maxScore")]
    public int MaxScore { get; set; }

    [JsonPropertyName("playerCount")]
    public int PlayerCount { get; set; }
}

// Approximate rank = sum of players in all higher buckets + position within bucket

Key Points:

  • Never scan an entire partition to find a single item's rank — this is O(N) and doesn't scale

  • COUNT queries are the simplest solution and work well for moderate scale (< 1M entries)

  • Pre-computed ranks via Change Feed are best for high-volume reads with eventual consistency tolerance

  • Score buckets provide O(1) approximate ranking for very large datasets

  • Consider the trade-off: exact real-time rank (more RU) vs. slightly stale rank (less RU)

  • For "nearby players ±10", combine a COUNT query with a TOP 21 query centered on the player's score

Reference: Cosmos DB query optimization

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