The distributed nature

To make Cosmos DB scalable and fast worldwide, data is distributed and duplicated in different nodes. Nodes can be in the same data center, region, and continent or on the other side of the world; it depends on the settings we use.

For this reason, we need to accept that to keep performance high, we need to lose consistency. For example, if we write a document in the West Europe region, it will take some time to be updated in the West US region.

In simple terms, we might not get the latest version when we read. However, based on our needs, we can select different levels of consistency. The following five are in order from the fastest to the slowest.

  • Eventual

  • Consistent Prefix

  • Session

  • Bounded Staleness

  • Strong

Available levels

Let’s see in detail all the available consistency levels. We start with the weakest consistency that has the best performance to the complete opposite.

Eventual consistency

It’s the weakest form of consistency and the easiest on performance. We don’t have any guarantees that documents are up to date; based on the node we hit, we might even get an older version compared to the last one we got. It’s ideal when we don’t need consistent data, just something to show, even if not precise, like generic statistics and counters.

Imagine a client making three document changes (v1v1,v2v2, and v3v3) in Region 1. If we read three times from Region 2, we might get v1v1, v2v2, and then v1v1 again.

Consistent Prefix consistency

This level applies only to transactions. On a single document write, the consistency is Eventual. However, when multiple documents are updated as part of a transaction, they are returned with the same consistency.

Note: On a multiple write region account, if we write from clients to multiple regions, the level will be Eventual.

Session consistency

The Session level is the default for Cosmos DB accounts. It guarantees we get the latest document version if the update happens in the same session. A session is generated automatically by a client. So, when using the same client to read and write, for example, in an API or CLI, we know we have the latest version.

Using the same session with multiple clients is possible thanks to session tokens. In this case, we need to store the token in a shared place, and clients need to add it to their requests.

Note: If other clients write outside the session, the Consistent Prefix rules apply.

Bounded Staleness consistency

It takes all the guarantees of the Consistent Prefix consistency and applies bounds on top of them.

We can limit how old a document can be when reading compared to the latest version. The limit can be on the number of versions or a time interval. The update is forced when one of the two metrics hits the limit.

Get hands-on with 1400+ tech skills courses.