Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

Azure Cosmos DB Partition Key Design: How to Prevent Hot Partitions and Uneven Workload Distribution

Azure Cosmos DB Partition Key Design: How to Prevent Hot Partitions and Uneven Workload Distribution

Azure Cosmos DB partition key design showing hot partitions and balanced workload distribution

Introduction

Azure Cosmos DB partition key design is one of the most important decisions when building a scalable NoSQL database. A well-designed partition key helps distribute data and workload evenly, prevent hot partitions, optimise Request Unit (RU) consumption, and maintain consistent application performance as data grows.

Azure Cosmos DB is designed to support globally distributed, low-latency applications that handle large volumes of operational data. However, achieving that scalability depends heavily on one architectural decision: partition key design.

A Cosmos DB container may have sufficient provisioned throughput, yet some requests can experience throttling, increased latency, and inconsistent performance. In many cases, the underlying issue is not insufficient RU/s capacity but an uneven distribution of data and workload across partitions.

Consider an e-commerce platform processing thousands of customer orders every minute. If the application uses OrderStatus as its partition key, a large percentage of incoming operations may target a small number of partition values such as Pending or Processing. Other partitions may remain relatively idle while heavily accessed partitions experience throttling.

This is known as a hot partition problem.

The challenge for Azure developers and architects is to select a partition key that supports balanced data distribution, predictable query performance, efficient RU consumption, and future scalability.

In this article, we will examine how Azure Cosmos DB partitioning works, how to choose an appropriate partition key, how to identify and resolve hot partitions, when hierarchical partition keys are useful, and how to approach partition key migration when an existing design no longer meets application requirements.

Azure Cosmos DB partition key design infographic explaining hot partitions, balanced workload distribution, and partition key best practices.
How to prevent hot partitions and optimise workload distribution in Azure Cosmos DB.

Understanding Partitioning in Azure Cosmos DB

Partitioning is the mechanism Azure Cosmos DB uses to distribute data and throughput across multiple physical partitions.

A partition key determines how items are grouped and routed within a container.

There are two important concepts to understand.

Logical Partitions

A logical partition contains all items that share the same partition key value.

For example, consider an Employee container:

{
  "id": "EMP001",
  "employeeId": "EMP001",
  "employeeName": "Rahul",
  "department": "Sales"
}

If /department is selected as the partition key, all employees belonging to the Sales department are assigned to the same logical partition.

Similarly, Finance and HR employees belong to their respective logical partitions.

Each logical partition has a storage limit of 20 GB and a throughput boundary. For standard partitioning, a logical partition can consume up to 10,000 RU/s.

Physical Partitions

Physical partitions are the underlying infrastructure units managed by Azure Cosmos DB.

They store logical partitions and provide the resources required to process requests.

Azure Cosmos DB automatically distributes logical partitions across physical partitions as the container scales.

An important distinction:

  • Logical partitions are determined by partition key values.
  • Physical partitions are managed by Azure Cosmos DB.
  • Developers design logical partitioning; they do not manually assign logical partitions to physical partitions.

This distinction is essential when troubleshooting performance problems.

Architecture overview:

Azure Cosmos DB Container
          |
          v
     Partition Key
          |
          v
   Logical Partitions
          |
          v
   Physical Partitions
          |
     +----+----+
     |         |
     v         v
   Node 1    Node 2
     |         |
   Data A    Data B
   Data B    Data C

The actual mapping and distribution are managed internally by the Cosmos DB service.

Microsoft reference: Partitioning and horizontal scaling in Azure Cosmos DB.

Why Partition Key Selection Matters

Partition key selection affects much more than data placement. It influences how efficiently the application reads, writes, updates, and queries data.

An inappropriate partition key can create several problems:

  • Uneven distribution of data.
  • Hot partitions caused by concentrated request traffic.
  • Increased RU consumption.
  • Cross-partition query overhead.
  • Request throttling (HTTP 429).
  • Storage growth concentrated in individual logical partitions.
  • Difficulty scaling the application as traffic increases.

For example, consider a retail application with 10 million order records.

If all orders are partitioned using a low-cardinality property such as OrderStatus, the distribution might look like this:

Partition KeyNumber of RecordsWorkload
Pending6,000,000Very High
Processing2,500,000High
Completed1,200,000Medium
Cancelled300,000Low

The problem is not simply the number of records. It is the concentration of data and request activity around a limited number of partition key values.

A better design must consider both data distribution and actual application access patterns.

How to Choose a Partition Key in Azure Cosmos DB

Selecting the best partition key requires understanding the application’s workload before creating the container.

There is no universally correct partition key. The right choice depends on how data is accessed, how frequently records are updated, how quickly data grows, and how the workload is distributed.

Consider these five design principles.

1. Choose a High-Cardinality Property

Cardinality refers to the number of distinct values a property can contain.

A high-cardinality property offers many possible partition key values.

For example:

PropertyCardinalityAssessment
CountryLowUsually unsuitable
OrderStatusLowUsually unsuitable
DepartmentLowUsually unsuitable
CustomerIdHighPotentially suitable
DeviceIdHighPotentially suitable
TransactionIdVery HighWorkload-dependent

A high-cardinality key provides more opportunities for distributing records.

However, cardinality alone does not guarantee balanced workload distribution. If most requests target one particular customer or device, that key can still become hot.

2. Consider the Application’s Query Patterns

Partition key design must align with how the application retrieves information.

Suppose a sales application frequently retrieves orders using CustomerId.

If the container uses /customerId as the partition key, the application can retrieve an individual order using both its ID and partition key.

This enables an efficient point read.

For example:

var response = await container.ReadItemAsync<Order>(
    id: "ORD1001",
    partitionKey: new PartitionKey("CUST101")
);

The combination of item ID and partition key identifies the item directly.

By contrast, queries that do not specify a partition key may need to search across multiple partitions.

Architectural consideration: A partition key should support the application’s most important read and write operations, not simply maximise the number of distinct values.

3. Avoid Frequently Changing Properties

A partition key should be based on a stable property.

For example, CustomerId is generally more stable than OrderStatus.

If an order changes from Pending to Completed, its partition key should not need to change.

This is particularly important because the partition key value of an existing item is immutable. Moving an item to another logical partition requires creating or replacing it with an item under the new key, subject to the application’s data and identity requirements.

4. Understand Data Growth

Consider an application where a single customer generates millions of transaction records.

Even if CustomerId provides good cardinality across the overall customer population, one exceptionally active customer may create a logical partition that grows disproportionately.

A standard logical partition has a 20 GB storage limit.

Therefore, partition key design must account for:

  • Current storage requirements.
  • Expected record growth.
  • Peak transaction volumes.
  • Largest individual tenant or customer.
  • Long-term retention requirements.

5. Balance Read and Write Workloads

A key that works well for write distribution may not be ideal for read operations.

For example, using a random transaction identifier can distribute writes effectively. However, retrieving all transactions belonging to one customer may require a broader query.

A good partition key balances:

  • Write distribution.
  • Read locality.
  • Query efficiency.
  • Storage distribution.
  • Transaction requirements.

What Causes Hot Partitions in Azure Cosmos DB?

A hot partition occurs when a particular partition or a small group of partitions receives a disproportionately high volume of requests.

This can happen even when the container has sufficient total provisioned throughput.

Consider an application with 40,000 RU/s provisioned throughput.

If one partition key range is consistently consuming its available throughput while other ranges remain underutilised, requests directed to that busy range may be throttled.

Common Causes of Hot Partitions

Low-cardinality partition keys

Using properties such as Status, Category, or Country can create a limited number of logical partitions.

Uneven customer activity

One customer may generate substantially more transactions than other customers.

Time-based ingestion

If all new events are assigned to a partition representing the current date or month, incoming writes may concentrate around that key.

Large tenant workloads

In multi-tenant systems, one tenant may generate substantially more traffic than the rest.

Skewed access patterns

A property may have millions of distinct values, but application requests may repeatedly target only a small subset.

Example: Identifying a Poor Partition Key

Suppose an IoT platform collects temperature readings from thousands of devices.

A developer selects /status as the partition key.

Example documents:

{
  "id": "READ001",
  "deviceId": "DEVICE101",
  "temperature": 32.5,
  "status": "Active"
}
{
  "id": "READ002",
  "deviceId": "DEVICE102",
  "temperature": 34.1,
  "status": "Active"
}
{
  "id": "READ003",
  "deviceId": "DEVICE103",
  "temperature": 30.8,
  "status": "Active"
}

Most incoming records share the same partition key value: Active.

This creates a concentration of data and write activity.

A more appropriate design could use DeviceId or a carefully designed device-and-time hierarchy, depending on query requirements and ingestion distribution.

The important lesson is that the partition key should represent a meaningful data distribution boundary, not merely a convenient property.

How to Find Hot Partitions in Azure Cosmos DB

Identifying a hot partition requires monitoring the distribution of RU consumption rather than looking only at total container throughput.

Monitor Normalized RU Consumption

Azure Cosmos DB provides the Normalized RU Consumption metric.

This metric measures the maximum RU/s utilisation across partition key ranges during a monitoring interval.

Navigate to:

  1. Open the Azure Portal.
  2. Select your Azure Cosmos DB account.
  3. Open Insights.
  4. Navigate to Throughput.
  5. Select Normalized RU Consumption (%) By PartitionKeyRangeID.
  6. Filter the metrics for the required database and container.

Look for partition key ranges that consistently show significantly higher utilisation than others.

For example:

Partition Key RangeNormalized RU Consumption
Range 095%
Range 128%
Range 235%
Range 322%

This indicates a potentially uneven throughput distribution.

However, a single spike does not automatically prove that the partition key design is defective. Investigate the duration, request patterns, throttling, and workload characteristics.

Use Diagnostic Logs

For more detailed analysis, enable the appropriate diagnostic settings and send resource logs to Log Analytics.

The CDBPartitionKeyRUConsumption table provides information about RU consumption by logical partition key and physical partition range.

Example KQL query:

CDBPartitionKeyRUConsumption
| where TimeGenerated > ago(1h)
| summarize TotalRU = sum(RequestCharge)
    by PartitionKey, PartitionKeyRangeId
| order by TotalRU desc
| take 20

This query helps identify logical partition key values that are consuming the most request units.

You can also investigate operations over time:

CDBPartitionKeyRUConsumption
| where TimeGenerated > ago(30m)
| summarize TotalRU = sum(RequestCharge)
    by bin(TimeGenerated, 5m),
       PartitionKeyRangeId
| order by TimeGenerated asc

This helps identify whether a particular physical partition range experiences sustained or periodic workload concentration.

Important: High RU consumption alone does not establish a hot partition. Correlate these results with normalized RU consumption, 429 responses, latency, and application request patterns.

Microsoft references:

How to Prevent Hot Partitions in Azure Cosmos DB

Preventing hot partitions starts with the data model, but it also requires workload analysis and operational monitoring.

Use High-Cardinality Partition Keys

Choose properties that distribute records across a sufficiently large number of values.

For example:

  • CustomerId instead of Country.
  • DeviceId instead of DeviceStatus.
  • AccountId instead of AccountType.

Validate that the application actually distributes requests across those values.

Use Synthetic Partition Keys

A synthetic partition key combines multiple properties into one partition key value.

For example:

{
  "id": "ORDER1001",
  "tenantId": "TENANT01",
  "customerId": "CUSTOMER105",
  "orderId": "ORDER1001",
  "partitionKey": "TENANT01_CUSTOMER105"
}

The container can use /partitionKey as its partition key.

This approach can improve distribution when the original property alone creates insufficient cardinality.

However, synthetic keys require careful consideration of query patterns and data access.

Use Write Sharding When Necessary

Write sharding distributes high-volume writes across multiple partition key values.

For example, a system receiving large volumes of events from one device could distribute writes using a controlled bucket:

DEVICE101_00
DEVICE101_01
DEVICE101_02
DEVICE101_03

The application assigns writes across these buckets.

This reduces the concentration of writes on one logical partition.

However, the application may need to query multiple buckets to retrieve all records for the device.

It also introduces additional complexity in aggregation, query routing, and transactional operations.

Use this pattern only when the workload justifies it.

Consider Hierarchical Partition Keys

Hierarchical partition keys are particularly useful for workloads that need logical grouping as well as more granular distribution.

For example:

TenantId
    |
    v
CustomerId
    |
    v
OrderId

The hierarchy allows queries using leading key prefixes to target relevant subsets of data.

However, the first-level key must also be considered carefully. If there are only a few large tenants, the first-level distribution can constrain ingestion across physical partitions.

Hierarchical partitioning is not an automatic solution to every hot partition problem.

Scale Throughput Only After Diagnosing the Root Cause

Increasing RU/s may help when the workload genuinely requires more capacity.

However, if requests are concentrated on one logical partition, increasing total throughput may not eliminate the underlying bottleneck.

First identify the hot key and determine whether the issue comes from:

  • Poor partition key selection.
  • An unusually active tenant.
  • A write burst.
  • An expensive query.
  • An application access-pattern problem.

Then decide whether to optimise the data model, application queries, throughput, or a combination of these.

Hierarchical Partition Keys: When Should You Use Them?

Hierarchical Partition Keys (HPK), also called subpartitioning, allow developers to define up to three levels of partition key hierarchy in Azure Cosmos DB for NoSQL.

They are useful when a single partition key does not provide sufficient distribution or when a business workload requires data to be grouped by multiple dimensions.

Example: Multi-Tenant Application

Consider a SaaS platform serving multiple organisations.

A possible hierarchical partition key is:

/tenantId
/customerId
/orderId

Example document:

{
  "id": "ORDER1001",
  "tenantId": "TENANT01",
  "customerId": "CUSTOMER105",
  "orderId": "ORDER1001",
  "amount": 12500
}

Queries that specify the leading hierarchy values can be efficiently routed to the relevant subset of partitions.

For example, retrieving orders for a tenant and customer can use both values.

Hierarchical Partition Keys vs Single Partition Keys

AreaSingle Partition KeyHierarchical Partition Key
Key structureOne propertyMultiple levels
Data groupingOne dimensionMultiple dimensions
Query routingBased on one keySupports leading key prefixes
Large tenant workloadsMay create a large logical partitionCan distribute data across subpartitions
Design complexityLowerHigher
Best suited forStraightforward workloadsComplex multi-dimensional workloads

Important Design Considerations

  • All levels should be evaluated for cardinality and workload distribution.
  • Queries using leading key prefixes can be routed efficiently.
  • Queries using only a middle-level key are cross-partition queries.
  • The complete hierarchical key combination defines a logical partition.
  • The standard 20 GB logical partition limit still applies to a complete key combination.

A particularly important consideration is that low cardinality at the first hierarchy level can limit ingestion distribution. Cosmos DB intentionally colocates items sharing the first-level key to support efficient prefix queries.

Therefore, a hierarchy such as TenantId → CustomerId should be evaluated against the number of active tenants and the write distribution across them.

Microsoft reference: Hierarchical partition keys in Azure Cosmos DB.

Azure Cosmos DB Partition Key Examples for Common Data Models

Partition key design should be specific to the business workload.

The following examples illustrate possible approaches rather than universal recommendations.

ApplicationPossible partition keyImportant consideration
E-commerce ordersCustomerIdSupports customer-centric queries
Multi-tenant SaaSTenantId or hierarchical tenant keyAccount for tenant size and activity
IoT telemetryDeviceId or device/time hierarchyAvoid concentrating high-rate ingestion
User activity trackingUserIdConsider unusually active users
Financial transactionsAccountIdConsider transaction volume per account
Product catalogueCategoryId or ProductIdBalance category queries and item access

E-Commerce Application

If customers frequently view their own order history, CustomerId can be a reasonable partition key.

However, if the application frequently queries orders by OrderId without knowing the CustomerId, additional access-pattern considerations are required.

Multi-Tenant SaaS Application

TenantId is a natural grouping property.

However, a large tenant may generate disproportionate traffic.

Hierarchical keys such as TenantId followed by CustomerId may help distribute that tenant’s data across smaller logical partitions while preserving tenant-level query routing.

The first-level tenant distribution still needs to be evaluated.

IoT Application

For an IoT platform, DeviceId may provide good cardinality.

However, a small number of high-volume devices can still create hot partitions.

A device-and-time hierarchy or controlled write-sharding strategy may be appropriate, depending on ingestion rate, retention, and query requirements.

How Partition Keys Affect RU Consumption and Query Performance

Request Units (RUs) represent the resources consumed by database operations in Azure Cosmos DB.

Read operations, write operations, and queries consume RUs based on their execution requirements.

Partition key selection affects the routing of these operations.

Point Reads

A point read uses both the item ID and partition key value.

var response = await container.ReadItemAsync<Order>(
    "ORDER1001",
    new PartitionKey("CUSTOMER105")
);

This allows Cosmos DB to directly locate the item.

Cross-Partition Queries

Consider a query that retrieves orders without specifying the partition key:

SELECT *
FROM c
WHERE c.status = "Pending"

If the partition key is CustomerId, the query may need to search across multiple partitions.

This is called a cross-partition query.

Cross-partition queries are supported, but they can consume more RUs and increase latency depending on the amount of data examined and the number of partitions involved.

RU Optimisation Strategies

  • Include the partition key in queries whenever the access pattern allows it.
  • Use point reads for individual item retrieval.
  • Avoid retrieving unnecessary properties.
  • Design queries around the application’s most frequent operations.
  • Review indexing policies.
  • Monitor RU consumption for expensive operations.
  • Avoid unnecessary cross-partition fan-out.

Architectural lesson: A good partition key is not simply one that distributes writes. It should also support efficient reads and queries.

Can You Change the Partition Key in an Existing Azure Cosmos DB Container?

This is one of the most important questions developers encounter when an application outgrows its original data model.

Traditionally, the partition key path is defined when a container is created and cannot simply be modified in place.

However, Microsoft now documents a portal-based Change Partition Key capability for Azure Cosmos DB for NoSQL.

This feature works by creating or selecting a destination container and copying the data using container copy jobs. It does not mutate the original container’s partition key definition.

How to Change a Partition Key

A typical migration involves:

Step 1 – Analyse the Existing Workload

Identify the problems with the current partition key.

Examples:

  • Hot partitions.
  • Uneven RU consumption.
  • Storage growth.
  • Expensive cross-partition queries.

Step 2 – Design the New Partition Key

Evaluate the application’s query patterns, cardinality, storage requirements, and workload distribution.

Step 3 – Create a Destination Container

Create a new container with the desired partition key and appropriate indexing and throughput configuration.

Step 4 – Copy Existing Data

Use the supported container copy mechanism.

For offline migration, writes to the source are stopped during the copy process.

For online migration, the supported copy process replicates changes while the source continues to receive operations.

Step 5 – Validate the Destination

Validate:

  • Document counts.
  • Data integrity.
  • Partition key values.
  • Unique key constraints.
  • Query behaviour.
  • RU consumption.
  • Application functionality.

Step 6 – Switch Application Traffic

Update the application configuration to use the destination container.

Step 7 – Monitor and Retire the Old Container

Monitor the new workload and retain the old container until the migration and rollback requirements are satisfied.

Important Migration Considerations

The documented portal-based partition key change capability has eligibility restrictions, including throughput below 1,000,000 RU/s and storage below 4 TB, along with region and account capability restrictions.

Online copy also has prerequisites, including continuous backup and all versions and deletes change feed mode. Online copy introduces additional RU charges for replace and delete operations.

Container copy jobs are documented as a preview capability, so verify current regional availability and limitations before planning a production migration.

References:

Common Partition Key Design Mistakes

MistakeWhy it causes problemsBetter approach
Selecting Status as the keyLow cardinalityUse a more distributed business identifier
Selecting Country as the keyLimited valuesEvaluate customer or transaction identifiers
Ignoring query patternsExcessive cross-partition queriesDesign around actual access patterns
Using only a random identifierPoor query locality for business dataBalance distribution and retrieval
Ignoring large tenantsUneven RU consumptionConsider hierarchical or sharded designs
Using time as the only keyConcentrated current-period writesEvaluate time-bucketed and device/customer keys
Increasing RU/s without investigationDoes not correct key skewDiagnose the workload first
Ignoring logical partition growthRisk of storage limitsForecast data growth and consider HPK

Production Readiness Checklist

Before deploying a Cosmos DB container, review the following questions:

  • Does the partition key have sufficient cardinality?
  • Is the distribution of data reasonably balanced?
  • Are requests distributed across key values?
  • Does the key support the application’s common query patterns?
  • Can any individual logical partition approach the 20 GB limit?
  • Are there unusually active tenants, customers, or devices?
  • Are point reads using both the ID and partition key?
  • Are cross-partition queries justified?
  • Have RU consumption and 429 responses been monitored?
  • Is there a migration strategy if the data model changes?
  • Have realistic production-scale workloads been tested?

A partition key should be treated as an architectural decision, not merely a container configuration setting.

Conclusion

Azure Cosmos DB can scale to demanding enterprise workloads, but its performance depends significantly on how data and requests are distributed.

Choosing a partition key based only on convenience can introduce hot partitions, uneven RU consumption, expensive cross-partition queries, and migration challenges.

A reliable design starts with understanding the application’s read and write patterns, evaluating key cardinality, forecasting data growth, and validating workload distribution under realistic conditions.

For complex multi-tenant and high-volume applications, hierarchical partition keys and controlled write-sharding strategies can provide additional design flexibility. However, they must be evaluated carefully against query requirements and operational complexity.

The real objective is not simply to distribute data across partitions. It is to design a data access strategy that remains efficient, predictable, and maintainable as the application grows.

Build Your Azure Cloud and Database Engineering Skills with Softchief Learn

Want to understand how Azure services work in real-world enterprise applications?

Softchief Learn focuses on practical Microsoft technology training, including Azure architecture, cloud development, .NET, Dynamics 365, Power Platform, and enterprise integration.

Explore implementation-oriented learning and develop the technical skills required to work on real-world Microsoft technology projects.

Explore our upcoming Live Webinars featuring expert-led sessions on Microsoft Azure, Dynamics 365, Power Platform, and AI technologies.
Register now:

Interested in Azure training and practical implementation guidance?

Connect with our training team: WhatsApp: https://wa.me/918328865778

Softchief Learn – Learn. Build. Implement.

Softchief Microsoft Azure training and implementation support from Microsoft MVP Sanjay Prakash
Need Azure training or implementation support? Get expert guidance from Softchief Technologies.

 

Leave a Reply