# How to choose a partition key in Azure Cosmos DB

# Azure Cosmos DB is highly scalable

One of the best features of Azure Cosmos DB (opens new window) is that it's incredibly fast. And that is because it uses a partitioning system (opens new window) to scale, which consists of physical and logical partitions.

To optimize the scalability and performance of Azure Cosmos DB, you need to choose the right partition key (opens new window) for your container. In this post, we'll go through the best practices to choose your partition key.

# Prerequisites

If you want to follow along, you'll need the following:

# Choosing your partition key

You choose a partition key when you create a container in Azure Cosmos DB. Note that you can't change the partition key of a container. If you do need to change it, you need to migrate the container data to a new container with the correct key.

A partition key consists of a path, like "/firstname", or "/name/first". You can use alphanumeric and underscore characters in the path.

The partition key needs to be a JSON property in the documents that you store in the container. So in the JSON snippet below, the partition key path could, for instance, be firstname.

{
    "firstname": "Véronique",
    "age": 50,
    "id": "61fb344e-279d-4185-957d-e88bb1101dba",
    "_rid": "mYw7AJk8AbkDAAAAAAAAAA==",
    "_self": "dbs/mYw7AA==/colls/mYw7AJk8Abk=/docs/mYw7AJk8AbkDAAAAAAAAAA==/",
    "_etag": "\"03000091-0000-0700-0000-607d80580000\"",
    "_attachments": "attachments/",
    "_ts": 1618837592
}
1
2
3
4
5
6
7
8
9
10

So how do you pick the best partition key for your container?

  1. You should pick a property that you do not update later
  2. The partition key should be a property that exists in every document in the container
  3. The partition key property should have a large range of possible values. This optimizes the amount of logical partitions that the key creates. "id" has a lot of values
  4. The value of the partition key can be of string or numeric types

Here's the exception to the best practices above: If your container is large and read-heavy (i.e., more then 30.000RUs and larger than 100GB), the key should be something that is often filtered on in queries. For instance, if your queries filter on "postalcode" often that could be a good partition key.

# Conclusion

When you choose the right partition key for your Azure Cosmos DB container (opens new window), you optimize performance. Try it out!