Choosing Session Consistency in Azure Cosmos DB for Low-Latency Real-Time Apps
Learn how Azure Cosmos DB's Session consistency level gives read-your-writes with latency close to Eventual, and see a .NET example that shows the trade-off and verification steps.
31 Jul 2025, 23:04 UTC

Problem: latency versus consistency in a globally distributed app
Imagine a multi-region gaming leaderboard that updates scores every few seconds. Players expect to see their own score immediately after they submit it, but they can tolerate a short delay when viewing others' scores. Using Strong consistency guarantees immediate visibility everywhere, yet each read incurs higher latency and lower throughput because Cosmos DB must wait for a quorum across all regions. The team needs a middle ground that gives read-your-writes for the client that performed the write while keeping read latency low.
Thesis: Session consistency provides read-your-writes with latency close to Eventual consistency
When the Cosmos DB account is configured with the Session consistency level, reads that use the session token returned by a write are guaranteed to see that write (read-your-writes) and any previous writes in the same session. Reads that do not present a token behave like Eventual reads, offering latency similar to the weakest level. This makes Session a practical choice for workloads where each client's own updates must be immediately visible, but cross-client staleness is acceptable.
When Session consistency is a good fit
- Applications where a single user or device performs a sequence of writes and expects to see its own updates (e.g., form wizards, shopping carts, game scores).
- Workloads that are read-heavy and can tolerate occasional stale reads from other users.
- Globally distributed accounts where lowering read latency improves user experience and reduces request units (RU) consumption.
Worked example: .NET SDK code that demonstrates read-your-writes
The following snippet shows how to capture the session token after a write and reuse it for an immediate read. Replace placeholders with your own values.
using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;
class Program
{
private static readonly string Endpoint = "<YOUR_COSMOSDB_ENDPOINT>";
private static readonly string Key = "<YOUR_PRIMARY_KEY>";
private static readonly string DatabaseId = "DemoDb";
private static readonly string ContainerId = "Scores";
static async Task Main()
{
var client = new CosmosClient(Endpoint, Key);
var database = client.GetDatabase(DatabaseId);
var container = database.GetContainer(ContainerId);
// 1. Write a document
var newScore = new { id = Guid.NewGuid().ToString(), player = "Alice", points = 42 };
ItemResponse<dynamic> writeResp = await container.CreateItemAsync(newScore, new PartitionKey(newScore.player));
// The session token is returned in the response headers
string sessionToken = writeResp.Headers.SessionToken;
Console.WriteLine($"Write completed, session token: {sessionToken}");
// 2. Immediate read using the session token (read-your-writes)
var readOptions = new ItemRequestOptions { SessionToken = sessionToken };
ItemResponse<dynamic> readResp = await container.ReadItemAsync<dynamic>(newScore.id, new PartitionKey(newScore.player), readOptions);
Console.WriteLine($"Read back points: {readResp.Resource.points}");
// Expected output: 42
// 3. Read without a token - may return stale data in another region
var staleRead = await container.ReadItemAsync<dynamic>(newScore.id, new PartitionKey(newScore.player));
Console.WriteLine($"Read without token points: {staleRead.Resource.points} (may be older)");
}
}
To run this code you need the Microsoft.Azure.Cosmos NuGet package (version 3.x or later) and appropriate permissions to read and write the target container. The operation does not modify the account's consistency level; it only uses the token returned by the write.
How to configure the account for Session consistency
You can set the default consistency level when creating the Cosmos DB account via Azure CLI or the portal.
az cosmosdb create \
--name <YOUR_ACCOUNT_NAME> \
--resource-group <YOUR_RG> \
--default-consistency-level Session \
--locations regionName=EastUS failoverPriority=0 isZoneRedundant=False \
--locations regionName=WestEurope failoverPriority=1 isZoneRedundant=False
Required permissions: Microsoft.DocumentDB/databaseAccounts/write on the resource group. Changing the consistency level after account creation is not supported; you would need to create a new account and migrate data. Note also that while you can request a stronger consistency level per request via the x-ms-consistency-level header, you cannot weaken it below the account default for individual operations.
Verifying the behavior (what to check, not what we observed)
- Read-your-writes: After a write, capture the session token and issue a read with that token. Verify the returned document reflects the write.
- Latency comparison: Enable Azure Monitor metrics for the account. Compare the average
requestDurationandrequestChargefor reads under Session consistency with a test account configured as Strong consistency (same region set, similar load). Microsoft's published performance guidance suggests Session reads can be roughly 30-50% faster. - Cross-region limitation: Perform a write in region A, capture its token, then issue a read in region B without forwarding the token. The read may return an older version, demonstrating that Session does not guarantee cross-region read-your-writes.
These checks can be performed with the Azure portal's Metrics explorer or via the Azure Monitor REST API. No special tooling beyond the SDK and standard monitoring is required.
Trade-off and limitation
The primary limitation of Session consistency is the lack of automatic cross-region read-your-writes. If your application requires that a write made in any region be immediately visible to reads in all other regions (e.g., financial transfers, inventory reservation), Session consistency will violate that rule unless you explicitly propagate the session token between regions, which adds complexity. In such cases, Bounded Staleness or Strong consistency may be more appropriate, albeit with higher latency.
Actionable closing
If your workload's main consistency need is "see my own writes," start by provisioning a Cosmos DB account with Session as the default consistency level. Use the session token returned by write operations for immediate reads, and monitor request duration and charge to confirm the latency gain. Keep an eye on any cross-region read patterns; if you notice stale reads that affect business logic, consider forwarding session tokens or moving to a stronger consistency level. This approach lets you achieve low-latency, responsive user experiences without paying the full cost of Strong consistency.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.