Cosmosdb Best Practices
ClineOfficialCreated by cosmosdb-agent-kitDistributed by Cline
- Skill
- Guidelines
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/cline/cosmosdb-best-practices/downloadUnzip 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-)
model-embed-related.md — Embed related data retrieved together
model-reference-large.md — Reference data when items grow large
model-avoid-2mb-limit.md — Keep items well under 2MB limit
model-id-constraints.md — Follow ID value length and character constraints
model-nesting-depth.md — Stay within 128-level nesting depth limit
model-numeric-precision.md — Understand IEEE 754 numeric precision limits
model-denormalize-reads.md — Denormalize for read-heavy workloads
model-schema-versioning.md — Version your document schemas
model-type-discriminator.md — Use type discriminators for polymorphic data
model-json-serialization.md — Handle JSON serialization correctly
model-relationship-references.md — Use ID references with transient hydration
2. Partition Key Design — CRITICAL (prefix: partition-)
partition-high-cardinality.md — Choose high-cardinality partition keys
partition-avoid-hotspots.md — Distribute writes evenly
partition-hierarchical.md — Use hierarchical partition keys for flexibility
partition-query-patterns.md — Align partition key with query patterns
partition-synthetic-keys.md — Create synthetic keys when needed
partition-key-length.md — Respect partition key value length limits
partition-20gb-limit.md — Plan for 20GB logical partition limit
3. Query Optimization — HIGH (prefix: query-)
query-avoid-cross-partition.md — Minimize cross-partition queries
query-use-projections.md — Project only needed fields
query-pagination.md — Use continuation tokens for pagination
query-avoid-scans.md — Avoid full container scans
query-parameterize.md — Use parameterized queries
query-order-filters.md — Order filters by selectivity
4. SDK Best Practices — HIGH (prefix: sdk-)
sdk-singleton-client.md — Reuse CosmosClient as singleton
sdk-async-api.md — Use async APIs for throughput
sdk-retry-429.md — Handle 429s with retry-after
sdk-connection-mode.md — Use Direct mode for production
sdk-preferred-regions.md — Configure preferred regions
sdk-excluded-regions.md — Exclude regions experiencing issues
sdk-availability-strategy.md — Configure availability strategy for resilience
sdk-circuit-breaker.md — Use circuit breaker for fault tolerance
sdk-diagnostics.md — Log diagnostics for troubleshooting
sdk-serialization-enums.md — Serialize enums as strings not integers
sdk-emulator-ssl.md — Configure SSL and connection mode for Cosmos DB Emulator
sdk-etag-concurrency.md — Use ETags for optimistic concurrency
sdk-java-content-response.md — Enable content response on write operations (Java)
sdk-java-cosmos-config.md — Configure Cosmos DB in Spring Boot with dependent beans
sdk-java-spring-boot-versions.md — Match Java version to Spring Boot requirements
sdk-local-dev-config.md — Configure local development to avoid cloud conflicts
sdk-newtonsoft-dependency.md — Explicitly reference Newtonsoft.Json package (.NET)
sdk-spring-data-annotations.md — Annotate entities for Spring Data Cosmos
sdk-spring-data-repository.md — Use CosmosRepository correctly
5. Indexing Strategies — MEDIUM-HIGH (prefix: index-)
index-exclude-unused.md — Exclude paths never queried
index-composite.md — Use composite indexes for ORDER BY
index-spatial.md — Add spatial indexes for geo queries
index-range-vs-hash.md — Choose appropriate index types
index-lazy-consistent.md — Understand indexing modes
6. Throughput & Scaling — MEDIUM (prefix: throughput-)
throughput-autoscale.md — Use autoscale for variable workloads
throughput-right-size.md — Right-size provisioned throughput
throughput-serverless.md — Consider serverless for dev/test
throughput-burst.md — Understand burst capacity
throughput-container-vs-database.md — Choose allocation level wisely
7. Global Distribution — MEDIUM (prefix: global-)
global-multi-region.md — Configure multi-region writes
global-consistency.md — Choose appropriate consistency level
global-conflict-resolution.md — Implement conflict resolution
global-failover.md — Configure automatic failover
global-read-regions.md — Add read regions near users
global-zone-redundancy.md — Enable zone redundancy for HA
8. Monitoring & Diagnostics — LOW-MEDIUM (prefix: monitoring-)
monitoring-ru-consumption.md — Track RU consumption
monitoring-latency.md — Monitor P99 latency
monitoring-throttling.md — Alert on throttling
monitoring-azure-monitor.md — Integrate Azure Monitor
monitoring-diagnostic-logs.md — Enable diagnostic logging
9. Design Patterns — HIGH (prefix: pattern-)
pattern-change-feed-materialized-views.md — Use Change Feed for materialized views
pattern-efficient-ranking.md — Use count-based or cached approaches for ranking
pattern-service-layer-relationships.md — Use a service layer to hydrate document references
10. Vector Search — HIGH (prefix: vector-)
vector-enable-feature.md — Enable vector search feature on account
vector-embedding-policy.md — Define vector embedding policy on container
vector-index-type.md — Configure vector indexes (QuantizedFlat or DiskANN)
vector-distance-query.md — Use VectorDistance() for similarity search
vector-normalize-embeddings.md — Normalize embeddings for cosine similarity
vector-repository-pattern.md — Implement repository pattern for vector search
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-*.mdfilesPartition key question → read
rules/partition-*.mdfilesSDK/client question → read
rules/sdk-*.mdfilesetc.
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
- ATTRIBUTION.mdAdded by AutoGineer876 B
- SKILL.md10.1 KiB
- rules/_sections.md2.1 KiB
- rules/_template.md802 B
- rules/global-conflict-resolution.md4.0 KiB
- rules/global-consistency.md3.7 KiB
- rules/global-failover.md3.7 KiB
- rules/global-multi-region.md3.2 KiB
- rules/global-read-regions.md3.9 KiB
- rules/global-zone-redundancy.md3.5 KiB
- rules/index-composite.md6.0 KiB
- rules/index-exclude-unused.md3.1 KiB
- rules/index-lazy-consistent.md3.1 KiB
- rules/index-range-vs-hash.md3.4 KiB
- rules/index-spatial.md3.1 KiB
- rules/model-avoid-2mb-limit.md2.0 KiB
- rules/model-denormalize-reads.md3.4 KiB
- rules/model-embed-related.md2.5 KiB
- rules/model-id-constraints.md2.9 KiB
- rules/model-json-serialization.md4.0 KiB
- rules/model-nesting-depth.md3.3 KiB
- rules/model-numeric-precision.md3.2 KiB
- rules/model-reference-large.md2.3 KiB
- rules/model-relationship-references.md3.6 KiB
- rules/model-schema-versioning.md2.4 KiB
- rules/model-type-discriminator.md3.5 KiB
- rules/monitoring-azure-monitor.md4.4 KiB
- rules/monitoring-diagnostic-logs.md5.1 KiB
- rules/monitoring-latency.md4.2 KiB
- rules/monitoring-ru-consumption.md4.2 KiB
- rules/monitoring-throttling.md4.4 KiB
- rules/partition-20gb-limit.md2.8 KiB
- rules/partition-avoid-hotspots.md3.4 KiB
- rules/partition-hierarchical.md2.7 KiB
- rules/partition-high-cardinality.md2.2 KiB
- rules/partition-key-length.md2.8 KiB
- rules/partition-query-patterns.md2.7 KiB
- rules/partition-synthetic-keys.md3.8 KiB
- rules/pattern-change-feed-materialized-views.md7.2 KiB
- rules/pattern-efficient-ranking.md5.8 KiB
- rules/pattern-service-layer-relationships.md4.8 KiB
- rules/query-avoid-cross-partition.md2.5 KiB
- rules/query-avoid-scans.md2.5 KiB
- rules/query-order-filters.md2.6 KiB
- rules/query-pagination.md6.2 KiB
- rules/query-parameterize.md2.9 KiB
- rules/query-use-projections.md2.7 KiB
- rules/sdk-async-api.md3.2 KiB
- rules/sdk-availability-strategy.md5.3 KiB
- rules/sdk-circuit-breaker.md8.4 KiB
- rules/sdk-connection-mode.md2.9 KiB
- rules/sdk-diagnostics.md3.6 KiB
- rules/sdk-emulator-ssl.md7.8 KiB
- rules/sdk-etag-concurrency.md8.1 KiB
- rules/sdk-excluded-regions.md4.9 KiB
- rules/sdk-java-content-response.md3.9 KiB
- rules/sdk-java-cosmos-config.md5.9 KiB
- rules/sdk-java-spring-boot-versions.md4.8 KiB
- rules/sdk-local-dev-config.md5.4 KiB
- rules/sdk-newtonsoft-dependency.md3.9 KiB
- rules/sdk-preferred-regions.md3.2 KiB
- rules/sdk-retry-429.md3.7 KiB
- rules/sdk-serialization-enums.md2.8 KiB
- rules/sdk-singleton-client.md3.7 KiB
- rules/sdk-spring-data-annotations.md3.4 KiB
- rules/sdk-spring-data-repository.md3.4 KiB
- rules/throughput-autoscale.md2.6 KiB
- rules/throughput-burst.md2.7 KiB
- rules/throughput-container-vs-database.md3.2 KiB
- rules/throughput-right-size.md3.1 KiB
- rules/throughput-serverless.md2.7 KiB
- rules/vector-distance-query.md4.8 KiB
- rules/vector-embedding-policy.md3.8 KiB
- rules/vector-enable-feature.md3.0 KiB
- rules/vector-index-type.md4.7 KiB
- rules/vector-normalize-embeddings.md8.6 KiB
- rules/vector-repository-pattern.md12.9 KiB
rules/vector-normalize-embeddings.md
title: Normalize Embeddings for Cosine Similarity impact: MEDIUM impactDescription: Ensures accurate similarity scores and consistent test results tags: vector, embeddings, normalization, testing, cosine
Normalize Embeddings for Cosine Similarity
Impact: MEDIUM (Accurate similarity scores)
When using cosine distance (the most common choice for vector search), normalize embeddings to unit length (L2 norm = 1). This ensures consistent similarity scores and enables accurate testing with mock embeddings.
Why Normalize:
Cosine similarity measures the angle between vectors, not magnitude
Unnormalized embeddings can produce inconsistent scores
Most embedding models (Azure OpenAI, etc.) return normalized vectors
Essential for generating mock embeddings for testing
Formula:
normalized_vector = vector / ||vector||₂
where ||vector||₂ = sqrt(sum(x² for x in vector))Incorrect (unnormalized embeddings):
# Python - BAD: Random vectors without normalization
import random
def generate_mock_embedding(dimensions=1536):
# Returns unnormalized random vector
return [random.uniform(-1, 1) for _ in range(dimensions)]
# Problem: Magnitude varies, affects cosine similarity scores// .NET - BAD: Unnormalized test embeddings
public float[] GenerateMockEmbedding(int dimensions = 1536)
{
var random = new Random();
var embedding = new float[dimensions];
for (int i = 0; i < dimensions; i++)
{
embedding[i] = (float)(random.NextDouble() * 2 - 1);
}
return embedding; // Not normalized - scores will be inconsistent
}Correct (normalized to unit length):
# Python - GOOD: Normalized embeddings
import numpy as np
def generate_mock_embedding(text: str, dimensions: int = 1536) -> list:
"""
Generate normalized mock embedding for testing.
Uses text hash as seed for reproducibility.
"""
# Use text hash as seed for deterministic results
seed = hash(text) % (2**32)
np.random.seed(seed)
# Generate random vector
vector = np.random.randn(dimensions).astype(np.float32)
# Normalize to unit length (critical for cosine similarity)
vector = vector / np.linalg.norm(vector)
return vector.tolist()
# Verify normalization
embedding = generate_mock_embedding("test document")
magnitude = np.linalg.norm(embedding)
assert abs(magnitude - 1.0) < 1e-6, f"Not normalized: {magnitude}"
# Use in tests
documents = [
{
"id": "doc1",
"content": "Azure Cosmos DB vector search",
"embedding": generate_mock_embedding("Azure Cosmos DB vector search")
}
]// .NET - GOOD: Normalized embeddings
using System;
using System.Linq;
public class EmbeddingHelper
{
public static float[] GenerateMockEmbedding(string text, int dimensions = 1536)
{
// Use text hash as seed for reproducibility
var seed = Math.Abs(text.GetHashCode());
var random = new Random(seed);
// Generate random vector
var vector = new float[dimensions];
for (int i = 0; i < dimensions; i++)
{
// Box-Muller transform for normal distribution
double u1 = random.NextDouble();
double u2 = random.NextDouble();
vector[i] = (float)(Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Cos(2.0 * Math.PI * u2));
}
// Normalize to unit length (L2 norm = 1)
var magnitude = Math.Sqrt(vector.Sum(x => x * x));
for (int i = 0; i < dimensions; i++)
{
vector[i] /= (float)magnitude;
}
return vector;
}
public static double CalculateMagnitude(float[] vector)
{
return Math.Sqrt(vector.Sum(x => x * x));
}
}
// Usage
var embedding = EmbeddingHelper.GenerateMockEmbedding("test document");
var magnitude = EmbeddingHelper.CalculateMagnitude(embedding);
Console.WriteLine($"Magnitude: {magnitude}"); // Should be ~1.0
var document = new Document
{
Id = "doc1",
Content = "Azure Cosmos DB",
Embedding = embedding
};// JavaScript - GOOD: Normalized embeddings
function generateMockEmbedding(text, dimensions = 1536) {
// Simple hash for seed
let seed = 0;
for (let i = 0; i < text.length; i++) {
seed = ((seed << 5) - seed) + text.charCodeAt(i);
seed = seed & seed; // Convert to 32-bit integer
}
// Seeded random number generator
const random = (function(seed) {
let state = seed;
return function() {
state = (state * 1103515245 + 12345) & 0x7fffffff;
return state / 0x7fffffff;
};
})(Math.abs(seed));
// Generate random vector with normal distribution (Box-Muller)
const vector = [];
for (let i = 0; i < dimensions; i++) {
const u1 = random();
const u2 = random();
const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
vector.push(z);
}
// Normalize to unit length
const magnitude = Math.sqrt(vector.reduce((sum, x) => sum + x * x, 0));
return vector.map(x => x / magnitude);
}
// Verify
const embedding = generateMockEmbedding("test document");
const magnitude = Math.sqrt(embedding.reduce((sum, x) => sum + x * x, 0));
console.log(`Magnitude: ${magnitude}`); // Should be ~1.0
const document = {
id: "doc1",
content: "Azure Cosmos DB",
embedding: embedding
};// Java - GOOD: Normalized embeddings
import java.util.Random;
public class EmbeddingHelper {
public static float[] generateMockEmbedding(String text, int dimensions) {
// Use text hash as seed for reproducibility
int seed = Math.abs(text.hashCode());
Random random = new Random(seed);
// Generate random vector with normal distribution
float[] vector = new float[dimensions];
for (int i = 0; i < dimensions; i++) {
vector[i] = (float) random.nextGaussian();
}
// Normalize to unit length
double magnitude = 0.0;
for (float v : vector) {
magnitude += v * v;
}
magnitude = Math.sqrt(magnitude);
for (int i = 0; i < dimensions; i++) {
vector[i] /= magnitude;
}
return vector;
}
public static double calculateMagnitude(float[] vector) {
double sum = 0.0;
for (float v : vector) {
sum += v * v;
}
return Math.sqrt(sum);
}
}
// Usage
float[] embedding = EmbeddingHelper.generateMockEmbedding("test document", 1536);
double magnitude = EmbeddingHelper.calculateMagnitude(embedding);
System.out.println("Magnitude: " + magnitude); // Should be ~1.0Production Embeddings:
Most embedding APIs return normalized vectors automatically, but verify:
# Azure OpenAI - typically normalized
from openai import AzureOpenAI
client = AzureOpenAI(...)
response = client.embeddings.create(
input="search query",
model="text-embedding-ada-002"
)
embedding = response.data[0].embedding
# Verify normalization (optional, for debugging)
import numpy as np
magnitude = np.linalg.norm(embedding)
print(f"Magnitude: {magnitude}") # Should be ~1.0
# If not normalized (rare), normalize:
if abs(magnitude - 1.0) > 0.01:
embedding = (np.array(embedding) / magnitude).tolist()Testing Best Practices:
Deterministic Mock Embeddings - Use text/content hash as random seed
seed = hash(text) % (2**32) # Reproducible resultsVerify Normalization - Assert magnitude is ~1.0 in tests
assert abs(np.linalg.norm(embedding) - 1.0) < 1e-6Realistic Dimensions - Use actual dimensions (1536 for Ada-002, 3072 for text-embedding-3-large)
Similarity Score Ranges - With normalized vectors and cosine distance:
Identical vectors: score = 1.0
Orthogonal vectors: score = 0.0
Opposite vectors: score = -1.0 (rare in embeddings)
When NOT to Normalize:
If using Euclidean or Dot Product distance functions (check your embedding policy)
When magnitude carries semantic meaning (very rare)
If embedding model explicitly states vectors are not normalized
Common Mistake:
# BAD: Comparing normalized query to unnormalized documents
query_embedding = normalize(get_embedding(query)) # Normalized
documents = [
{"embedding": [random.random() for _ in range(1536)]} # NOT normalized
]
# Results: Inconsistent similarity scoresRelated Rules:
vector-embedding-policy.md - Choose cosine distance function
vector-distance-query.md - VectorDistance() queries return similarity scores
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