cosmosdb-best-practices
par microsoft
Guide complet d'optimisation des performances pour les applications Azure Cosmos DB, contenant plus de 75 règles réparties dans 11 catégories, priorisées par impact pour guider le refactoring automatisé et la génération de code.
npx skills add https://github.com/microsoft/vscode-cosmosdb --skill cosmosdb-best-practicesAzure Cosmos DB Best Practices
Comprehensive performance optimization guide for Azure Cosmos DB applications, containing 75+ rules across 11 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
- 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
- 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-20gb-limit - Plan for 20GB logical partition limit
3. Query Optimization (HIGH)
- query-avoid-cross-partition - Minimize cross-partition queries
- query-use-projections - Project only needed fields
- 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
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-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-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
5. Indexing Strategies (MEDIUM-HIGH)
- index-path-syntax - Use correct indexing path syntax (
/?for scalars,/[]for arrays,/*terminal-only) - index-exclude-unused - Exclude paths never queried
- 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
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
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
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
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
Full Compiled Document
For the complete guide with all rules expanded: AGENTS.md
Plus de skills de microsoft
oss-growth
microsoft
Persona de growth hacker OSS
official
microsoft-foundry
microsoft
Déployer, évaluer et gérer les agents Foundry de bout en bout : build Docker, push ACR, création d’agent hébergé/par prompt, démarrage de conteneur, évaluation par lots, évaluation continue, workflows d’optimisation de prompt, agent.yaml, curation de jeux de données à partir de traces. UTILISER POUR : déployer un agent vers Foundry, agent hébergé, créer un agent, invoquer un agent, évaluer un agent, exécuter une évaluation par lots, évaluation continue, surveillance continue, statut d’évaluation continue, optimiser un prompt, améliorer un prompt, optimiseur de prompt, optimiser les instructions d’un agent, améliorer un agent...
officialdevelopmentdevops
azure-ai
microsoft
Utiliser pour Azure AI : Recherche, Parole, OpenAI, Intelligence documentaire. Aide pour la recherche, la recherche vectorielle/hybride, la reconnaissance vocale, la synthèse vocale, la transcription, l'OCR. QUAND : Recherche AI, recherche par requête, recherche vectorielle, recherche hybride, recherche sémantique, reconnaissance vocale, synthèse vocale, transcrire, OCR, convertir du texte en parole.
officialdevelopmentapi
azure-deploy
microsoft
Exécutez les déploiements Azure pour les applications DÉJÀ PRÉPARÉES disposant de fichiers .azure/deployment-plan.md et d'infrastructure existants. N'utilisez PAS cette compétence lorsque l'utilisateur demande de CRÉER une nouvelle application — utilisez plutôt azure-prepare. Cette compétence exécute les commandes azd up, azd deploy, terraform apply et az deployment avec une récupération d'erreur intégrée. Nécessite .azure/deployment-plan.md de azure-prepare et un état validé de azure-validate. QUAND : "exécuter azd up", "exécuter azd deploy", "exécuter le déploiement",...
officialdevopsaws
azure-storage
microsoft
Services Azure Storage incluant Blob Storage, File Shares, Queue Storage, Table Storage et Data Lake. Répond aux questions sur les niveaux d'accès au stockage (chaud, froid, froid, archive), quand utiliser chaque niveau et comparaison des niveaux. Fournit du stockage d'objets, des partages de fichiers SMB, de la messagerie asynchrone, du NoSQL clé-valeur et de l'analyse de big data. Inclut la gestion du cycle de vie. À UTILISER POUR : stockage blob, partages de fichiers, stockage de files d'attente, stockage de tables, data lake, téléchargement de fichiers, téléchargement de blobs, comptes de stockage, niveaux d'accès,...
officialdevelopmentdatabase
azure-diagnostics
microsoft
Déboguer les problèmes de production Azure à l'aide d'AppLens, Azure Monitor, l'état des ressources et un triage sécurisé. QUAND : déboguer des problèmes de production, résoudre les problèmes d'App Service, CPU élevé d'App Service, échec de déploiement d'App Service, résoudre les problèmes de Container Apps, résoudre les problèmes de Functions, résoudre les problèmes d'AKS, kubectl ne peut pas se connecter, échecs kube-system/CoreDNS, pod en attente, crashloop, nœud non prêt, échecs de mise à niveau, analyser les logs, KQL, insights, échecs de pull d'image, problèmes de démarrage à froid, échecs de sonde de santé,...
officialdevopsdevelopment
azure-prepare
microsoft
Préparer les applications Azure pour le déploiement (infra Bicep/Terraform, azure.yaml, Dockerfiles). Utiliser pour créer/moderniser ou créer+déployer ; pas pour la migration cross-cloud (utiliser azure-cloud-migrate). NE PAS UTILISER POUR : les applications copilot-sdk (utiliser azure-hosted-copilot-sdk). QUAND : "créer une application", "construire une application web", "créer une API", "créer une API HTTP serverless", "créer un frontend", "créer un backend", "construire un service", "moderniser une application", "mettre à jour une application", "ajouter une authentification", "ajouter un cache", "héberger sur Azure", "créer et...
officialdevelopmentdevops
azure-validate
microsoft
Validation pré-déploiement pour la préparation Azure. Effectuez des vérifications approfondies sur la configuration, l'infrastructure (Bicep ou Terraform), les attributions de rôles RBAC, les autorisations d'identité managée et les prérequis avant le déploiement. QUAND : valider mon application, vérifier l'état de préparation au déploiement, exécuter des contrôles préalables, vérifier la configuration, vérifier si prêt à déployer, valider azure.yaml, valider Bicep, tester avant le déploiement, résoudre les erreurs de déploiement, valider Azure Functions, valider l'application de fonction, valider serverless...
officialdevopstesting