Domain 1 of 3 · Chapter 3 of 5

Design and implement data models and partitioning strategies

Design items around access patterns, not tables

Picture an application screen that shows one person with all of their contact details and addresses. In a relational database that person is spread across a Person table, a ContactDetail table and an Address table, and every read rebuilds the person with JOINs. In Azure Cosmos DB for NoSQL the same person is usually one JSON item with contactDetails and addresses arrays inside it, so retrieving the complete record is a single read of a single item, and updating it is a single write[1]. The query language cannot rebuild the relational version for you: a JOIN works within a single item, typically between the root item and a nested array, and never joins items across containers or across top-level items[1]. A design that copies each relational table into its own container therefore leaves the application to reassemble every entity with extra requests.

Shaping items, choosing partition keys and estimating cost belong to one outline item: the Microsoft DP-420 study guide skills measured[2] lists 'Design data models for access patterns and operational requirements', 'Design and select partition keys based on cardinality, access patterns, and write distribution requirements' and 'Estimate workload cost requirements' under Design and implement data models and partitioning strategies (Design and develop database solutions), and lists 'Implement create, replace, update, patch and delete operations' under Implement database operations and 'Evaluating and configuring appropriate throughput' under Evaluate resource models and SDK solutions.

Start from the access patterns

Microsoft frames data modeling around three questions: how the data is stored, how the application retrieves and queries it, and whether the application is read-heavy or write-heavy[1]. When moving from a relational database, design each item around the way your application reads and writes that data[1], not around the source tables. A flexible schema does not remove that work; it removes only the fixed table layout.

Several item types can share one container

A container does not have to hold a single entity type. When related entities are read together, you can mix item types in one container so that related items sit in the same partition, for example books and their reviews partitioned by bookId, and add a field to each item that identifies its type[1]. The shared partition-key value places a book and its reviews in the same logical partition (the group of items that share one partition-key value, explained in How partitions work below), and the type field lets a query select only books or only reviews.

Listing: a book and two reviews stored as three items in one container partitioned by /bookId

{ "id": "b1", "bookId": "b1", "type": "book", "name": "Azure Cosmos DB 101" }
{ "id": "r1", "bookId": "b1", "type": "review", "content": "This book is awesome" }
{ "id": "r2", "bookId": "b1", "type": "review", "content": "Best book ever!" }

The listing shows three separate items, one per line. All three carry bookId = "b1", the partition-key value, so a query such as SELECT * FROM c WHERE c.bookId = 'b1' AND c.type = 'review' reads only that book's logical partition. The type property is an application convention (often called a type discriminator), not a reserved system property, and a separate container per entity type is not required just because the JSON shapes differ.

Separate data that is written independently

The same access-pattern test can argue for splitting one entity. Microsoft's guidance is to use references when related entities are large, unbounded, or updated independently[1], that is, to store the related data as separate items connected by an identifier (see Embed or reference related data below). A product with a large, rarely changing description and a small, frequently replaced status block is the typical case: in one item, every full replacement of the status also rewrites the whole description. Storing the status as its own item keeps the frequently written unit small. Partial document update (the Patch API)[3] sends only the modified fields instead of a whole-document replace, which reduces the update payload, but it does not change what a read returns or turn two independently accessed parts into one natural read unit.

The takeaway: list the reads and writes first, then make each item the unit that those operations touch together.

JSON representation: item size, numbers, and dates

Every item is stored as JSON, so three representation choices made early are hard to undo later: how large an item may grow, how numbers are stored, and how dates are stored.

Item size

The maximum size of an item is 2 MB, measured as the UTF-8 length of its JSON representation[4]. Apart from that size and the length limits on partition-key and id values, there is no practical limit on the number of properties, but embedded objects and arrays have a maximum nesting depth of 128 levels[4]. The 2 MB budget covers the whole item, embedded arrays and objects included, so an entity whose embedded collection keeps growing eventually stops fitting (the next section shows how to avoid that). Splitting a large entity into several items keeps each one under the limit, but retrieving the pieces may add work and charges, and only pieces that share one logical partition can still be written in one transaction.

Numbers

Azure Cosmos DB saves documents as JSON, and Microsoft recommends that you convert numbers to strings if they might exceed the boundaries of IEEE 754 binary64 double-precision numbers[1], because numbers beyond those boundaries cause interoperability problems between JSON implementations. The risk is lost precision, not only size: a large exact identifier from another system is the typical case, and for a numeric partition key an error can report a possible loss of precision of the partition-key value, so Microsoft suggests a string partition key if you require precise numeric values[5]. The advice matters most for the partition-key property: because the partition key is immutable, fixing it later requires a data migration[1].

Dates

JSON, and therefore Cosmos DB, has no DateTime type; date and time values are stored with the basic JSON types[6]. Two representations are documented:

Representation JSON type Example value Behavior
ISO 8601 UTC string (recommended) string "2014-09-15T23:14:25.7251173Z" sorts correctly as text; range filters need every value in UTC
Unix timestamp number 1410822865 elapsed seconds since January 1, 1970, the same form as the system _ts property

The recommended string format is yyyy-MM-ddTHH:mm:ss.fffffffZ in UTC, which keeps lexicographic sorting correct, and range queries on date strings are supported only if all the strings are UTC[6]. The alternative is a Unix timestamp, a number of elapsed seconds since January 1, 1970, which is how the internal _ts property is stored[6]. The two are not interchangeable: choose one representation per property and pass query parameters in that same form, an ISO 8601 string for string dates and a number of seconds for timestamps. The GetCurrentDateTime system function returns the current UTC date and time as an ISO 8601 string[6], so it matches the string representation.

The takeaway: budget each item against 2 MB, store large exact identifiers as strings (above all in the partition key), and pick one date representation per property.

Embed or reference related data

Embedding versus referencing is the central relationship decision, and the documentation gives explicit criteria for each side. Embedding (also called denormalizing) stores related data inside the parent item; referencing (also called normalizing) stores it as separate items connected by an identifier.

The two rule sets

Use embedded data models when relationships are contained, when they are one-to-few, when the data changes infrequently, when it does not grow without bound, and when it is queried frequently together[1]; denormalized models typically give better read performance[1]. Use normalized models for one-to-many and many-to-many relationships, when related data changes frequently, and when referenced data could be unbounded[1]; normalizing typically gives better write performance, but normalized models can need more round trips to the server[1].

A person's few contact details and addresses pass every embedding test, so they belong in the person item; referencing them would add round trips and avoid no growth or update cost. The figure below applies the rules in a fixed order: growth first, then whether the data is updated often or independently of the parent, then whether it is read with its parent.

Unbounded collections

A blog post with an embedded comments array has no practical limit on how many comments it can hold, so the item can grow without limit[1], and as an item grows, transmitting, reading and updating it at scale becomes harder[1], with the 2 MB item limit as the hard ceiling. The documented fix is an item per comment carrying the post identifier, with postId as the partition key of the comments[1], so "all comments for one post" stays a single-partition query.

Shared data that changes often

Embedding stock information in every portfolio means updating every portfolio that holds a stock each time that stock trades[1], potentially thousands of items many times a day. Referencing the stock instead means only the single stock item is updated[1]; the cost is that the application must make several requests to show the stocks in a portfolio[1].

Put the reference on the side that grows

A list of identifiers can also grow without bound. A publisher item that lists the ids of all its books becomes a mutable, growing array when the number of books is unbounded; storing the publisher id on each book instead removes the unbounded collection[1]. Replacing embedded child objects with an unlimited array of child ids in the same parent only moves the problem.

References are not foreign keys

There is no foreign-key constraint: the database does not verify relationships between items, so these links are "weak"; if the referenced item must exist, check it in the application or with server-side triggers or stored procedures[1]. Stored procedures and triggers act only within one logical partition (see How partitions work below). Nothing cascades either: creating a comment with a postId does not link anything in the database, and deleting a post leaves its comments in place until your code removes them.

The takeaway: ask whether the related data can grow without bound, whether it is updated often or independently (shared data that changes often can multiply update work), and whether it is read with its parent; data that is bounded, stable and read together is a good candidate for embedding.

Can the related datagrow without bound?Reference fromthe growing sideYesNoUpdated often orindependently?Reference asseparate itemsYesNoRead togetherwith the parent?Embed in theparent itemYesNoReference asseparate items
Embed-or-reference decision for related data, applying the growth, update and read-together rules in order.

Hybrid modeling techniques

Real designs rarely sit at either extreme, and mixing embedded and referenced data can simplify application logic, reduce server round trips and keep performance good[1]. This section covers four documented hybrid techniques: reference arrays for many-to-many relationships, duplicated display fields, a bounded embedded subset, and precomputed aggregates.

Many-to-many relationships without join items

Copying a relational join table into "joining" items works, but loading an author with their books, or a book with its author, then always needs at least two extra queries: one to the joining item and one to the item being joined[1]. Dropping the joining items and storing a books id array on each author and an authors id array on each book[1] answers both lookup directions from the item already read. Microsoft summarizes this as replacing join tables with reference arrays or duplicated read-optimized projections that match the query patterns[1]. The arrays must stay bounded, by the growth rule from the previous section.

Duplicate stable display fields beside the reference

Microsoft's book example keeps the authors reference array from the many-to-many case and adds each author's name and thumbnail beside the author id[1]:

Listing: a book item that references its authors and copies two display fields of each

{
  "id": "b1",
  "name": "Azure Cosmos DB 101",
  "authors": [
    { "id": "a1", "name": "Thomas Andersen", "thumbnailUrl": "https://....png" },
    { "id": "a2", "name": "William Wakefield", "thumbnailUrl": "https://....png" }
  ]
}

In each authors entry, id is the reference to the complete author item, while name and thumbnailUrl are copies (the ....png URLs are shortened placeholders). Because the application displays each author's name and thumbnail with every book, denormalizing some author data reduces round trips per book in a list; if an author changes their name or photo, every book they published must be updated, which is acceptable when those fields rarely change[1]. The full author item stays the authoritative copy for every other read and update.

Embed a bounded recent subset

A post can embed only its most recent comments in a recentComments array while every comment is also stored as its own item with the post's id[1]. The common "show the post" read stays one read, and the embedded array stays small because the application keeps only a fixed number of recent entries in it. Keeping the duplicated comments consistent is the application's job.

Precompute aggregates on the write path

An author item can store a countOfBooks value that is recalculated each time a book is published, saving expensive processing on reads; this optimization suits read-heavy systems that can afford computation on writes[1]. Embedding every child just to display a count would be the wrong fix when the children are unbounded. Microsoft's worked example adds commentCount and likeCount to each post: because the container is partitioned by postId, a new comment and its post sit in the same logical partition, so a stored procedure creates the comment and increments the count as one atomic transaction, keeping the count in sync[7]. Transactional batch operations from the client SDK[8] give the same atomicity for items with one full partition-key value (taught in Implement database operations). When the copied data lives in another partition or container, such as a username copied into posts, Microsoft's example reads the source container's change feed and, for each username change, calls a stored procedure on the posts container that updates the copies[7]: the feed only records the change, and that consumer does the propagation, which is not a single transaction (see Implement change feed).

The takeaway: favor duplicating display fields that common reads need and that rarely change, keep every embedded array bounded, and keep a precomputed value in the same logical partition as its sources when it must never drift.

Versioning and history patterns

Overwriting an item keeps only its current state. When an application must answer "what did this look like last week?", the history has to be modeled explicitly, and Microsoft says to choose a versioning pattern based on retention requirements, query latency goals and cost limits[1].

Replacing a current-state item leaves no archive behind, and the change feed does not create one either: in latest version mode, if an item is created and then updated before you read the change feed, only the updated version appears[9] (see Implement change feed). Three documented patterns keep the history as items in the container; the third uses time to live (TTL) to age out older versions automatically[1]:

Pattern What is stored Storage cost Reading history Write cost
Event sourcing every mutation as a new event item higher over time point-in-time reads need reconstruction or read-optimized projections an extra write per mutation, simple and scalable
Snapshot plus delta periodic full snapshots plus deltas between them lower than full copies of every version replay the deltas after the closest snapshot small frequent deltas plus scheduled snapshots
TTL-based version expiry historical versions that expire; current version kept predictable and bounded low to moderate, limited by the retention window similar to the pattern TTL is combined with (below), plus background deletes

Event sourcing

Use an append-only model in which each mutation is written as a new event item, and use change feed design patterns to project current state into one or more materialized views[1]. The retained event items are the history; the projections serve fast current-state reads.

Snapshot plus delta

Store periodic full snapshots of an entity plus incremental deltas between them; to read a historical version, load the closest snapshot and apply later deltas up to the target timestamp[1]. This trades storage for replay work: storage is lower than keeping every version as a full copy, especially for large items with small changes, while historical reads might replay several deltas[1].

Expiring old versions with TTL

A common approach sets the container's TTL to -1 and assigns ttl only to historical version items[1], so old versions age out while the current version is kept indefinitely (see Implement database operations). Teams often combine the patterns, for example event sourcing or snapshots for retention and TTL for lifecycle control[1].

The takeaway: when history matters, store it as items (events, or snapshots plus deltas); overwriting in place and reading the latest-version change feed later does not recover intermediate states.

How partitions work: logical and physical partitions, hash placement

Partitioning is how a container scales, and every partition-key decision in the rest of this topic is a decision about the structures this section describes. The items in a container are divided into logical partitions, formed by each item's partition-key value; all items in one logical partition have the same partition-key value[10]. The partition key together with the item id uniquely identifies an item[10], which is why a point read (a direct lookup of one item by its id and its partition-key value, the cheapest way to fetch a single item) always needs both.

Logical partitions

There is no limit to the number of logical partitions in a container, and each logical partition can store up to 20 GB of data[10]. A logical partition also defines the scope of database transactions[10]: multi-item transactions, transactional batches, stored procedures and triggers work only on items that share the same full partition-key value[8] ("full", sometimes written "complete": for a single-path key, simply its value; for a hierarchical partition key, the values of all its levels together, as Hierarchical partition keys below explains; a "full logical partition" is the partition of one such value, not a partition that is full). Throughput is capped as well, in request units per second (RU/s; a request unit is the performance currency in which Azure Cosmos DB measures every database operation[11], see Evaluate resource models and SDK solutions): each physical partition provides up to 10,000 RU/s, and because each logical partition maps to only one physical partition, logical partitions also have a 10,000 RU/s limit[10]. Azure Cosmos DB stops ingesting data for a partition-key value that exceeds 20 GB[12].

Physical partitions

A container scales by distributing data and throughput across physical partitions; one or more logical partitions map to a single physical partition, and Azure Cosmos DB manages physical partitions entirely[10]. Each physical partition provides up to 10,000 RU/s and stores up to 50 GB[10], so both provisioned throughput and total storage decide how many there are. As throughput or data grows, the service splits physical partitions without affecting availability; after a split, all data of a single logical partition is still on the same physical partition, because a split only creates a new mapping of logical partitions to physical partitions[10].

Hash-based placement

Azure Cosmos DB hashes each item's partition-key value and allocates the key space of those hashes evenly across the physical partitions[10]. Placement follows the hash, not the visible value, so alphabetically adjacent tenant names or consecutive order numbers say nothing about which physical partition holds them.

The figure below shows the nesting: a container holds physical partitions, and each physical partition holds whole logical partitions (keys A to E stand for five partition-key values).

What the structure means for throughput

Provisioned throughput for a container is divided evenly among its physical partitions[10]. In Microsoft's example, 18,000 RU/s over three physical partitions gives each physical partition 6,000 RU/s, which the logical partitions on it share collectively[10]: logical partitions do not each receive their own slice. A key that directs too many requests to a few partitions makes them "hot", which uses provisioned throughput inefficiently and can cause rate limiting and higher costs[10]. Raising the container's RU/s adds capacity across physical partitions but cannot lift one logical partition above 10,000 RU/s, and a split never divides a hot logical partition.

Spreading data also affects queries: when a query does not include the partition key, checking each additional physical partition costs about 2 to 3 RU[10], while with one physical partition or only a few (for example five or fewer), the partition-key value might not matter for queries[10].

The takeaway: the logical partition is the unit you design (its key, its 20 GB and 10,000 RU/s ceiling, its transaction scope); physical partitions are managed for you and only multiply capacity across many keys.

ContainerPhysical partition 1up to 50 GB and10,000 RU/sLogical: key ALogical: key BLogical: key CPhysical partition 2up to 50 GB and10,000 RU/sLogical: key DLogical: key EEach logical partition: up to20 GB and 10,000 RU/sSplits move whole logical partitions
How one container nests physical partitions and whole logical partitions, with the documented storage and throughput limits of each.

Choosing a partition key

Because a partition key cannot be changed in place, start from the strategy. Microsoft compares four partitioning strategies[10]: a regular partition key (one existing property with high cardinality that aligns with query patterns), a synthetic partition key (no single field has both, often under heavy writes; see Synthetic partition keys), a hierarchical partition key (HPK; queries filter on the leading levels of a multi-level key; see Hierarchical partition keys), and a global secondary index (GSI; no single key serves every query pattern), which adds a synchronized container under another key rather than replacing the container's key (last subsection below). For all containers, Microsoft says the partition key should[10]:

  • be a property whose value does not change, because an item's partition-key value cannot be updated;
  • contain only string values, or numbers converted to strings when they might exceed double precision;
  • have high cardinality, meaning a wide range of possible values;
  • spread RU consumption and data storage evenly across logical partitions;
  • have values no larger than 2,048 bytes, or 101 bytes if large partition keys aren't enabled.

Cardinality is necessary, not sufficient

A key with millions of possible values can still concentrate load. A key that seems to have high cardinality, such as UserId, still produces a hot partition if the workload operates on just one specific UserId[12]. In a review, check where the busiest values and the fastest-growing data land, not only how many values exist.

Read-heavy containers: match the equality filter

A cross-partition query runs against more than one physical partition: a fan-out query checks every physical partition, while a targeted one is scoped to only a few[13]. For large read-heavy containers, choose a partition key that appears frequently as a filter in queries, so that queries are routed only to the relevant physical partitions; if most requests are queries and most queries use an equality filter on UserID, then UserID reduces cross-partition queries[10]. Container size decides how much this matters: most small containers need only one or two physical partitions, while a container with over 30,000 RU/s provisioned or over 100 GB of data needs more than a few, and then the key should minimize cross-partition queries[10]. A random GUID that queries never filter on distributes writes well but turns most reads into cross-partition queries[10].

The item id as partition key

Using /id maps each item to its own logical partition: excellent write distribution, and low-latency, low-RU point reads because knowing an item's id means knowing its partition key[10]. It suits small read-heavy containers and write-heavy containers of any size[10]. The caveats: a query that filters only on other properties, without an equality filter on id, is cross-partition[10], the id becomes unique across the whole container, and stored procedures or triggers cannot target multiple logical partitions[10]. An order whose line items have different ids can therefore never be written as one transaction.

Immutability of the path and of the values

Once you select a partition key you can't change it in place; to change it, move the data to a new container with the desired key[10], for example with a container copy job (taught in Implement change feed). Partition-key values are immutable too: a replace operation requires the key to match the existing item and cannot move it, so moving an item means creating a new item with the new value and deleting the original, and those two operations cannot be performed atomically across logical partitions[10].

Key length is measured in bytes

The maximum length of a partition-key value is 2,048 bytes, or 101 bytes if large partition keys aren't enabled[4]. The limit counts bytes, not visible characters: check a concatenated key's encoded length, because in UTF-8 non-ASCII characters take more than one byte each.

A second access path: global secondary indexes

GSIs are read-only containers with their own partition key, automatically synchronized with the source container[14], and they are eventually consistent with the source regardless of the account's consistency level[14]. They add cost: each GSI has additional storage and RU costs[10], the change feed reads that sync it consume RUs on the source while its writes consume RUs on the GSI, and replace and delete operations on the source cost an extra 50 to 100% of the base write charge[14]. Adding a GSI is also an alternative to moving data when a different key is needed[10].

The takeaway: pick an immutable, string-valued property with many values that spread real load, align it with the dominant equality filter, and budget a GSI when one key cannot serve two independent query patterns.

Hierarchical partition keys: limits and definition

A hierarchical partition key (HPK) defines the partition key as an ordered list of up to three property paths, such as /TenantId, /UserId, /SessionId; Microsoft also calls the feature subpartitioning[12]. It solves one problem: with hierarchical partition keys, a logical partition key prefix can exceed 20 GB and 10,000 RU/s, and queries by prefix are routed efficiently to the subset of partitions that hold the data[12].

The prefix scales; each full key does not

An HPK raises no limit: it lets one prefix spread across many full keys, and each full combination of TenantId, UserId and SessionId remains one capped logical partition. With an HPK, the logical partition is the entire partition-key path: partitioned by TenantId and then UserId, one logical partition is a value such as Contoso_Alice, still limited to 20 GB, while the storage available to tenant Contoso becomes 20 GB times its number of unique UserIds[15]. Physical partitions keep their 50 GB and 10,000 RU/s limits, but when one TenantId's data spans several physical partitions, the total RU/s for that TenantId can exceed 10,000[15].

Defining the key when the container is created

In an Azure Resource Manager template, the partitionKey object lists the paths (at most three levels), with kind set to MultiHash and version set to 2[12]. The order of the paths array is the hierarchy; it is not one concatenated value. No new combined property is needed: each item simply carries its own TenantId and UserId properties[15]. Hierarchical partition keys can be set only when a container is created; to adopt one, create a new container with the hierarchy and copy the data with a container copy job[12].

Listing: creating a TenantId, UserId, SessionId container with the .NET SDK and the Python SDK

// ... (client and database setup omitted)
// The list order is the hierarchy order: up to three levels.
List<string> subpartitionKeyPaths = new List<string> { "/TenantId", "/UserId", "/SessionId" };
ContainerProperties containerProperties = new ContainerProperties(
    id: "<container-name>",
    partitionKeyPaths: subpartitionKeyPaths);
Container container = await database.CreateContainerIfNotExistsAsync(containerProperties, throughput: 400);
from azure.cosmos import PartitionKey
# ... (client and database setup omitted)
# A list of paths plus kind="MultiHash" makes the key hierarchical.
container = database.create_container(
    id=container_name,
    partition_key=PartitionKey(path=["/TenantId", "/UserId", "/SessionId"], kind="MultiHash"),
)

Both listings follow Microsoft's SDK examples[12]. In .NET, ContainerProperties accepts the ordered partitionKeyPaths list; in Python, the path argument of PartitionKey takes the list and kind="MultiHash" marks it hierarchical. The throughput: 400 value is the example's choice, not a requirement, and defining several unrelated single-path keys never produces prefix behavior.

SDK prerequisite

Containers with hierarchical partition keys work only with supported SDK versions, which you need both to create the containers and to perform create, read, update, delete and query operations on their data; for the .NET SDK v3 that means version 3.33.0 or later[12], and the same table lists minimum versions for the Java, JavaScript and Python SDKs. Upgrading only the provisioning tool is not enough: every application that reads or writes the container needs a supporting SDK.

Point reads need the full key

To point-read one item, pass its id and the full value of the partition key, including all three components of the path[12]. In .NET the value is built with PartitionKeyBuilder; in Python it is the ordered list of component values.

Listing: point reads on the TenantId, UserId, SessionId container

// ... (container from the creation listing above)
string id = "f7da01b0-090b-41d2-8416-dacae09fbb4a";
PartitionKey partitionKey = new PartitionKeyBuilder()
    .Add("Microsoft")                             // TenantId
    .Add("00aa00aa-bb11-cc22-dd33-44ee44ee44ee")  // UserId
    .Add("0000-11-0000-1111")                     // SessionId
    .Build();
ItemResponse<UserSession> readResponse = await container.ReadItemAsync<UserSession>(id, partitionKey);
# ... (container from the creation listing above)
item_id = "f7da01b0-090b-41d2-8416-dacae09fbb4a"
pk = ["Microsoft", "00aa00aa-bb11-cc22-dd33-44ee44ee44ee", "0000-11-0000-1111"]
container.read_item(item=item_id, partition_key=pk)

A TenantId alone is only a prefix: it is enough to target a query (next section), never enough to address one item.

The takeaway: an HPK is an ordered MultiHash definition fixed at container creation; a prefix grows past one logical partition while each full key stays capped, and point reads always need every level.

Hierarchical partition keys: level order and routing

Once an HPK is chosen, the remaining decisions are the order of its levels, how many distinct values the first level has, and whether the item id becomes the last level.

How queries are routed

When a query specifies all partition-key values in its WHERE filter, or a prefix of the key hierarchy, the SDK routes it to the corresponding physical partitions; queries that provide only the "middle" of the hierarchy are cross-partition queries[12]. For TenantId, UserId, SessionId:

Filter in the WHERE clause Routing
TenantId, UserId and SessionId the single logical and physical partition holding that key
TenantId and UserId a targeted subset of partitions (a targeted cross-partition query)
TenantId only a targeted subset of partitions
UserId only, or SessionId only all physical partitions (a fan-out query)

The "cross-partition" queries for middle-only filters are therefore the fan-out case: a filter on UserId or SessionId alone is routed to all physical partitions, resulting in a fan-out cross-partition query[12].Include the leading partition-key values in the WHERE clause: supplying them only through PartitionKeyBuilder doesn't by itself guarantee efficient routing, and queries that omit them from the WHERE clause might incur significantly higher RU costs[12]. The figure below reduces the table to the two questions that decide the routing.

Order the levels by the leading filter

Because a leading prefix enables targeted routing, prefer a first-level value that common queries frequently know. A multitenant workload that frequently filters on specific user sessions benefits from TenantId, UserId and SessionId, in that order[12]. If queries don't align with the hierarchy, for example filtering only by OrderId when CustomerId is the first level, query performance might suffer[10].

First-level cardinality limits early ingestion

Hierarchical partitions keep all documents with the same first-level key on the same physical partition to avoid full fan-out queries, so a first level with low cardinality limits all write operations at ingestion time to one physical partition until it reaches 50 GB and splits[12]. With only five tenants, each tenant's operations are scoped to one physical partition; the maximum ingestion throughput is the number of physical partitions times 10,000 RU/s, and splits can take 4 to 6 hours to complete[12]. Millions of distinct UserIds under a few tenants do not change this before storage-driven splits happen. For write-heavy workloads, Microsoft recommends a first level with at least thousands of unique values and more unique values than physical partitions; if the first level lacks cardinality and is hitting the 20 GB limit, it suggests a synthetic partition key instead[12]: a key value your code builds and stores in one property (see Synthetic partition keys below).

The item id as the last level

Adding the item id as the last level guarantees that the levels above it can scale beyond the 20 GB logical-partition limit[12], because no full key accumulates more than one item. It costs transaction scope: stored procedures and atomic batch transactions work only at the full logical partition-key level, so with /id as the last level you cannot run them by specifying only /TenantId, or /TenantId and /UserId; if you need them, don't set /id as the last level[8].

The takeaway: put a frequently known common filter first, give the first level enough values to spread writes, and add id last only when no atomic multi-item work is needed below the prefix.

Filter includesTenantId?Fan-out query:all partitionsNoYesAlso UserId andSessionId?One logicalpartitionYesNoTargeted subsetof partitions
How the WHERE filter routes a query on a TenantId, UserId, SessionId hierarchical partition key.

Synthetic partition keys

When no existing property both spreads load and matches the queries, the application can build one. If no property with many distinct values exists in the data, you can construct a synthetic partition key[16], a property whose value your own code computes. Microsoft documents three techniques[16], compared here before each is detailed (400 suffix values per date is the documentation example's bucket count, not a required value):

Technique Example value Effect on writes Reading one item
Concatenate properties abc-123-2018 from deviceId and date one bucket per device and date derivable when both values are known
Random suffix 2018-08-09.1 to 2018-08-09.400 each day's writes spread over 400 values difficult: the suffix is unknown
Precalculated suffix the date plus a suffix computed from the VIN spread as evenly as a random suffix derivable from the date and the VIN

Concatenating properties

Concatenating deviceId "abc-123" and date 2018 produces a synthetic partitionKey value of "abc-123-2018"; instead of adding it manually, client-side logic concatenates the values and inserts the synthetic key into each item[16]. The container's partition-key path points at that property (here /partitionKey). The service never builds the value from other fields, so an item written without it lacks the intended address. A request that knows both source values recomputes the key and routes directly.

Random suffix

Appending a random number between 1 and 400 to a date produces values such as 2018-08-09.1 through 2018-08-09.400, spreading each day's writes evenly across partitions for better parallelism and higher throughput[16]. The cost falls on reads: you don't know which suffix was used when an item was written, so reading a specific item is difficult[16]. It fits write-heavy data that is not looked up item by item.

Precalculated suffix

Instead of a random number, calculate the suffix from a value you query by, such as a hash of the vehicle identification number (VIN) producing a number between 1 and 400, and append it to the date; writes spread evenly, and the application can calculate the partition-key value for a given VIN to read the item[16].

Listing: computing a precalculated suffix deterministically in Python

import hashlib

def vehicle_partition_key(date: str, vin: str, buckets: int = 400) -> str:
    digest = hashlib.sha256(vin.encode("utf-8")).hexdigest()
    suffix = int(digest, 16) % buckets + 1  # a number from 1 to buckets
    return f"{date}.{suffix}"               # "<date>.<suffix>", like "2018-08-09.1"

The writer stores the returned value in the partition-key property; any later reader with the same date, VIN and bucket count calls the same function and gets the same key, which a fresh random number on the read path would almost never reproduce.

A synthetic key is not a hierarchy

A synthetic key that combines TenantId and UserId adds complexity to the application, and its queries for one tenant are still cross-partition unless all users are known and specified in advance[12]. The combined string is one ordinary partition-key value, and placement comes from a hash of that value[10], so a filter on only the tenant part of the string (a STARTSWITH condition, for example) cannot narrow which partitions to search. That narrowing is exactly what an HPK prefix provides. Choose an HPK when queries by the leading component are central and the first level has enough values; choose a synthetic key when write distribution comes first or the leading level has too few values.

The takeaway: a synthetic key is a value your code builds and stores; a calculated suffix keeps writes spread and reads addressable, a random suffix cannot be derived from the base value alone, and neither offers prefix routing.

Multitenant partitioning strategies

A software-as-a-service (SaaS) application might host thousands of small tenants and a handful of very large ones; the multitenant design question is where each tenant's data lives and what it shares with other tenants. Multitenant designs must meet two requirements that often conflict: security and performance isolation between tenants, and a low, sustainable cost per tenant[8].

The two recommended isolation models

Microsoft recommends two models for most solutions: a partition key per tenant, typical of business-to-consumer (B2C) SaaS, and a database account per tenant, typical of business-to-business (B2B) SaaS[8]. Isolation by container or by database is possible but not recommended, largely because of account limits on the number of databases and containers and on metadata operations[8].

Workload need Partition-key-per-tenant Database-account-per-tenant
Cost efficiency one container's RU/s shared by all tenants per-account resources, with RU/s shareable through a fleet pool
Noisy-neighbor prevention no yes
Per-tenant account features (geo-replication, point-in-time restore, customer-managed keys) not possible yes
Tenant data deletion application-managed deletion of the tenant's items delete the tenant's account

These rows summarize Microsoft's comparison of the two models[8]. A noisy neighbor is one tenant whose heavy load slows the others: shared throughput across tenants in the same container can cause contention during peak usage, which can create noisy neighbor problems[8]. A fleet pool is an optional pool of throughput (RU/s) that all database accounts in a fleetspace can share[8] (see Manage and monitor fleets across accounts and subscriptions).

Partition-key-per-tenant

In this model one container stores all tenants' data under a partition key such as /TenantId, and the tenants share the container's throughput[8]. Throughput provisioned on a container is reserved for that container, but the logical partitions and tenants within it share it[8]: a distinct TenantId value is a data-placement choice, not a capacity reservation, so the model fits workloads that don't need guaranteed RU/s for a single tenant[8]. A tenant identifier is an effective key when each tenant's data and request load fit within one logical partition and most operations are scoped to one tenant[8]. For tenants that grow larger, Microsoft documents two directions:

Isolating the exceptional tenants

Account-level configuration, including regions, consistency, networking and access control, applies to everything in the account; a tenant that needs independent account-level configuration or a stronger security and performance boundary needs a separate account[8]. When a few large tenants consistently need higher request volumes than the others, isolate them in their own database accounts and keep the remaining tenants in a shared container[8]. Adding HPK levels changes placement inside one container; it never gives a tenant its own consistency level or region list.

The takeaway: pool ordinary tenants by partition key (with an HPK when tenants grow large), and move only the tenants that need guaranteed capacity or their own account settings into dedicated accounts.

Partitioning anti-patterns in a solution review

A design review is a good place to catch a partitioning mistake, because a partition key can't be changed in place later[10]. The designs below illustrate partitioning mistakes; the rows summarize design guidance, with references to earlier sections where relevant.

Design seen in review Why it fails Better choice
The current date as the only key of a write-heavy stream all of one day's concurrent writes target one logical partition, capped at 10,000 RU/s the date plus a suffix (Synthetic partition keys)
A low-cardinality key such as status, type or country only as many logical partitions as distinct values, uneven RU and storage, hot partitions under load a higher-cardinality or synthetic key
A random GUID that no query filters on writes spread, but most reads fan out (Choosing a partition key) a key aligned with the equality filter, or a GSI
/id for a mixed query workload or for multi-item transactions non-id filters are cross-partition and every item is its own transaction scope (Choosing a partition key) a key shared by the items read and written together
A tenant key with one tenant approaching 20 GB that tenant's logical partition stops accepting data at 20 GB (How partitions work) an HPK such as TenantId, then id
An HPK with few first-level values for time-bound ingestion writes confined to few physical partitions until splits (Hierarchical partition keys: level order and routing) a synthetic key, or a higher-cardinality first level
A large exact number as the key value precision problems across JSON implementations, and the key cannot be corrected later (JSON representation) store it as a string

The low-cardinality row comes straight from Microsoft's list of anti-patterns: fields like status, type or country create as many logical partitions as distinct values, which often leads to uneven RU and storage distribution and hot partitions under load; use one only when data volume is small and traffic per value stays well below the 20 GB and 10,000 RU/s logical-partition limits[10].

Fixes that do not work

Two remedies are often proposed for a hot key, and both fail for the structural reason from How partitions work. Adding container RU/s does not raise one logical partition above 10,000 RU/s, and forcing more physical partitions does not divide a hot logical partition, because a split moves whole logical partitions.

The 20 GB ceiling in production

Azure Monitor alerts can warn when a logical partition's storage approaches 20 GB[17]; Microsoft documents how to configure these alerts in Azure Monitor[17]. If a production workload reaches the 20 GB logical-partition limit, the recommended long-term solution is to rearchitect with hierarchical partition keys; a temporary increase can be requested through a support ticket to buy time, but SLA guarantees are not honored while the limit is increased[4].

The takeaway: test every proposed key against the criteria in Choosing a partition key, plus the transaction-scope and per-value growth checks the table above adds.

Describing a workload in the Cost Estimator

Cost estimation is part of the design, because embedding versus referencing, an extra GSI or a second region each changes what the workload costs. The Azure Cosmos DB Cost Estimator is a public-preview tool, usable without signing in, that estimates the required RU/s and cost of an Azure Cosmos DB for NoSQL workload[18] (RU/s, request units per second, as in How partitions work); some older pages still link to it as the capacity planner[16]. It offers a guided wizard or a Configure panel, and the projected monthly cost updates as the inputs change[18].

Describe operations, not business transactions

The estimator maps NoSQL operations to its operation types: point reads to Reads, creates to Writes, updates to Updates, deletes to Deletes, and queries to Queries[18]. A business transaction such as "place an order" usually performs several of these, for example a query for the cart, a create for the order and an update of stock, so translate each business transaction into its operations before entering rates; entering 100 orders per second as 100 point reads understates the work. Rates can be entered per second or per month[18], and every rate must use the unit that the toggle shows.

One data type per document shape

Each data type has a name, a document size and a document count, plus its own rates of reads, writes, updates, deletes and queries; add data types for workloads with several document shapes, and use Import JSON to work from sample documents[18]. Treating 1 KB status items and 100 KB entity documents as one average shape hides the cost of the large documents, and comparing an embedded design with a referenced one is more accurate when each design's documents and operation mix are entered separately. Query complexity is chosen from presets: simple (about 3 RU), filter (about 10 RU) or complex (about 30 RU)[18].

Peak rate versus total consumption

In the Capacity Mode input, serverless bills per request, so its estimate depends on workload activity; autoscale scales provisioned throughput with traffic for variable workloads; manual provisions a fixed amount for sustained, predictable traffic[18]. Provisioned throughput has to cover the per-second peak of the operation mix, while a serverless estimate follows the total work done over the month, so two workloads with the same peak but very different total activity can favor different modes. The Compare view shows configurations side by side, for example serverless versus provisioned throughput[18].

The order of an estimate

The tool's guided path is a nine-step wizard: Workload, Stage, Data, Traffic, Backup, Read/Write Pattern, Region, Review, and Estimate[18]. The figure below is not that wizard but a suggested six-stage workflow: configure and compare an estimate in the tool, then validate it against measured request charges[19]:

  1. Document types: describe each with its size and count.
  2. Operation rates per type: reads, writes, updates, deletes and queries, per second or per month.
  3. Storage, regions, capacity mode: plus indexing mode, backup and discounts.
  4. Advanced components: vector operations, a dedicated gateway and change feed consumers, when the design uses them.
  5. Compare and export: review alternatives side by side and save the estimate.
  6. Validate with measured charges: run representative operations and compare their request charges with the estimate.

The takeaway: the estimator is only as accurate as the operation mix and document shapes it is given.

1. Document types: size, count2. Operation rates per type3. Storage, regions, capacity mode4. Advanced components5. Compare and export6. Validate with measured charges
A suggested six-stage workflow for an Azure Cosmos DB Cost Estimator estimate (not the tool's nine-step wizard), ending with measured charges.

Cost components beyond request units

Throughput is one line of the bill: the Compare view breaks the cost down across throughput, storage and backup in an itemized table[18], and several design choices from this topic add lines of their own. This section lists the components a complete estimate includes.

An estimate, not a quote

The projected cost is an estimate only and isn't a quote; prices are estimates based on public pricing rates for throughput and storage, shown in US dollars, with rates for every region on the pricing page[18]. The query-complexity presets and built-in RU hints are generic, so measure representative operations before final sizing: every operation through the Azure Cosmos DB API reports the RUs it consumed[8]. Use current regional prices rather than dollar figures copied from an older example.

The takeaway: a complete estimate covers storage with its index, regions and discounts, background consumers, growth, and optional components such as vectors, a dedicated gateway and GSIs, and it is checked against measured charges.

How the four partitioning strategies compare

CriterionRegular partition keySynthetic partition keyHierarchical partition key (HPK)Global secondary index (GSI)
Key shapeOne existing property, such as /customerIdOne property your code fills with combined values, such as deviceId-dateUp to three ordered paths, such as /TenantId, /UserId, /SessionIdA separate read-only container with its own key, kept in sync with the source
Use whenOne property has high cardinality, even load, and appears in common filtersNo single property both spreads load and matches queries, often under heavy writesQueries filter on a leading prefix such as a tenant, and a prefix may outgrow 20 GBSeveral independent query patterns need different partition keys
Queries that route efficientlyEquality on the keyOnly queries that know the full combined valueThe full key or any leading prefix; a filter on a later level alone fans outEquality on the GSI's own key, served from the GSI
Can one tenant or grouping grow past one logical partition (20 GB, 10,000 RU/s)?No: one key value is one capped logical partition; the container grows only across distinct valuesYes, by dividing a business grouping across synthetic values; each full value is cappedYes for a prefix; each full key is still cappedEach GSI key value has the same cap, so it depends on the GSI's key
Main trade-offHot or oversized values when load is skewedApplication must build the value and know it to route readsLow first-level cardinality limits ingestion; transactions need the full keyExtra storage and RUs; eventually consistent with the source

Decision tree

Does one propertyspread load and matchcommon filters?YesNoQueries filter on aleading level withmany values?YesNoRegularpartition keyHierarchicalpartition keySyntheticpartition keyAnother independentquery pattern?YesAdd a GSIbeside the key

Sharp facts the exam loves — give these one last read before exam day.

Cheat sheet

Sharp facts the exam loves — scan these before test day.

Document boundaries should follow business read and write patterns

Design a NoSQL item around the data the application reads, writes, and processes together rather than copying a relational table layout unchanged. A self-contained business entity can be retrieved and updated with fewer requests. Schema flexibility does not remove the need to model access patterns and expected growth.

Trap Copying every relational table into a separate container without reviewing access patterns, which preserves relational reconstruction work the NoSQL query engine does not perform.

2 questions test this
Related entity types can share a container and partition key

When a parent and its separately stored children are commonly accessed together, store both item types in one container with the same parent-based partition-key value. Add a type discriminator so parent-only queries can select the required items. A separate container per entity type is not mandatory in a schema-agnostic database.

Trap Creating one container per related entity type merely to represent different JSON shapes, which loses the intended shared-container access pattern.

3 questions test this
Frequently replaced attributes can be separated from large static data

When a small set of frequently updated attributes and a large static entity are read and written independently, consider storing them as separate items. Full replacements then rewrite the smaller mutable item rather than the combined payload. Patch can reduce update payload, but it does not by itself make independently accessed data one natural read unit.

Trap Embedding a large rarely read static object in every frequently replaced status item, which increases the size of the write unit without serving the access pattern.

2 questions test this
Numbers beyond safe double-precision boundaries should be stored as strings

Azure Cosmos DB stores JSON numbers using IEEE 754 double-precision semantics. Convert identifiers or numeric values that might exceed safe interoperable precision to strings before storage. This is especially important for partition-key fields because their values cannot later be corrected in place.

Trap Storing an arbitrarily large exact numeric identifier as a JSON number, which can lose precision across JSON implementations.

2 questions test this
A NoSQL item's UTF-8 JSON representation must fit within 2 MB

A NoSQL item's maximum size is 2 MB measured as the UTF-8 length of its JSON representation. Model growing entities so the complete document remains within that limit, including embedded arrays and objects. Splitting a large entity into related items changes both retrieval work and transaction placement requirements.

3 questions test this
Date-time text and numeric Unix timestamps require deliberate representation choices

Azure Cosmos DB for NoSQL stores dates using JSON primitives rather than a native DateTime type. UTC ISO 8601 strings are the recommended representation for sortable date-time text, while Unix timestamps can represent elapsed seconds as numbers. Keep query arguments and conversions aligned with the chosen representation instead of treating strings and numeric timestamps as interchangeable.

3 questions test this
Append-only event items preserve mutation history for later projection

When historical mutations must remain available, model each mutation as a new event item rather than overwriting the same current-state item. Change-feed consumers can project those events into current-state materialized views. The retained event items supply the history; ordinary replacement of a current-state item does not create that event archive automatically.

Trap Overwriting one entity item and treating its latest-version change feed as an immutable event log, which can omit intermediate states and does not retain a separate item per mutation.

2 questions test this
Snapshots plus deltas reduce repeated full-version storage at the cost of reconstruction work

Use periodic full snapshots with incremental deltas when historical states are needed but storing every complete version is expensive. Reconstruct a requested historical state from the nearest preceding snapshot and the later deltas through the target time. This trades smaller frequent writes and lower version storage for replay work during historical reads.

Maintaining frequently read aggregates on writes trades write work for cheaper reads

When an application repeatedly reads a parent's child count or a similar aggregate, store the calculated value and maintain it when the contributing items change. This shifts computation to the write path so common reads need not recalculate the aggregate. If the source items and aggregate item share one container and the same complete partition-key value, update them in one transaction to keep the stored summary consistent with the source change.

Trap Embedding every child in the parent just to display a count when the child collection is unbounded, because the parent then grows with the entire collection instead of retaining a bounded summary.

2 questions test this
Embed bounded one-to-few data that is commonly read together

When related data is contained, bounded, and commonly queried together, embed it in the parent item. This makes the combined entity available through one read and is particularly suitable for infrequently changing one-to-few relationships. Relationship cardinality and growth matter more than a blanket rule to normalize everything.

Trap Referencing a few stable contact details that every person read requires, which adds round trips without avoiding meaningful growth or update cost.

2 questions test this
Unbounded child collections should be modeled as separate referenced items

When a parent's related collection can grow without a practical bound, store children separately and reference the parent. An ever-growing embedded array makes the parent increasingly expensive to transmit and eventually threatens the item-size limit. One-to-many relationships therefore require an explicit growth assessment rather than automatic embedding.

Trap Embedding every historical comment inside a popular post, which creates an unbounded mutable parent item.

2 questions test this
Reference frequently changing data that is shared by many entities

When many items share a frequently changing entity, reference one authoritative item rather than embedding a mutable copy in every consumer. Updating that authoritative item avoids rewriting every duplicate. The trade-off is extra application reads to assemble the full result.

Trap Embedding a changing stock quote in every portfolio holding it, which multiplies updates across all copies.

3 questions test this
Place a parent reference on each child to avoid an unbounded parent reference array

Even an array of identifiers can grow without bound. When one publisher can have indefinitely many books, store the publisher identifier on each book rather than a growing list of all book identifiers on the publisher. This keeps the parent stable while allowing more child items to be added.

Trap Replacing embedded child objects with an unlimited array of child ids in the same parent, which preserves the unbounded-parent problem.

3 questions test this
A hybrid model can embed a bounded recent subset while referencing the full collection

When most reads need only a few recent children, keep a bounded recent subset in the parent and store the complete child collection separately. The common read remains self-contained without allowing the embedded array to grow forever. The application must maintain any deliberately duplicated values consistently with its requirements.

2 questions test this
Document references do not create foreign-key constraints

A property containing another item's identifier is a relationship convention, not a database-enforced foreign key. Application code or suitable same-partition server-side logic must validate existence when that integrity rule is required. Creating a referenced item does not automatically establish cascading updates or deletes.

Trap Relying on a parentId property to reject orphan children automatically, which adds no foreign-key enforcement.

2 questions test this
Many-to-many models should match both relationship access directions

For many-to-many relationships, evaluate bounded reference arrays or duplicated read-optimized projections that match the required lookup directions. For example, authors can reference their books while books reference their authors when those collections remain bounded. This makes the related identifiers available directly from the entity being read.

Trap Copying a relational join table into relationship-only documents by default, which adds intermediary lookups even when bounded direct references satisfy both access patterns.

4 questions test this
A hybrid reference can duplicate stable display fields while retaining an authoritative item

When common reads always display a related entity's relatively stable name or thumbnail, duplicate those selected fields alongside its reference. Keep the complete authoritative entity separate for other reads and updates. This reduces common-read round trips at the cost of refreshing the duplicated fields when they change.

Trap Keeping only the related id when every list read needs its stable display fields and extra lookups must be minimized, which forces additional reads to assemble each display result.

3 questions test this
A good partition key balances actual storage and RU demand as well as cardinality

Choose a key with many possible values that distributes both storage and request activity across those values. High cardinality alone is insufficient if most traffic still targets one value. Review the busiest tenants or entities and their data growth rather than considering only the total count of distinct values.

Trap Approving a high-cardinality key solely from its distinct-value count, which can hide a single overwhelmingly busy value.

2 questions test this
A read-heavy partition key should align with frequent equality filters

For a read-heavy container, choose a high-cardinality key that commonly appears as an equality predicate in the workload's WHERE clauses. This lets the service route requests to the relevant partitions. A key that distributes writes well but is absent from normal filters can be a poor fit for the read pattern.

Trap Choosing a random GUID that no normal query knows merely for even writes, which does not align with the dominant read pattern.

2 questions test this
Partition-key definitions and existing item key values cannot be changed in place

A container's partition-key definition is fixed at creation, so changing it requires a new container and data movement. An existing item's partition-key value is also immutable: moving the item requires a create with the new value and deletion of the original. Those operations cannot form one atomic cross-partition transaction.

Trap Replacing an item with a new partition-key value to move it atomically, which cannot change its partition address in place.

2 questions test this
Using id as the partition key favors independent point reads and writes

Using /id as the partition key gives each uniquely identified item its own logical partition and makes its full point-read address easy to derive. This suits independent item reads and writes, but queries on other properties do not share a useful grouping key. Multi-item transactional operations also cannot group distinct ids when each id is its partition value.

Trap Using /id for an order aggregate that requires atomic writes across different line-item ids, which puts those items in different logical partitions.

2 questions test this
A date-only key can concentrate current ingestion into one hot value

A write-heavy stream partitioned only by the current date directs concurrent writes for that date to one logical partition. Similarly, low-cardinality status or country keys provide only a few buckets and can concentrate demand. Choose additional distinguishing values when expected per-value traffic or storage approaches logical-partition limits.

Trap Selecting the current day as the sole key because dates increase over time, which does not distribute writes arriving on the same day.

2 questions test this
Partition-key value length is a byte limit rather than a character count

A partition-key value supports up to 2,048 bytes when large partition keys are enabled, or 101 bytes without that capability. Validate derived keys using their encoded byte length, particularly when concatenating fields. Multibyte text can consume more bytes than its visible character count.

3 questions test this
A full logical partition is limited to 20 GB and 10,000 RU/s

A full logical partition groups items with the same complete partition-key value and has a standard 20-GB storage limit. Its throughput cannot exceed 10,000 RU/s because it resides on one physical partition. Increasing total container capacity does not remove these per-value constraints.

Trap Increasing overall container RU/s to let one unchanged full key consume more than 10,000 RU/s, which cannot bypass its partition boundary.

2 questions test this
Physical partitions provide up to 50 GB and 10,000 RU/s each

Azure Cosmos DB manages physical partitions, each of which can host multiple logical partitions. A physical partition supports up to 50 GB of storage and 10,000 RU/s, so total storage and provisioned throughput both influence how many are required. Logical partitions sharing a physical partition also share that partition's available throughput.

Trap Assuming each logical partition receives the full container allocation, which ignores its co-resident logical partitions and physical capacity.

2 questions test this
A physical partition split never divides one full logical partition

As storage or throughput grows, Azure Cosmos DB can split physical partitions without making the container unavailable. It remaps complete logical partitions to the resulting physical partitions. A single hot full key stays together, so forcing more physical partitions does not distribute that key's traffic.

Trap Splitting a physical partition to divide one hot logical key across both children, which preserves that key on one child.

3 questions test this
Azure Cosmos DB distributes logical keys by their hashes rather than by visible value order

Azure Cosmos DB hashes partition-key values and distributes the hash space across physical partitions. Similar-looking or adjacent values therefore do not imply adjacent storage placement. There is no fixed container-wide limit on the number of distinct logical partition keys, allowing growth through additional well-distributed values.

Trap Predicting physical placement from alphabetically adjacent tenant names, which ignores hash-based distribution.

2 questions test this
Hierarchical prefixes can exceed logical-partition limits while complete keys remain bounded

Hierarchical partition keys support up to three levels and let a prefix such as a tenant span multiple full logical partitions. That prefix can therefore exceed 20 GB and 10,000 RU/s. The complete combination of all configured key components still defines one logical partition and retains its limits.

Trap Assuming HPK removes the storage limit from each complete tenant-user-session combination, which remains one logical partition.

2 questions test this
Hierarchical key order should match the leading filters in common queries

Put the most useful common query prefix first in a hierarchical partition key. For a TenantId, UserId, SessionId hierarchy, a TenantId filter or TenantId plus UserId filter targets the relevant subset of physical partitions. Filtering only UserId or SessionId omits the leading prefix and requires full cross-partition routing.

Trap Putting cityId first when most queries know only customerId, which leaves the dominant queries without a leading key prefix.

2 questions test this
A hierarchical key definition uses ordered paths with MultiHash and version two

Define an HPK container with an ordered paths array, kind MultiHash, and version 2. The array order defines the hierarchy rather than combining values into one concatenated string. In Python, PartitionKey can take a list of paths with kind='MultiHash'; in .NET, ContainerProperties accepts partitionKeyPaths.

Trap Defining several unordered Hash paths and expecting hierarchical prefix behavior, which needs the ordered MultiHash definition.

2 questions test this
A point read on an HPK container requires every key component

To point-read an item from an HPK container, provide its id and all configured key components in hierarchy order. In .NET, build the complete PartitionKey with PartitionKeyBuilder; in Python, provide the ordered component values. A prefix is sufficient for a targeted query, not for uniquely addressing a point read.

Trap Supplying only TenantId to point-read an item in a three-level hierarchy, which is a prefix rather than its full partition address.

2 questions test this
Low first-level cardinality can limit early HPK ingestion parallelism

Hierarchical partitioning tries to colocate a first-level key's data until storage growth causes splits. A small number of first-level values can therefore constrain initial ingestion to a small number of physical partitions even when lower levels have many values. For write-heavy ingestion, choose high-cardinality leading values or assess a synthetic-key alternative rather than assuming lower-level cardinality immediately provides parallelism.

Trap Relying on millions of second-level user ids to guarantee immediate ingestion distribution for one small first-level tenant, which can remain colocated before storage-driven splits.

2 questions test this
An item identifier at the final HPK level can subdivide a growing lower-level group

If TenantId and UserId together may exceed one logical partition's storage budget, add a high-cardinality final component such as the item id. This allows the tenant-user prefix to span more full keys. The extra subdivision changes which items can participate in one transaction, so retain shared full keys wherever atomic multi-item work is required.

Trap Adding a unique item id as the last key component while assuming different item ids remain one transaction group, which separates their complete keys.

3 questions test this
.NET clients require SDK version 3.33.0 or later for HPK operations

Azure Cosmos DB .NET SDK support for hierarchical partition keys requires version 3.33.0 or later. The supporting SDK is required for CRUD and query operations as well as container creation, so verify the application's data clients before directing them to an HPK container.

Trap Upgrading only the container-provisioning application while retaining unsupported data clients, which leaves ordinary CRUD and query access without the required HPK SDK support.

2 questions test this
A tenant-key shared container suits tenants whose workloads can share one resource

Use a partition-key-per-tenant container when each tenant fits within a full logical partition and the service can share throughput among tenants without guaranteed per-tenant reservations. This is cost-efficient for many small tenants and keeps one container's capacity configuration to manage. A tenant key is a data-placement choice, not a reserved capacity allocation for that tenant.

Trap Promising each tenant a fixed RU/s reservation merely because it has a distinct TenantId value, which does not reserve a share of the shared container.

2 questions test this
A few disproportionately demanding tenants can be isolated while smaller tenants remain pooled

When a few tenants consistently require much greater capacity or independent account-level configuration, evaluate separate accounts for those tenants while retaining smaller tenants in a shared container. This hybrid model targets the exceptional workload without multiplying resources for every small tenant. Additional key levels alone do not provide independent account settings or a dedicated tenant resource boundary.

Trap Adding a lower HPK level to provide a large tenant an independent default consistency setting, which remains an account-level choice.

2 questions test this
A synthetic key materializes several values into one partition-key property

When no existing property offers the required grouping and distribution, construct a synthetic partition-key property in application code. Concatenating a device identifier with a date creates a per-device-per-date bucket and lets a request knowing both values derive its address. The service does not concatenate arbitrary document fields merely because the application queries them together.

Trap Configuring a synthetic key path without populating its combined property on new items, which leaves the intended derived address absent.

3 questions test this
A random suffix spreads writes but makes exact read routing harder

Append a random suffix when a low-cardinality base value would otherwise concentrate writes and write parallelism is the priority. The suffix creates more full key values. A reader that knows only the base value cannot reconstruct the original random suffix, so it needs a stored address or additional lookup work.

Trap Choosing a random suffix while requiring a reader to derive the complete key from the base value alone, which discards information needed for direct routing.

2 questions test this
A calculated suffix combines write distribution with reproducible read routing

When the reader knows a stable property such as a vehicle identifier, calculate a suffix from that property and append it to the base key. A deterministic hash-based suffix spreads writes while allowing the application to recompute the same key later. This is preferable to a random suffix when exact lookup routing must be derivable.

Trap Using a fresh random suffix on the read path, which is unlikely to reproduce the address chosen during the write.

3 questions test this
A concatenated synthetic key does not supply hierarchical prefix routing

A synthetic value such as tenantId-userId is one ordinary partition-key value. A query knowing only tenantId cannot use it as a native HPK prefix; it must know complete derived values or perform broader routing. Choose HPK when leading-component queries are a key requirement and its distribution trade-offs fit the workload.

Trap Expecting a string prefix filter on a concatenated key to behave like an HPK tenant prefix, which uses a different partitioning mechanism.

2 questions test this
Cost estimation needs operation rates and document sizes rather than transaction counts alone

Describe each data type's document size, population, and rates of reads, writes, updates, deletes, and queries in the Azure Cosmos DB Cost Estimator. A business transaction may contain several database operations, so size throughput from those operations and their individual charges. The estimator can accept rates per second or per month, which must match the units of the input workload.

Trap Entering business transactions per second as point reads when each transaction also performs writes and queries, which underrepresents the workload.

2 questions test this
Mixed document shapes should be represented separately in a workload estimate

The Cost Estimator supports multiple data types with separate sizes, item counts, and operation rates. Import sample JSON or configure each document type instead of treating tiny status items and large entity documents as one uniform shape. This makes comparisons between embedded and referenced designs reflect their actual read and write mix.

Trap Sizing a mixed workload entirely from its smallest sample document, which ignores expensive larger document operations.

2 questions test this
Peak capacity and total consumed work answer different pricing questions

Provisioned-throughput sizing must accommodate the operation mix at the required per-second peak, whereas serverless estimates depend on consumed RUs over time. A workload's peak and total monthly work can favor different capacity models. Compare both rather than selecting a model from peak requests alone.

Trap Comparing serverless and manual costs using only peak RU/s, which omits the activity duration and total consumed work.

2 questions test this
A complete cost estimate includes storage, regions, and the selected pricing options

Throughput is only one component of workload cost. Include data storage, region count and location, backup choices, and applicable discounts in the estimator's configuration. Compare the resulting itemized breakdown instead of assuming a cheaper operation pattern always produces the lowest total monthly cost.

Trap Comparing database designs only by write RU charge while omitting duplicated storage and region costs, which leaves out material cost components.

2 questions test this
Background consumers and expected growth belong in capacity estimates

Include change-feed consumers and other background database work alongside foreground application operations. The current estimator has a Change Feed Consumers option and growth projections for storage and compute. A design that fits today's foreground peak can still be undersized after background processing or retained data grows.

Trap Sizing all throughput from API traffic while treating change-feed readers as free, which omits their database requests.

2 questions test this
Cost Estimator projections should be checked against measured requests and current prices

The Azure Cosmos DB Cost Estimator provides a projected monthly cost, not a contractual quote. Its query-complexity presets and operation hints are estimates, so validate representative workload charges before final sizing. Use current regional pricing rather than copying dollar figures from an older illustrative example.

Trap Treating a generic query-complexity preset as the guaranteed charge of every production query, which substitutes an estimate for workload measurement.

3 questions test this
An alternate partitioned copy trades extra storage and RU work for another access path

When independent access patterns cannot share one useful partition key, evaluate an additional copy organized by another key. Global secondary indexes are documented as automatically synchronized alternate-key containers with eventual consistency and additional storage and RU costs. Include those costs and the allowed freshness in the data-model decision rather than treating the alternate layout as free.

Trap Adding an alternate-key synchronized container while budgeting only the original container's storage and work, which omits the extra copy.

2 questions test this
Vector workload estimates need embedding storage and vector operation inputs

For a vector-enabled workload, enable the Cost Estimator's Vector Operations inputs in addition to ordinary document operations. Include vector dimensions and index type, vector writes and queries per second, and partitions scanned per query. These inputs account for embedding storage and vector-operation work that a CRUD-only estimate omits.

2 questions test this
An integrated-cache estimate includes dedicated gateway compute

When estimating a design that uses the integrated cache, include the dedicated gateway SKU and instance count. The gateway is a separate compute component even when cache hits reduce database RU consumption. A throughput-and-storage-only comparison does not capture that complete design cost.

2 questions test this
Storage sizing must include the index as well as document data

Azure Cosmos DB's total consumed storage combines data size and index size. When all properties are indexed, the index can occupy more space than the document data itself. Include both footprints when estimating storage capacity and cost rather than sizing only from the stored JSON payloads.

References

  1. https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/modeling-data
  2. https://learn.microsoft.com/en-us/credentials/certifications/resources/study-guides/dp-420
  3. https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update
  4. https://learn.microsoft.com/en-us/azure/cosmos-db/concepts-limits
  5. https://learn.microsoft.com/en-us/azure/cosmos-db/troubleshoot-bad-request
  6. https://learn.microsoft.com/en-us/azure/cosmos-db/working-with-dates
  7. https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/model-partition-example
  8. https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/service/cosmos-db
  9. https://learn.microsoft.com/en-us/azure/cosmos-db/change-feed-modes
  10. https://learn.microsoft.com/en-us/azure/cosmos-db/partitioning
  11. https://learn.microsoft.com/en-us/azure/cosmos-db/request-units
  12. https://learn.microsoft.com/en-us/azure/cosmos-db/hierarchical-partition-keys
  13. https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-query-container
  14. https://learn.microsoft.com/en-us/azure/cosmos-db/global-secondary-indexes
  15. https://learn.microsoft.com/en-us/azure/cosmos-db/hierarchical-partition-keys-faq
  16. https://learn.microsoft.com/en-us/azure/cosmos-db/synthetic-partition-keys
  17. https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-alert-on-logical-partition-key-storage-size
  18. https://learn.microsoft.com/en-us/azure/cosmos-db/estimate-ru-with-capacity-planner
  19. https://learn.microsoft.com/en-us/azure/cosmos-db/optimize-cost-reads-writes
  20. https://learn.microsoft.com/en-us/azure/cosmos-db/index-policy