0
0
AzureHow-ToBeginner · 4 min read

How to Choose Partition Key in Cosmos DB for Best Performance

Choose a partition key in Cosmos DB that evenly distributes data and workload across partitions. Pick a key with high cardinality and that is frequently used in queries to avoid hotspots and improve performance.
📐

Syntax

The partition key is defined when creating a Cosmos DB container. It is a property path in your JSON documents that Cosmos DB uses to group data into partitions.

Example parts:

  • /category - the property named 'category' in each document
  • /userId - the property named 'userId'
javascript
const containerDefinition = {
  id: "myContainer",
  partitionKey: {
    paths: ["/category"],
    kind: "Hash"
  }
};
💻

Example

This example shows how to create a Cosmos DB container with a partition key on the category property. This key helps Cosmos DB distribute items evenly if categories are many and balanced.

javascript
const { CosmosClient } = require("@azure/cosmos");

async function createContainer() {
  const endpoint = "https://your-account.documents.azure.com:443/";
  const key = "your-primary-key";
  const client = new CosmosClient({ endpoint, key });

  const database = client.database("myDatabase");

  const containerDefinition = {
    id: "products",
    partitionKey: {
      paths: ["/category"],
      kind: "Hash"
    }
  };

  const { container } = await database.containers.createIfNotExists(containerDefinition);
  console.log("Container created with partition key /category");
}

createContainer().catch(console.error);
Output
Container created with partition key /category
⚠️

Common Pitfalls

Common mistakes when choosing a partition key include:

  • Choosing a key with low cardinality (few unique values), causing uneven data distribution and hotspots.
  • Using a property that changes often, which can cause costly data movement.
  • Picking a key not used in queries, leading to inefficient cross-partition queries.

Always pick a stable, high-cardinality property that matches your query patterns.

javascript
/* Wrong way: low cardinality key */
const badPartitionKey = {
  paths: ["/country"], // only a few countries
  kind: "Hash"
};

/* Right way: high cardinality key */
const goodPartitionKey = {
  paths: ["/userId"], // many unique users
  kind: "Hash"
};
📊

Quick Reference

TipExplanation
Use high cardinality keyEnsures even data and request distribution.
Choose stable propertyAvoid keys that change frequently.
Match query patternsUse keys often filtered in queries.
Avoid large partitionsKeep partitions balanced in size.
Test with sample dataValidate distribution before production.

Key Takeaways

Pick a partition key with many unique values to spread data evenly.
Use a property that does not change to avoid costly data moves.
Choose a key that your queries filter on to improve performance.
Avoid keys with few distinct values to prevent hotspots.
Test your partition key choice with real data patterns before finalizing.