📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Explain the main consistency models in distributed data stores: strong (linearisable), read-your-writes, monotonic reads, consistent prefix and eventual. Use Cosmos DB's five consistency levels as an example, and tell me how you would choose one for a feature.

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.

Mid-Level Theory Intermediate consistency-models cosmos-db distributed-systems eventual-consistency read-your-writes replication

🎯 Key points

  • A consistency model is a contract about which values a read may return after writes on other replicas
  • Strong (linearisable): every read sees the latest committed write, as if one copy existed
  • Session guarantees: read-your-writes, monotonic reads, monotonic writes, writes-follow-reads
  • Consistent prefix: reads never see writes out of order, but may lag; Eventual: replicas converge if writes stop
  • Cosmos DB: Strong, Bounded Staleness (K versions or T seconds), Session (default), Consistent Prefix, Eventual; stronger costs more RU and latency
  • Strong across regions makes every write wait for remote regions and blocks writes when a region is unreachable
  • Session in Cosmos DB relies on the session token; losing it across instances breaks read-your-writes
  • Choose per feature by asking what a stale or out-of-order read would cost the user or the business

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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 CosmosClient instance. 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."


The models, strongest to weakest

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

Cosmos DB levels in practice (as of November 2026)

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

Production example

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.

πŸ” What the interviewer is checking

Checks whether the candidate can name the consistency models precisely, map them to a real product, and choose based on business impact.

Green flags

  • Distinguishes linearisable, session guarantees, consistent prefix and eventual.
  • Knows Cosmos DB's five levels and their costs.
  • Knows the session-token pitfall across instances.
  • Chooses per feature with a reason.

Red flags

  • "Eventual means it's a bit slow."
  • Can't explain read-your-writes.
  • Strong everywhere without considering cost.

πŸ“š Learn in depth

1. Where inconsistency comes from

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.

2. Linearisability

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).

3. The session guarantees (Terry et al., 1994)

  • Read-your-writes: after you write, your reads reflect it.
  • Monotonic reads: once you've seen a version, you never see an older one.
  • Monotonic writes: your writes apply in the order you issued them.
  • Writes-follow-reads: a write you make after reading X is ordered after X.

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.

4. Consistent prefix and eventual

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.

5. How Cosmos DB implements the levels

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.

6. Choosing per feature

Ask three questions:

  1. If a user sees data 5 seconds old, what breaks?
  2. If a user sees their own change disappear, what breaks?
  3. If events appear out of order, what breaks?

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.

Try it yourself

  1. With the Cosmos DB emulator, write an item and read it back with two different CosmosClient instances; log the session token from the write response.
  2. Pass the token to the second client via ItemRequestOptions.SessionToken and confirm the read reflects the write.
  3. Compare RequestCharge for the same read under Session and under Eventual.
  4. Model a chat thread and explain which anomaly Consistent Prefix prevents that Eventual allows.

πŸ’» Code

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;
    }
}

⚠ Common mistakes

  • Mistake: Using "eventual consistency" as if it meant "consistent within a second". Why it is wrong: eventual gives no time bound or ordering; lag can be long during failures. Instead: use Bounded Staleness or measure replication lag if you need a bound.
  • Mistake: Assuming Session consistency works across API instances automatically. Why it is wrong: the session token lives in each CosmosClient; a read on another instance doesn't have it. Instead: pass the token through the client or route the user consistently.
  • Mistake: Choosing Strong everywhere "to be safe". Why it is wrong: it doubles read RU, adds latency and blocks multi-region writes. Instead: use Strong only for the invariants that need it.
  • Mistake: Choosing Eventual for counters that enforce limits. Why it is wrong: concurrent writers on stale data oversell or overspend. Instead: use a single writer, optimistic concurrency with ETags, or Strong.
  • Mistake: Relying on last-writer-wins with wall-clock timestamps for conflicts. Why it is wrong: clock skew silently discards newer writes. Instead: use versions, a custom merge or CRDTs.
  • Mistake: Reading from a SQL Server readable secondary right after a write. Why it is wrong: redo on the secondary is asynchronous, so you may not see your own write. Instead: read your own writes from the primary.

πŸ› Senior insight: trade-offs

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

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions that stronger levels cost latency or availability. Why: Checks the theory behind the trade-off between consistency, latency and availability.
    How to answer

    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.

  2. When: Candidate mentions read models or replicas lagging. Why: Checks how eventual consistency from a read model is handled in the UI.
    How to answer

    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.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with 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.

  3. When: Candidate mentions ETags or concurrent updates. Why: Checks optimistic concurrency as a way to protect invariants without strong consistency.
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Saved profile changes "revert" behind a load balancer
Situation
A customer-profile API ran as [three] instances on Azure App Service in Australia East, backed by Cosmos DB with Session consistency and [n] reads per second.
Signals
Support tickets: "my new address disappeared after I saved it"; about [3%] of profile saves followed by a stale read within 2 seconds; no errors in Application Insights.
Investigation
Correlated the write and the following read in Application Insights by user id and saw they hit different instances; logged the session token returned by the write and the one used by the read (none); confirmed with the Cosmos DB diagnostics string that the read went to a lagging replica.
Resolution
Immediate: enabled ARR affinity to keep users on one instance. Real fix: returned the session token in a response header, had the SPA send it back on reads, and passed it via `ItemRequestOptions.SessionToken`; removed affinity afterwards.
Prevention
An integration test that writes through one client and reads through another with the token; consistency requirements documented per container in an ADR; a dashboard of stale-read complaints tagged in support.

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.

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me