Consistency models from linearisable to eventual, the session guarantees (read-your-writes, monotonic reads, consistent prefix), how Cosmos DB's Strong, Bounded Staleness, Session, Consistent Prefix and Eventual levels map to them, and how to choose per feature.
A consistency model is the contract that says which values a read may return when data is replicated. At one end, strong (linearisable) consistency makes every read see the latest committed write, as if there were one copy. At the other, eventual consistency only promises replicas converge once writes stop. In between are the session guarantees: read-your-writes (you see your own updates), monotonic reads (you never go back in time) and consistent prefix (you never see writes out of order). Cosmos DB exposes this as five levels: Strong, Bounded Staleness, Session (the default), Consistent Prefix and Eventual; stronger levels cost more latency and request units, and Strong can't be used with multi-region writes. I choose per feature: what does a stale or out-of-order read cost here? The trade-off is freshness against latency, cost and availability.
"When data lives on several replicas, a write lands on one first and reaches the others later. A consistency model is the promise about what a reader can see in that gap. Strong or linearisable consistency hides the gap completely: once a write is acknowledged, every reader everywhere sees it. Eventual consistency only promises the replicas will agree eventually if writes stop; a reader can see old values, or new then old. Most real applications live in between, on the session guarantees: read-your-writes, so a user who just saved a profile sees the change; monotonic reads, so a refresh never shows older data than the last one; and consistent prefix, so you never see a reply before the message it replies to.
Cosmos DB is a nice example because it makes the choice explicit. Strong gives linearisable reads but needs a quorum, costs about twice the RUs for reads and isn't allowed with multiple write regions. Bounded Staleness lets reads lag by at most K versions or T seconds. Session, the default, gives read-your-writes and monotonic reads within a session, tracked by a session token. Consistent Prefix keeps order but not freshness, and Eventual is cheapest and fastest. In .NET the catch with Session is that the token lives in the
CosmosClientinstance. If a user writes through one API instance and reads through another, the second instance doesn't have the token, so read-your-writes quietly breaks unless you pass the token along.The mistake I see is picking one level for the whole account and never thinking about it again. I decide per feature, based on what a stale read would cost."
| Model | Promise | Example where it matters |
|---|---|---|
| Strong (linearisable) | Every read sees the latest acknowledged write | Seat booking, stock reservation |
| Bounded staleness | At most K versions or T seconds behind | Leaderboards, dashboards with an SLA |
| Session (read-your-writes + monotonic) | You see your own writes; no going back in time | User editing their own profile or basket |
| Consistent prefix | Order preserved, freshness not | Chat threads, activity feeds |
| Eventual | Converges if writes stop | Like counts, product views, analytics |
| Level | Read cost | Multi-region writes | Typical use |
|---|---|---|---|
| Strong | ~2Γ RU (quorum read) | Not supported | Invariants that must never break |
| Bounded Staleness | ~2Γ RU (quorum read) | Supported | Ordered, bounded-lag reads across regions |
| Session (default) | 1Γ RU | Supported | Most user-facing apps |
| Consistent Prefix | 1Γ RU | Supported | Feeds, ordered event views |
| Eventual | 1Γ RU | Supported | Counters, non-critical reads |
A customer-profile API on three instances behind a load balancer used Cosmos DB with Session consistency. About 3% of users complained that their saved address "reverted" after saving. The write and the follow-up read hit different API instances, so the second CosmosClient didn't have the session token and read from a lagging replica. Returning the session token to the client in a response header and sending it back on the next read took complaints to zero without paying for Strong.
Checks whether the candidate can name the consistency models precisely, map them to a real product, and choose based on business impact.
Green flags
Red flags
Writer Replica A (Sydney) Replica B (Melbourne)
| -- x=2 --> | ack |
| | ---- replicate --------> | (10-15 ms later)
Reader 2 ------------------------- read x ->| returns x=1 (stale)
Any replication that acknowledges before all replicas have the write opens a window where readers disagree. Consistency models describe what is allowed inside that window.
The system behaves as if every operation happened instantly at one point between its start and end, on a single copy. To provide it, a read must confirm it sees the latest write, typically by reading from a majority quorum or from the single leader. Cost: latency (wait for the quorum) and availability (a minority partition can't serve).
They're cheap because they only coordinate for one client, usually by carrying a token (a version or log position) that replicas must have caught up to before answering.
Consistent prefix: if writes were A, B, C, a reader may see A or A,B but never A,C. Eventual: no promise except convergence. Eventual consistency also forces you to think about conflicts when two replicas accept writes: last-writer-wins (by timestamp, which suffers from clock skew), custom merge, or CRDTs.
Each physical partition is a replica set of four replicas in a region using a quorum protocol. Strong and Bounded Staleness reads go to two replicas (a local minority quorum), hence about twice the RU. Session reads use the session token (x-ms-session-token), which encodes the partition's logical sequence number; the replica must have reached it before answering. The .NET SDK caches the token per CosmosClient and per container; you can read it from ItemResponse.Headers.Session and pass it back via ItemRequestOptions.SessionToken.
Ask three questions:
No to all three β Eventual. Only question 2 β Session. Question 3 β Consistent Prefix or stronger. Question 1 with money or stock β Strong, or redesign around a single writer.
CosmosClient instances; log the session token from the write response.ItemRequestOptions.SessionToken and confirm the read reflects the write.RequestCharge for the same read under Session and under Eventual.Keeping read-your-writes across API instances with Cosmos DB Session consistency: return the session token after a write and send it back on the next read.
using Microsoft.Azure.Cosmos;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => new CosmosClient(
builder.Configuration["Cosmos:Endpoint"],
new Azure.Identity.DefaultAzureCredential(),
new CosmosClientOptions { ConsistencyLevel = ConsistencyLevel.Session }));
builder.Services.AddSingleton<ProfileStore>();
var app = builder.Build();
app.MapPut("/profiles/{id}", async (string id, Profile profile, ProfileStore store, HttpResponse res, CancellationToken ct) =>
{
var token = await store.SaveAsync(profile with { id = id }, ct);
res.Headers["x-session-token"] = token; // the client echoes this on its next read
return Results.NoContent();
});
app.MapGet("/profiles/{id}", async (string id, HttpRequest req, ProfileStore store, CancellationToken ct) =>
Results.Ok(await store.GetAsync(id, req.Headers["x-session-token"].FirstOrDefault(), ct)));
app.Run();
public sealed record Profile(string id, string DisplayName, string Suburb);
public sealed class ProfileStore(CosmosClient client)
{
private readonly Container _profiles = client.GetContainer("app", "profiles");
public async Task<string> SaveAsync(Profile p, CancellationToken ct)
{
var response = await _profiles.UpsertItemAsync(p, new PartitionKey(p.id), cancellationToken: ct);
return response.Headers.Session; // logical sequence number this write reached
}
public async Task<Profile> GetAsync(string id, string? sessionToken, CancellationToken ct)
{
// With the token, the replica must have caught up to the write before answering
var options = new ItemRequestOptions { SessionToken = sessionToken };
var response = await _profiles.ReadItemAsync<Profile>(id, new PartitionKey(id), options, ct);
return response.Resource;
}
}
CosmosClient; a read on another instance doesn't have it. Instead: pass the token through the client or route the user consistently.Consistency is a product decision expressed in technical terms. I write it down per feature ("basket: read-your-writes; stock: linearisable; recommendations: eventual") and that list drives the storage design. It also tells the UI team where they need optimistic updates or a "savingβ¦" state.
What each level does to latency and availability at scale. In a single region, Cosmos DB writes are acknowledged by a local quorum at every level, so the difference is mainly read cost: Strong and Bounded Staleness read from two replicas (about 2Γ RU), the others from one. Across regions the picture changes. With Strong, a write isn't acknowledged until it is committed in every region, so write latency includes the round trip to the furthest region (Australia East to Southeast is roughly 10β15 ms; adding a US region adds 150 ms or more), and if a region becomes unreachable writes stall until it is removed. Bounded Staleness acknowledges locally but throttles writes when the lag bound is reached, so a slow region can slow the writer. Session, Consistent Prefix and Eventual acknowledge locally and stay available for reads and writes during a regional outage; the price is stale reads and, with multi-region writes, conflicts to resolve.
Transient faults change what readers see. During a failover, a replica restart or a throttling burst (429s), clients retry and may be routed to a different replica or region. Under Session that's safe only if the session token travels with the retry; under Eventual a retry can return an older value than the first attempt saw, which breaks monotonic reads in the UI. Design for it: keep tokens, show 'last updated' times where staleness matters, and test failovers with Azure Chaos Studio or the Cosmos DB manual failover.
Measure before paying for strength: Cosmos DB reports RequestCharge per call and replication lag per region; SQL Server exposes redo_queue_size and secondary_lag_seconds for readable secondaries.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Strong | Invariants: stock, seats, balances | ~2Γ read RU, cross-region write latency, single write region | Read-heavy, low-value data |
| Bounded staleness | Ordered reads with a lag SLA | ~2Γ read RU, write throttling at the bound | Latency-critical writes |
| Session | User sees own changes | Token handling across instances | Data many users edit at once |
| Consistent prefix | Ordered feeds, chat | Stale but ordered | Need to see latest value |
| Eventual | Counters, analytics, caches | Anomalies and conflicts | Anything enforcing a limit |
CAP says that when a network partition splits a replicated data store, it must choose between consistency (every read sees the latest write, strictly linearisability) and availability (every working node still answers). Because partitions happen in any real network, "pick two of three" is misleading: the real choice is C or A during a partition. PACELC adds the part that matters every day: Else, when there's no partition, you trade latency against consistency, because keeping replicas in sync means waiting for them. Real systems sit at different points: SQL Server Always On with synchronous commit favours consistency at the cost of latency; Cosmos DB lets you choose one of five consistency levels; Redis replication is asynchronous and can lose acknowledged writes on failover. The trade-off is per use case, not per company.
CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.
Select/AsNoTracking or Dapper.There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.
CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.
An ETag is an opaque version identifier for a representation of a resource, returned in the ETag header. Clients send it back in conditional requests. On a GET, If-None-Match lets the server answer 304 Not Modified with no body when nothing changed, saving bandwidth. On a PUT, PATCH or DELETE, If-Match makes the write conditional: if someone else changed the resource since the client read it, the server returns 412 Precondition Failed instead of silently overwriting their change (the lost update problem). A SQL Server rowversion column, mapped with EF Core's IsRowVersion, makes a natural strong ETag. The trade-off: clients must read before they write and handle 412 by refreshing and retrying.
How to tell it (STAR)
**S:** Users of our [profile API] reported saved changes reverting, with no errors anywhere. **T:** I was asked to find out why. **A:** I correlated writes and reads in Application Insights and saw they landed on different instances, so the second Cosmos client had no session token and read from a lagging replica. I added session-token passing through the client instead of upgrading to Strong. **R:** Stale-read complaints dropped from [about 3%] of saves to zero, and we avoided roughly doubling our read RU cost.
Last updated 23 Nov 2026.