Database / Azure Cosmos DB interview questions
What is a partition key in Azure Cosmos DB and why is choosing it correctly so important?
A partition key is a property you designate on every item in a Cosmos DB container. Its value is hashed to determine which logical partition the item belongs to. Cosmos DB distributes logical partitions across physical partitions (server nodes), and this is how it achieves horizontal scaling — more physical partitions means more throughput and storage capacity distributed across more servers.
The reason choosing it correctly matters so much comes down to two hard limits Cosmos DB enforces:
- A single logical partition can hold at most 20 GB of data.
- Throughput and storage cannot be rebalanced across logical partitions — you cannot move an item from one logical partition to another after it is written without deleting and reinserting it.
A poorly chosen partition key creates hot partitions — a small number of logical partitions absorbing the majority of reads and writes while others sit idle. Even if you provision 50,000 RU/s at the container level, a hot partition effectively limits you to a fraction of that because RU/s are distributed evenly across physical partitions.
A good partition key has high cardinality (many distinct values), even distribution of reads and writes across those values, and aligns with your most common query patterns so that queries stay within a single partition (cross-partition queries fan out to all physical partitions and are more expensive). For a social app, userId is typically a better partition key than country, because a small country could easily hold millions of users and hit the 20 GB ceiling.
Cosmos DB also supports a synthetic partition key — concatenating two or more properties to form a higher-cardinality value when no single field is sufficient on its own.
More Related questions...