Skip to content
AI-200 Learn

Choose consistency levels for optimal performance

The five Cosmos DB consistency levels for AI-200: guarantees, 2x read RU for Strong and Bounded staleness, session tokens and per-client overrides.

What this covers

Consistency levels decide how fresh a read is relative to recent writes, and they change read RU cost, latency and availability. This page covers the five levels and their guarantees, how they affect RUs, Session consistency and session tokens, overriding the account default from code, multi-region rules, and using the PBS metric to check whether a weaker level is good enough.

Exam weight: Develop AI solutions by using Azure data management services (30–35%)

Skills measured

  • "Optimize query performance and Request Units (RUs) consumption by using indexing policies and consistency levels"

Key concepts

The five levels, strongest to weakest

LevelGuaranteeTypical use
StrongLinearizable: every read returns the latest committed write, in any regionFinancial or regulatory data
Bounded stalenessReads lag writes by at most K versions or T time, whichever comes firstSingle-write-region global apps needing near-strong reads
Session (default for new accounts)Read-your-writes and write-follows-reads within a sessionMost user-facing and AI apps
Consistent prefixNever out of order; transactional batches appear togetherEvent or audit sequences
EventualNo ordering; replicas converge over timeCounters, analytics, background jobs

Read consistency applies within a single logical partition.

RU impact

LevelRead quorumRead RUWrite quorum
StrongTwo replicas (local minority)2×Global majority
Bounded stalenessTwo replicas2×Local majority
SessionOne replica (with token)1×Local majority
Consistent prefixOne replica1×Local majority
EventualOne replica1×Local majority

Write RU charges are the same at every level; Strong only adds write latency in multi-region accounts because every region must commit. Moving a read-heavy app from Strong to Session roughly halves read RUs.

Session tokens

After each write the server returns x-ms-session-token. One CosmosClient tracks tokens automatically. When a different service or client instance must see that write (an upload API followed by a separate search API), pass the token along with the request. Tokens are partition-bound and shouldn't be modified. A client that hasn't written to a partition, or was recreated, reads that partition with eventual-like behaviour until it has a token.

Overriding the default

The account default applies to every database and container. Clients and requests can override it for reads only, and only to a weaker level: an account set to Strong can have Session or Eventual clients, but a client can't ask for Strong on a Session account. The training module's pattern of separate clients per level (for example an Eventual client for analytics) works within that rule. After changing the account default, restart apps so new clients pick it up.

Vector search and consistency

Similarity search usually tolerates eventual reads; a few-second-old index rarely changes the answer. Use Session when a user expects their just-uploaded document to appear in their own search immediately.

Multi-region rules

  • Strong isn't available with multiple write regions, and accounts spanning more than 5,000 miles (8,000 km) need support to enable it.
  • Bounded staleness suits single-write-region accounts; it's an anti-pattern with multi-region writes. Minimum bounds: K = 10 and T = 5 s for one region; K = 100,000 and T = 300 s for multiple regions.
  • Session and weaker commit locally and replicate asynchronously.

PBS metric

Probabilistically Bounded Staleness, in Metrics under the consistency category, shows how often weaker reads actually return the latest data. If eventual reads are current more than 99% of the time, more workloads may safely drop to a weaker level.

How it works

Diagram source: sequenceDiagram participant Up as Upload API participant C as Cosmos DB participant S as Search API Up->>C: create_item(doc) C-->>Up: 201 + x-ms-session-token Up-->>S: session token in request S->>C: query_items(session_token=token) C-->>S: Includes the new doc (read-your-writes)

Hands-on

Azure portal

  1. Account > Default consistency (under Settings).
  2. Select the level; for Bounded staleness set maximum lag in operations and seconds.
  3. Save, then restart client applications.

Azure CLI

Azure CLI / Bash
az cosmosdb update \
  --name <account-name> --resource-group <resource-group> \
  --default-consistency-level Session

az cosmosdb update \
  --name <account-name> --resource-group <resource-group> \
  --default-consistency-level BoundedStaleness \
  --max-staleness-prefix 100000 --max-interval 300

Python

Python
from azure.cosmos import CosmosClient, ConsistencyLevel
from azure.identity import DefaultAzureCredential

endpoint, cred = "https://<account-name>.documents.azure.com:443/", DefaultAzureCredential()

client = CosmosClient(endpoint, credential=cred, consistency_level=ConsistencyLevel.Session)
container = client.get_database_client("documents-db").get_container_client("documents")

session = {}
container.create_item(
    body={"id": "doc-123", "title": "Project Proposal", "category": "proposals"},
    response_hook=lambda headers, _: session.update(token=headers.get("x-ms-session-token")),
)

# Another service, another client: pass the token to read its own write
results = container.query_items(
    query="SELECT * FROM c WHERE c.category = @category",
    parameters=[{"name": "@category", "value": "proposals"}],
    partition_key="proposals",
    session_token=session["token"],
)

# Cheaper reads for analytics (must be weaker than the account default)
analytics = CosmosClient(endpoint, credential=cred, consistency_level=ConsistencyLevel.Eventual)

Exam traps

RequirementLevel
User must see their own upload immediatelySession
Global latest value, single write region, cost no objectStrong
Readers in other regions may lag at most 5 minutesBounded staleness
Ordered event history, freshness optionalConsistent prefix
Cheapest, fastest reads for dashboardsEventual

Quick review

  • Five levels: Strong, Bounded staleness, Session, Consistent prefix, Eventual.
  • Session is the default and the usual answer.
  • Strong and Bounded staleness reads use two replicas and double read RUs.
  • Pass x-ms-session-token between services for read-your-writes.
  • Client and request overrides can only weaken consistency.
  • Strong is incompatible with multi-region writes.
  • Bounded staleness minimums: 10 ops/5 s single region, 100,000 ops/300 s multi-region.
  • PBS shows how often weaker reads are actually current.

Practice

Practice: Cosmos DB RU and indexing questions

Official references