Overview of Constraints

Learn how to create unique key policies on a Cosmos DB container to improve consistency.

Constraints

We read that JSON documents are flexible multiple times and that applications must maintain consistency. However, there is something we can do at the container level—we can add unique key constraints. We can tell Cosmos DB that a value for a specific path, or a combination of multiple ones, is unique.

For example:

  • On a users container, we can set /email as unique.

  • On a games container, we can set the combination of /title and /year as unique.

Note: These limitations are applied only within a logical partition. This means we can’t expect a value to be unique within the whole container.

Additional details

  • We must set unique keys when we create the container. If we need to add them later, we must create a new container and migrate the data.

  • Containers have a limit of 10 constraints, with a maximum of 16 paths each.

  • Since Cosmos DB has to run additional checks, there is a slight increase in RURequest unit is a performance currency abstracting the system resources such as CPU, IOPS, and memory that are required to perform the database operations. usage for write operations.

Implementation

There are multiple ways to create containers. Let’s see the main options to create constraints.

The Azure portal

Get hands-on with 1200+ tech skills courses.