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

πŸ“š Interview question

In a design interview you've proposed a cache, a read model and a few services that talk through events. The interviewer asks: "So which parts of this are strongly consistent and which aren't?" How do you decide where a design needs strong consistency and where eventual consistency is fine, how do you make the eventual parts safe, and how do you explain the trade-off to a product owner?

Consistency trade-offs in system design: classifying data by the cost of staleness, invariants that need strong consistency, where eventual consistency is safe, read-your-writes and other session guarantees, compensations, and explaining it to stakeholders.

Senior Theory Advanced consistency cosmos-db eventual-consistency system-design trade-offs transactions

🎯 Key points

  • Decide per piece of data and per operation, not per system: ask what a stale or conflicting read costs the business
  • Strong consistency for invariants whose breach costs money or trust: negative balances, oversold stock, double-booked seats, duplicate usernames — keep each inside one transactional boundary
  • Eventual consistency is fine for derived and display data: search indexes, read models, counters, recommendations, notifications
  • Make eventual parts safe: transactional outbox (relayed by a worker, or a Functions trigger on the Cosmos DB change feed), idempotent consumers, ordering per key, reconciliation jobs
  • Design the UX for eventual consistency: read-your-writes for the actor, optimistic UI, 'processing' states instead of missing data
  • Session guarantees fix most complaints: Cosmos DB session consistency, read from the primary after a write, monotonic reads
  • Bound the staleness and measure it: replica lag, projection lag, cache TTL, with alerts on lag
  • Explain to stakeholders in business terms: how stale, for how long, what the user sees, what making it strong would cost

⏱ 30-second answer

I decide per piece of data, by asking what a stale or conflicting read costs the business. Invariants β€” a balance can't go negative, stock can't oversell, a seat can't be booked twice β€” need strong consistency, so I keep each one inside a single transactional boundary: one database, one aggregate, one partition. Derived data β€” search indexes, read models, dashboards, notifications β€” can be eventually consistent if I bound the lag and make the pipeline reliable with an outbox, idempotent consumers and reconciliation. Most user complaints are fixed by read-your-writes, not global strong consistency. To a product owner I say: "the order list may be up to two seconds behind, but your own new order always shows". The trade-off: strong consistency costs latency, availability and scale; eventual costs complexity and needs compensation paths.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I don't pick one consistency level for the whole system; I go through the data and ask one question: what happens if someone reads a stale or conflicting value? If the answer is money lost, a law broken or a promise we can't keep, that's an invariant and it needs strong consistency. If the answer is 'someone sees a slightly old list for a second', that's derived data and eventual consistency is fine.

So in this design, the stock reservation and the payment state are strong: they live in one Azure SQL database, the reservation is a conditional update in one transaction, and nothing else is allowed to change stock. The product search index, the 'orders' read model, the analytics and the emails are eventual: they're fed by events from an outbox, the consumers are idempotent, and I measure projection lag with an alert at, say, five seconds. For example, at [company] we [had support tickets saying 'my order disappeared' because the order history came from a read model that lagged by a few seconds]. Rather than make the read model synchronous, I [added read-your-writes: after placing an order the client was sent to the primary for that customer for 30 seconds], [and the tickets went to zero without touching the write path's latency].

The mistake I see is going strong everywhere because it feels safe β€” distributed transactions, synchronous calls to keep every copy in step β€” and getting a slow, fragile system; or the opposite, going eventual without an outbox, idempotency or reconciliation and quietly losing data. When I explain it to a product owner I use their words: how stale, for how long, what the user sees, and what making it strong would cost in latency and money. Strong where the business has an invariant, eventual everywhere else, and a reconciliation job for when eventual goes wrong."


Classify the data

Data Cost of stale / conflicting read Consistency How
Account balance, ledger Money lost, regulatory breach Strong Single DB transaction, double-entry, optimistic concurrency
Stock for checkout Overselling Strong at reservation Conditional UPDATE ... WHERE Available >= @qty
Seat or appointment slot Double booking Strong Unique constraint on (slot, resource)
Unique username / email Duplicate accounts Strong Unique index in one store
Order history list Confusion, tickets Eventual + read-your-writes Read model + session guarantee
Search index, recommendations Slightly old results Eventual Change feed / outbox projection
Dashboards, counters Approximate numbers Eventual Batched aggregation
Emails, notifications Late message Eventual, at-least-once Queue + idempotent sender

Session guarantees

Guarantee User-visible meaning How in Azure / .NET
Read-your-writes I always see my own change Cosmos DB Session consistency with the session token; route a user to the SQL primary for N seconds after a write
Monotonic reads I never see time go backwards Sticky replica per session; session token
Consistent prefix I see events in order Partition by key; ordered processing per key (Service Bus sessions)
Bounded staleness At most X seconds or K versions behind Cosmos DB Bounded Staleness; monitor replica lag

Production example

An order history read model lagged the write side by a p99 of [3 s], creating [~40] support tickets a week. Adding read-your-writes for 30 seconds after a write cut tickets to [0], and an outbox plus a nightly reconciliation between the ledger and the read model found and repaired [12] missed projections in the first month.

πŸ” What the interviewer is checking

Checks whether the candidate can place strong and eventual consistency deliberately in a design, make the eventual parts reliable, and explain the result in business terms.

Green flags

  • Classifies data by business cost of staleness and names concrete invariants
  • Keeps each invariant in one transactional boundary
  • Mentions outbox, idempotency, ordering and reconciliation
  • Uses session guarantees (read-your-writes) to fix UX problems

Red flags

  • "Everything must be strongly consistent" or "everything is eventual"
  • Proposes distributed transactions across services by default
  • No plan for lost or duplicate events

πŸ“š Learn in depth

1. What consistency means here

In a design discussion, "consistency" means what a reader can observe after a write. The spectrum (from strongest to weakest): linearisable β†’ sequential β†’ causal β†’ session guarantees (read-your-writes, monotonic reads) β†’ eventual. This is different from the C in ACID (constraints hold) β€” a common mix-up.

2. Invariants define the boundaries

An invariant is a rule that must never be broken, even briefly: balance >= 0, reserved <= stock, one booking per seat. The design rule:

one invariant  ->  one transactional boundary  ->  one owner

In DDD terms that boundary is the aggregate; physically it's one database (or one Cosmos DB logical partition, where transactional batches are scoped to a partition key).

3. The data flow

          strong (one transaction)                eventual (bounded lag)
[API] -> [Orders DB: order + stock + outbox] --> [relay] --> [Service Bus topic]
                                                     |-> [search projection]
                                                     |-> [order history read model]
                                                     |-> [email sender]
                     nightly: [reconciliation job] compares source vs projections

The outbox row is written in the same transaction as the business change, so an event is published if and only if the change committed.

4. Why not strong everywhere

PACELC: even without partitions, stronger consistency costs latency (synchronous replication, quorum reads). Across regions a synchronous write adds the round trip (Sydney–Melbourne ~10–15 ms; Sydney–US West ~150 ms). During a partition you must choose between refusing writes (C) or accepting divergent writes (A).

5. Making eventual safe

Risk Mitigation
Lost events Transactional outbox, at-least-once delivery
Duplicates Idempotent consumers (processed-message table, natural idempotency)
Reordering Partition by entity key, ordered sessions, version numbers that ignore older updates
Silent drift Reconciliation jobs, lag metrics, dead-letter alerts
Business conflicts Compensation: refund, apologise, back-order

6. Explaining it

Use a sentence with three parts: what can be stale, by how much, and what the user sees. "Search can be up to 5 seconds behind after a price change; checkout always uses the live price, so nobody pays the wrong amount."

7. Try it yourself

  1. List ten pieces of data in a system you know and classify each with the table above.
  2. In the Cosmos DB emulator, write with Session consistency and read with and without the session token from a second client; observe the difference.
  3. Build a tiny outbox: write an order and an outbox row in one EF Core transaction, and a BackgroundService that publishes and marks rows sent.
  4. Measure projection lag by stamping events with a UTC timestamp and recording now - timestamp in the consumer as a metric.
  5. Write a reconciliation query that finds orders with no row in the read model after 10 minutes.

πŸ’» Code

Strong where there is an invariant (a conditional update inside one transaction), eventual for the rest (an outbox row in the same transaction).

namespace Shop.Checkout;

using System.Text.Json;
using Microsoft.EntityFrameworkCore;

public sealed record ReserveStock(Guid OrderId, Guid ProductId, int Quantity);

public sealed class OutboxMessage
{
    public Guid Id { get; init; } = Guid.CreateVersion7();
    public required string Type { get; init; }
    public required string Payload { get; init; }
    public DateTimeOffset CreatedAt { get; init; } = DateTimeOffset.UtcNow;
    public DateTimeOffset? SentAt { get; set; }
}

public sealed class ReservationService(ShopDbContext db)
{
    public async Task<bool> ReserveAsync(ReserveStock cmd, CancellationToken ct)
    {
        await using var tx = await db.Database.BeginTransactionAsync(ct);

        // Invariant: reserved stock never exceeds available stock.
        // The WHERE clause makes check-and-decrement one atomic statement, so two buyers can't both win.
        var updated = await db.Stock
            .Where(s => s.ProductId == cmd.ProductId && s.Available >= cmd.Quantity)
            .ExecuteUpdateAsync(s => s.SetProperty(x => x.Available, x => x.Available - cmd.Quantity), ct);

        if (updated == 0) return false; // sold out: the caller tells the user immediately

        // Everything downstream (search, history, email) is eventual and fed from this row.
        db.Outbox.Add(new OutboxMessage
        {
            Type = "StockReserved",
            Payload = JsonSerializer.Serialize(cmd)
        });
        await db.SaveChangesAsync(ct);
        await tx.CommitAsync(ct);
        return true;
    }
}

Read-your-writes with Cosmos DB session tokens: return the token to the client and send it back on the next read.

namespace Shop.History;

using Microsoft.Azure.Cosmos;

public sealed record OrderView(string id, string customerId, decimal total);

public sealed class OrderHistory(Container container)
{
    public async Task<string> SaveAsync(OrderView order, CancellationToken ct)
    {
        var response = await container.UpsertItemAsync(order, new PartitionKey(order.customerId), cancellationToken: ct);
        return response.Headers.Session; // the client keeps this token
    }

    public async Task<OrderView> GetAsync(string id, string customerId, string? sessionToken, CancellationToken ct)
    {
        var options = new ItemRequestOptions { SessionToken = sessionToken }; // guarantees the reader sees its own write
        var response = await container.ReadItemAsync<OrderView>(id, new PartitionKey(customerId), options, ct);
        return response.Resource;
    }
}

⚠ Common mistakes

  • Mistake: Choosing one consistency level for the whole system. Why it is wrong: Most data doesn't need strong consistency, and forcing it everywhere costs latency, availability and scale. Instead: Classify each piece of data by the cost of a stale read.
  • Mistake: Spreading one invariant across services. Why it is wrong: You then need distributed transactions or accept that the invariant can be broken β€” an oversold flash sale means refunds, angry customers and possibly ACL (Australian Consumer Law) complaints; a negative balance means real money lost. Instead: Keep each invariant inside one transactional boundary with one owner.
  • Mistake: Publishing events after SaveChanges with a separate call. Why it is wrong: A crash between the two loses the event and the read side drifts for ever. Instead: Use a transactional outbox. Relay it with a BackgroundService, or on Azure let a Functions trigger do the work: the Azure SQL trigger (change tracking) on the outbox table, or the Cosmos DB change feed trigger when the source is Cosmos DB.
  • Mistake: Assuming exactly-once delivery. Why it is wrong: Brokers deliver at least once; duplicates double-apply effects. Instead: Make consumers idempotent and processing ordered per key.
  • Mistake: Making a read model synchronous to fix "my change disappeared" complaints. Why it is wrong: It couples the write path to the read path. Instead: Provide read-your-writes for the user who made the change.
  • Mistake: Designing screens as if every read is current. Why it is wrong: Users see items vanish or reappear and lose trust. Instead: Show the user's own change immediately (optimistic UI or read-your-writes), and show a clear 'processing' or 'updated a few seconds ago' state for derived data.
  • Mistake: Not measuring lag. Why it is wrong: "Eventually" can silently become hours when a consumer is stuck. Instead: Emit projection and replica lag metrics and alert on them; dead-letter alerts too.
  • Mistake: Explaining consistency with CAP jargon to a product owner. Why it is wrong: They can't make a decision from it. Instead: Say what can be stale, by how much, what the user sees, and what the alternative costs.

πŸ› Senior insight: trade-offs

Seniors treat consistency as a product decision backed by engineering: the business already lives with eventual consistency (bank transfers settle later, airlines overbook and compensate), so the question is where it is unacceptable. Keep the strongly consistent core small and boring β€” one database, short transactions β€” and make everything else asynchronous with outbox, idempotency and reconciliation. Measure lag and drift so "eventual" has a number.

Option When it fits Cost When not to
Single-DB transaction Invariant within one service Scales only as far as one primary Data owned by several services
Saga with compensation Business process across services Complex states, compensations When a real invariant must never break even briefly
Outbox + projections Derived read models, integrations Lag, reconciliation work User must see the result in the same request (use read-your-writes)
Cosmos DB Session Per-user consistency at low cost Token handling Cross-user invariants
Cosmos DB Strong / multi-region sync Rare global invariants Latency, availability, cost Most workloads

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions read-your-writes or Cosmos DB consistency levels Why: Checks they know the consistency models and when to use each
    How to 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.

  2. When: Candidate mentions a saga or an outbox Why: Checks they can choose between one transaction, outbox and saga for a multi-step process
    How to answer

    I start with the invariants. If something must be true at every instant (a balance never negative, a seat never double-booked), that data belongs in one aggregate, one service and one local transaction. Often the right answer is to redraw the boundary.

    If other services only need to react and their effects never need undoing (send a receipt, update search), I use the transactional outbox with idempotent consumers: simple, at-least-once and eventually consistent.

    If a later step can fail for business reasons and earlier steps must be undone (payment declined after stock was reserved), I build a saga, usually orchestrated, with compensations, timeouts and persisted state.

    The trade-off: each step up buys flexibility across team and service boundaries, but costs complexity, latency and operating effort, so I pick the lowest one that meets the business rules.

  3. When: Candidate mentions CAP or partitions Why: Checks they understand what CAP and PACELC really say
    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.

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

"My order disappeared" tickets from a lagging read model
Situation
[Online retailer] with an order history screen served from a [Cosmos DB] read model fed by events from the [Azure SQL] orders database; [~15,000] orders a day.
Signals
[~40] support tickets a week saying a just-placed order was missing; projection lag p99 of [3 s], spiking to [40 s] during sales; occasional orders missing for good.
Investigation
Added a lag metric (now minus event timestamp) in the projector and charted it in Azure Monitor; compared order ids in SQL and Cosmos DB with a reconciliation query; found events were published after SaveChanges in a separate call, so crashes lost some.
Resolution
Immediately sent the customer's next reads to the SQL primary for 30 seconds after placing an order. Then moved publishing to a transactional outbox with an idempotent projector, and added a nightly reconciliation that re-projects missing orders.
Prevention
Lag and reconciliation-mismatch alerts, an architecture test that forbids publishing outside the outbox, and an ADR listing which data is strong and which is eventual with its allowed lag.

How to tell it (STAR)

**S:** Customers kept telling us their new order had disappeared from their history. **T:** I had to fix it without slowing down checkout. **A:** I measured the read model's lag, found it was seconds normally and occasionally permanent because events could be lost. I added read-your-writes for the customer who just ordered, moved publishing to an outbox with an idempotent projector, and added a nightly reconciliation. **R:** The tickets went from [~40] a week to [0], and reconciliation repaired [12] missed orders in the first month.

More in Senior Design Focus

Last updated 23 Nov 2026.

🌐 Sangam's Webring

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