Cosmosdb best practices
Skill AzureCosmosDB/cosmosdb-agent-kit/skills/cosmosdb-best-practices
Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, and SDK usage. Use when writing, reviewing, or refactoring code that interacts with Azure Cosmos DB, designing data models, optimizing queries, or implementing high-performance database operations. USE FOR: Cosmos DB NoSQL, partition key design, RU optimization, point reads, cross-partition queries, SDK singleton, CosmosClient, container modeling, change feed, bulk operations, vector search, full-text search, hierarchical partition keys, global distribution, autoscale throughput, indexing policy. DO NOT USE FOR: PostgreSQL, MySQL, MongoDB (non-Azure), DynamoDB, Cassandra, Azure SQL, Cosmos DB for PostgreSQL (vCore), Cosmos DB for MongoDB vCore, Azure DocumentDB, general SQL databases, Redis, Elasticsearch.From its SKILL.md
npx -y skills add AzureCosmosDB/cosmosdb-agent-kit --skill cosmosdb-best-practicesAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
What its file declares
Copied from the file, not written here
The file declares its own license as MIT. That is the author’s claim about this one file, and it is not the same thing as the license GitHub reports for the repository, which is listed with the other numbers below.
SKILL.md
16.6 KB, ~3.8k tokens by cl100k_base, as published. Nobody here has run it
Azure Cosmos DB Best Practices
Comprehensive performance optimization guide for Azure Cosmos DB applications, containing 100+ rules across 12 categories, prioritized by impact to guide automated refactoring and code generation.
When to Apply
Reference these guidelines when:
- Designing data models for Cosmos DB
- Choosing partition keys
- Writing or optimizing queries
- Implementing SDK patterns
- Using the Cosmos DB Emulator for local development
- Inspecting or managing Cosmos DB data with developer tooling
- Implementing vector search or RAG features on Cosmos DB
- Reviewing code for performance issues
- Configuring throughput and scaling
- Building globally distributed applications
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Data Modeling | CRITICAL | model- |
| 2 | Partition Key Design | CRITICAL | partition- |
| 3 | Query Optimization | HIGH | query- |
| 4 | SDK Best Practices | HIGH | sdk- |
| 5 | Indexing Strategies | MEDIUM-HIGH | index- |
| 6 | Throughput & Scaling | MEDIUM | throughput- |
| 7 | Global Distribution | MEDIUM | global- |
| 8 | Monitoring & Diagnostics | LOW-MEDIUM | monitoring- |
| 9 | Design Patterns | HIGH | pattern- |
| 10 | Developer Tooling | MEDIUM | tooling- |
| 11 | Vector Search | HIGH | vector- |
Quick Reference
1. Data Modeling (CRITICAL)
- model-embed-related - Embed related data retrieved together
- model-reference-large - Reference data when items get too large
- model-avoid-2mb-limit - Keep items well under 2MB limit
- model-id-constraints - Follow ID value length and character constraints
- model-nesting-depth - Stay within 128-level nesting depth limit
- model-numeric-precision - Understand IEEE 754 numeric precision limits
- model-denormalize-reads - Denormalize for read-heavy workloads including pre-computed aggregates
- model-schema-versioning - Version your document schemas
- model-type-discriminator - Use type discriminators for polymorphic data
- model-json-serialization - Handle JSON serialization correctly for Cosmos DB documents
- model-relationship-references - Use ID references with transient hydration for document relationships
2. Partition Key Design (CRITICAL)
- partition-high-cardinality - Choose high-cardinality partition keys
- partition-avoid-hotspots - Distribute writes evenly
- partition-hierarchical - Use hierarchical partition keys for flexibility; order levels broad→narrow
- partition-query-patterns - Align partition key with query patterns
- partition-synthetic-keys - Create synthetic keys when needed
- partition-key-length - Respect partition key value length limits
- partition-immutable-key - Choose immutable properties as partition keys
- partition-20gb-limit - Plan for 20GB logical partition limit
- partition-rekey-migration - Re-key a misaligned container with the Change partition key feature
3. Query Optimization (HIGH)
- query-aggregate-single-pass - Compute min/max/avg with one scoped aggregate query
- query-avoid-cross-partition - Minimize cross-partition queries
- query-use-projections - Project only needed fields; prefer dedicated result types for projections
- query-pagination - Use continuation tokens for pagination
- query-avoid-scans - Avoid full container scans
- query-parameterize - Use parameterized queries
- query-order-filters - Order filters by selectivity
- query-top-literal - Use literal integers for TOP, never parameters
- query-latest-by-timestamp - Query "latest" documents with explicit ORDER BY and TOP 1
- query-olap-detection - Detect and redirect analytical queries away from transactional containers
- query-point-reads - Use point reads (ReadItem) instead of queries when id and partition key are known
4. SDK Best Practices (HIGH)
- sdk-singleton-client - Reuse CosmosClient as singleton
- sdk-async-api - Use async APIs for throughput
- sdk-retry-429 - Handle 429s with retry-after
- sdk-connection-mode - Use Direct mode for production
- sdk-preferred-regions - Configure preferred regions
- sdk-excluded-regions - Exclude regions experiencing issues
- sdk-availability-strategy - Configure availability strategy for resilience
- sdk-circuit-breaker - Use circuit breaker for fault tolerance
- sdk-diagnostics - Log diagnostics for troubleshooting
- sdk-serialization-enums - Serialize enums as strings not integers
- sdk-emulator-ssl - Configure SSL and connection mode for Cosmos DB Emulator
- sdk-ifnonematch-create - Use
setIfNoneMatchETag("*")oncreateItemto reject duplicates atomically (409 on conflict) - sdk-no-shared-request-options - Never reuse a
CosmosItemRequestOptionsinstance across multiplecreateItemcalls — SDK mutates it internally, causing wrong partition key on second call - sdk-patch-incr - Use
CosmosPatchOperations.incr()for atomic counter increments — no read RU, no ETag conflict cycle - sdk-bypage-empty-token - Guard against empty-string continuation tokens before calling
byPage()— passnullfor first page, never"" - sdk-etag-concurrency - Use ETags for optimistic concurrency on read-modify-write operations
- sdk-java-content-response - Enable content response on write operations (Java)
- sdk-java-cosmos-config - Configure Cosmos DB initialization correctly in Spring Boot
- sdk-java-spring-boot-versions - Match Java version to Spring Boot requirements
- sdk-local-dev-config - Configure local development to avoid cloud conflicts
- sdk-dotnet-cosmos-package-id - Use
Microsoft.Azure.Cosmos, not the abandonedAzure.Cosmosv4-preview package - sdk-newtonsoft-dependency - Explicitly reference Newtonsoft.Json package
- sdk-python-async-deps - Include aiohttp when using Python async SDK
- sdk-spring-data-annotations - Annotate entities for Spring Data Cosmos
- sdk-spring-data-repository - Use CosmosRepository correctly and handle Iterable return types
- sdk-langchain-cosmosdb-saver - Use CosmosDBSaver for LangGraph checkpointing with async container client
- sdk-langchain-async-checkpointer - Initialize async Cosmos DB container in startup routine, not module level
- sdk-langchain-mcp-persistent-session - Maintain persistent MCP client sessions for application lifetime
- sdk-langchain-mcp-tool-content-format - Handle both string and list formats in MCP ToolMessage content
- sdk-langgraph-mcp-tool-filtering - Filter MCP tools by name prefix for per-agent assignment
- sdk-dotnet-namespace-collision - Avoid
Microsoft.Azure.Cosmosnamespace collisions with domain models (User, Database, Container, etc.) - sdk-ingestion-rate-control - Rate-control high-volume ingestion (concurrency, retry-after, throughput control)
5. Indexing Strategies (MEDIUM-HIGH)
- index-exclude-unused - Exclude paths never queried
- index-path-syntax - Use correct path notation (
/?,/[],/*) - index-composite - Use composite indexes for ORDER BY
- index-composite-direction - Match composite index directions to ORDER BY
- index-spatial - Add spatial indexes for geo queries
- index-range-vs-hash - Choose appropriate index types
- index-lazy-consistent - Understand indexing modes
6. Throughput & Scaling (MEDIUM)
- throughput-autoscale - Use autoscale for variable workloads
- throughput-right-size - Right-size provisioned throughput
- throughput-serverless - Consider serverless for dev/test
- throughput-burst - Understand burst capacity
- throughput-container-vs-database - Choose allocation level wisely
- throughput-idle-container-review - Review idle containers for lifecycle action
- throughput-ttl-stale-data - Expire stale data with TTL before hitting storage limits
- throughput-serverless-migration - Migrate a low-traffic provisioned account to serverless
7. Global Distribution (MEDIUM)
- global-multi-region - Configure multi-region writes
- global-consistency - Choose appropriate consistency level
- global-conflict-resolution - Implement conflict resolution
- global-failover - Configure automatic failover
- global-read-regions - Add read regions near users
- global-zone-redundancy - Enable zone redundancy for HA
- global-multi-region-write-antipattern - Avoid multi-region writes without an active-active need
8. Monitoring & Diagnostics (LOW-MEDIUM)
- monitoring-ru-consumption - Track RU consumption
- monitoring-latency - Monitor P99 latency
- monitoring-throttling - Alert on throttling
- monitoring-azure-monitor - Integrate Azure Monitor
- monitoring-diagnostic-logs - Enable diagnostic logging
9. Design Patterns (HIGH)
- pattern-change-feed-materialized-views - Use Change Feed for cross-partition query optimization
- pattern-efficient-ranking - Use count-based or cached approaches for efficient ranking
- pattern-service-layer-relationships - Use a service layer to hydrate document references
- pattern-langgraph-multi-agent - Use StateGraph with conditional edges for multi-agent routing
- pattern-langgraph-interrupt-human - Use LangGraph interrupt for human-in-the-loop confirmation flows
- pattern-langgraph-resume-checkpoint - Resume LangGraph from checkpoint after interrupt for multi-turn conversations
- pattern-langgraph-agent-routing-cosmosdb - Persist active agent in Cosmos DB for deterministic routing via point reads
- pattern-langgraph-fastapi-startup - Initialize LangGraph agents in FastAPI startup with retry logic
- pattern-langgraph-chat-history-separate - Store chat history in a dedicated container, not the checkpointer
- pattern-background-task-writes - Use FastAPI background tasks for non-blocking chat history writes
- pattern-langgraph-async-cosmos-routing - Wrap Cosmos DB sync calls in asyncio.to_thread for LangGraph routing functions
- pattern-langgraph-async-cosmos-writes - Use asyncio.to_thread for active agent writes in async node functions
- pattern-langgraph-agent-name-attribution - Tag AI messages with agent name for API response attribution
10. Developer Tooling (MEDIUM)
- tooling-vscode-extension - Use the VS Code extension for routine inspection and management
- tooling-emulator-setup - Use the Emulator for local development and testing
11. Vector Search (HIGH)
- vector-enable-feature - Enable vector search on the account before using vector features
- vector-embedding-policy - Define vector embedding policy for vector properties
- vector-index-type - Configure vector indexes in the indexing policy
- vector-normalize-embeddings - Normalize embeddings for cosine similarity
- vector-distance-query - Use VectorDistance for similarity search
- vector-repository-pattern - Implement a repository pattern for vector search
12. Full-Text Search (HIGH)
- fts-enable-capability - Enable
EnableNoSQLFullTextSearchcapability on the account — prerequisite for all FTS functions - fts-full-text-policy - Define
fullTextPolicyon the container with correct language code (en-US, case-sensitive) - fts-index-policy - Add
fullTextIndexesentry in the indexing policy to build the inverted index - fts-contains-query - Use
FullTextContains/FullTextContainsAll/FullTextContainsAnyinstead ofCONTAINS(LOWER(...)) - fts-score-ranking - Use
ORDER BY RANK FullTextScore(path, term)for BM25 relevance ranking - fts-hybrid-query - Combine FTS predicates with range/equality filters; put most selective filter first
How to Use
Use the linked rule files above for detailed explanations and code examples. The links give the agent direct paths to the relevant guidance instead of relying on folder scanning or inferred filenames.
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
What ships with it: 140 files
561.4 KB alongside SKILL.md
rules/
- fts-add-index.md1.6 KB
- fts-define-policy.md1.7 KB
- fts-enable-capability.md1.6 KB
- fts-hybrid-queries.md2.0 KB
- fts-keyword-matching.md2.2 KB
- fts-relevance-ranking.md1.4 KB
- global-conflict-resolution.md4.0 KB
- global-consistency.md3.9 KB
- global-failover.md3.7 KB
- global-multi-region.md3.2 KB
- global-multi-region-write-antipattern.md2.6 KB
- global-read-regions.md3.9 KB
- global-zone-redundancy.md3.5 KB
- index-composite-direction.md2.7 KB
- index-composite.md10.4 KB
- index-exclude-unused.md4.0 KB
- index-lazy-consistent.md3.3 KB
- index-path-syntax.md2.5 KB
- index-range-vs-hash.md3.6 KB
- index-spatial.md3.1 KB
- model-avoid-2mb-limit.md2.0 KB
- model-denormalize-reads.md11.8 KB
- model-embed-related.md2.5 KB
- model-id-constraints.md7.4 KB
- model-json-serialization.md6.0 KB
- model-nesting-depth.md3.3 KB
- model-numeric-precision.md3.2 KB
- model-reference-large.md2.3 KB
- model-relationship-references.md3.6 KB
- model-schema-versioning.md2.8 KB
- model-ttl-expiration.md3.1 KB
- model-type-discriminator.md3.5 KB
- monitoring-azure-monitor.md4.4 KB
- monitoring-diagnostic-logs.md5.1 KB
- monitoring-latency.md4.2 KB
- monitoring-ru-consumption.md7.5 KB
- monitoring-throttling.md4.4 KB
- partition-20gb-limit.md2.8 KB
- metadata.json559 B
- README.md4.8 KB
100 more files not listed here. See all 140 in the repository.
Gives 0 of the 12 instructions most performance cost skills give in ~3.8k tokens
Counted across 797 of the 1,117 authors here whose files we hold, read 2026-09-06
- Check for product marketing context firstin 46 of 797, across 20 files
- Measure before optimizingin 31 of 797, across 25 files
- Profile first to identify the actual bottleneckin 23 of 797, across 22 files
- Verify your robots.txt allows AI crawlersin 21 of 797, across 12 files
- Import directly and avoid barrel filesin 19 of 797, across 15 files
- Spawn all runs in the same turnin 18 of 797, across 11 files
- Write a draft of the skillin 17 of 797, across 10 files
- Understand the user's intentin 17 of 797, across 10 files
- Use React.cache for per-request deduplicationin 16 of 797, across 11 files
- Profile before optimizingin 16 of 797, across 14 files
- Include specific numbers with sourcesin 15 of 797, across 8 files
- Add lazy loading to below-fold imagesin 15 of 797, across 10 files
Said here and by no other author read
- Exclude paths never queried
- Use autoscale for variable workloads
- Use Change Feed for cross-partition query optimization
- Use VectorDistance for similarity search
- Enable vector search on the account
- Use point reads instead of queries
Grouped from the skills themselves: near-identical wordings counted once, and counted by distinct author, so one author publishing three of these counts once. Length counted with cl100k_base; the agent that loads this file may tokenize it differently.