cosmos-db
  1. cosmos-db-session

CosmosDB Consistency Models

Overview

CosmosDB is a globally distributed database service, which allows developers to store and access data using a variety of APIs. CosmosDB supports multiple consistency models that enable developers to balance consistency, availability, and partition tolerance. A consistency model defines how quickly replica data is propagated within a distributed system, and how quickly it reflects updates made by clients. In this tutorial, we will discuss different consistency models provided by CosmosDB.

Syntax

CosmosDB provides four types of consistency models, which can be specified during the creation of the database account:

  1. Strong Consistency
  2. Bounded Staleness Consistency
  3. Session Consistency (default)
  4. Eventual Consistency

The syntax to specify a consistency level is as follows:

{
    "consistency": "<consistency level>"
}

Example

To create a CosmosDB account with Session Consistency, use the following syntax:

{
    "id": "<cosmosdb-account-identifier>",
    "kind": "GlobalDocumentDB",
    "consistencyPolicy": {
        "defaultConsistencyLevel": "Session",
        "maxIntervalInSeconds": 10,
        "maxStalenessPrefix": 200
    }
}

Explanation

The above code creates a CosmosDB account with Session consistency as its default consistency level. maxIntervalInSeconds and maxStalenessPrefix are optional parameters used for Bounded Staleness Consistency, and specifies the maximum time and prefix length for stale data.

Use

  • Strong Consistency: ensures that all clients see the most up-to-date version of data at all times, but this consistency level limits the service availability across regions.
  • Bounded Staleness Consistency: provides a balance between consistency and availability, and it allows developers to trade-off how up-to-date the data can be across different regions.
  • Session Consistency (default): maintains consistency for the duration of the session, ensuring that all reads within a session see the same data.
  • Eventual Consistency: provides the highest level of availability and allows data to propagate to all regions over time, but data may be stale and not immediately up-to-date.

Important Points

  • Strong consistency may result in partitioning failures due to increased latency in multi-region configurations.
  • Session consistency is an optimal choice for scenarios that require monotonic reads, consistency of prefixes, and read-your-writes.
  • Eventual consistency is the least consistent model and is typically used in non-critical applications.

Summary

In this tutorial, we discussed the different consistency models provided by CosmosDB, their syntax, use cases, and important points. Developers can choose a consistency level based on their application requirements, balancing consistency, availability, and partition tolerance.

Published on: