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

📚 Interview question

You're designing a system where reads outnumber writes 50 to 1 and the read screens need data from several modules. How would you apply CQRS at the architecture level: separate read stores, projections, handling eventual consistency in the UX, and deciding whether you also need event sourcing?

Architecture-level CQRS for a read-heavy .NET system: the spectrum from split handlers to separate read stores, building projections from events or change feeds, choosing the read store, designing UX for eventual consistency, and why CQRS does not require event sourcing.

Senior Architecture Advanced architecture azure cqrs eventual-consistency projections read-models

🎯 Key points

  • CQRS separates the write model (aggregates, invariants) from the read model (query-shaped DTOs) so each can evolve, scale and be stored independently
  • Treat it as tiers: split handlers on one database, then read-optimised views in the same database, then separate read stores fed by events
  • Projections built from integration events (outbox) or change feeds; idempotent with version checks and checkpoints
  • Read store chosen per query shape: SQL summary tables/indexed views, Azure Cosmos DB, Azure AI Search, Redis
  • UX for eventual consistency: return the new state from the command, optimistic UI, version tokens, read-your-writes from the write store
  • Event sourcing is optional; CQRS works with state-based EF Core writes plus outbox events
  • Move up a tier only on measured triggers: read p95 vs SLO after indexing, database CPU/DTU, cross-module queries
  • Projection lag is an SLO with alerts; rebuild projections side by side

⏱ 30-second answer

CQRS at the architecture level separates the write model (aggregates enforcing invariants, normalised SQL) from the read model (denormalised, query-shaped data) so the read side can live in a different store and scale on its own. I adopt it in tiers, each only when measurements justify it: first separate command and query handlers on one database; then read-optimised views in the same database; and only then separate read stores (Cosmos DB, Azure AI Search, Redis) fed by projections from outbox events.

Separate stores make reads eventually consistent, so I design the UX for it: return the new state from the command, use optimistic UI, or read from the write side right after a change. Event sourcing is optional.

The trade-off: read scalability and simpler queries versus projection plumbing, lag and two models to keep in sync.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd treat CQRS as a ladder rather than a switch. Level one is just separating command handlers from query handlers in code; queries use AsNoTracking and project straight into DTOs. Level two keeps one database but adds read-optimised structures: indexed views, a denormalised summary table maintained in the same transaction, or a read replica. Level three gives the read side its own store, populated asynchronously by projections. With reads at 50 to 1 and screens that join data from several modules, I'd expect to need level two for most screens and level three for the cross-module ones, because a module shouldn't query another module's tables.

For level three, each module publishes integration events through an outbox, and a projection service subscribes and builds a read model per screen: say an OrderOverview document in Cosmos DB, partitioned by customer, or an Azure AI Search index for free-text search. Projections are idempotent, keep a checkpoint, and can be rebuilt side by side. For example, at [company] we [moved a dashboard that joined five modules to a projected read model], which [took p95 from around 1.8 s to 120 ms and removed the cross-module queries]. The pushback was eventual consistency, so we [returned the new state from the command and showed a 'processing' state for the rare case the projection lagged], and recorded the decision in [an ADR] with projection lag as an SLO.

On event sourcing: it's a separate decision. CQRS with separate read stores works perfectly well with EF Core state-based writes and an outbox. I'd only add event sourcing if the history itself were a requirement.

The mistake I see is jumping to level three on day one, with a message broker and a NoSQL read store for screens a well-indexed SQL query would serve in 20 ms."


The CQRS ladder

Level Read side Consistency Cost Fits when
1. Split handlers Same tables, AsNoTracking projections Immediate Almost none Default for any app
2. Read-optimised, same DB Indexed views, summary tables, read replica Immediate (or replica lag, seconds) Low Hot queries, moderate scale
3. Separate read store Cosmos DB, AI Search, Redis, reporting DB Eventual (ms to seconds) Projections, broker, ops Cross-module views, very high read scale, search
3 + event sourcing Projections from the event log Eventual High History is a business requirement

Decision table

Driver Points to lower levels Points to level 3
Read/write ratio < 10:1 50:1 and up with heavy read SLOs
Query shape Fits relational indexes Free-text, geo, per-user feeds
Data spans modules No Yes, and modules own their data
Team size and ops maturity One team, little platform support Several teams, broker and observability in place
Consistency need Users must see writes instantly everywhere Seconds of lag acceptable on most screens

Production example

A [logistics] portal served about 3,000 reads per second against 60 writes per second. Moving its shipment-tracking screen to a Cosmos DB projection fed from outbox events cut Azure SQL DTU usage by 45% and p95 latency from 900 ms to 80 ms. Median projection lag was 250 ms, and the p99 lag SLO of 5 seconds was breached twice in six months, both during broker throttling.

🔍 What the interviewer is checking

Checks that the candidate can apply CQRS proportionately at the architecture level, design projections and read stores, and treat eventual consistency as a UX and product concern.

Green flags

  • Describes CQRS as a ladder and starts low
  • Builds projections from outbox events with idempotency and checkpoints
  • Chooses read stores by query shape and residency needs
  • Has concrete UX techniques for lag and treats it as a product decision
  • States clearly that event sourcing is optional

Red flags

  • Equates CQRS with event sourcing or with MediatR
  • Separate databases by default without measurement
  • No plan for lag, rebuilds or monitoring

📚 Learn in depth

1. What CQRS actually separates

Command-Query Separation (Bertrand Meyer) says a method either changes state or returns data. CQRS (Greg Young) applies that at the model level: the model that enforces rules doesn't have to be the model you query.

             Commands                                Queries
                |                                       |
                v                                       v
+---------------------------+            +---------------------------+
| Write model               |            | Read model                |
| Aggregates, invariants    |            | Flat DTOs per screen      |
| EF Core, normalised SQL   |            | No business rules         |
+-------------+-------------+            +-------------^-------------+
              | outbox events                          |
              v                                        |
        Azure Service Bus  -->  Projection handlers  --+
                                (idempotent, checkpointed)

2. Building projections

Sources, in order of preference:

  1. Integration events via outbox: business-meaningful, decoupled from the write schema.
  2. Change feeds: SQL Server change tracking or CDC, Cosmos DB change feed. Good for replicating tables you own, but they expose your schema.
  3. Event store subscriptions: if you event source.

Each projection stores a checkpoint and applies events idempotently (upsert by id plus version check: ignore an event whose version is older than the stored one).

3. Choosing the read store

Store Good for Watch out for
Same Azure SQL (summary tables, indexed views) Most dashboards and lists Write amplification, locking
Azure SQL read replica / geo-replica Offloading reporting Replica lag, read-only
Azure Cosmos DB Per-entity documents, global low latency Partition key design, RU cost
Azure AI Search Free-text, facets Indexing lag, cost per replica
Redis Hot keys, leaderboards Memory cost, persistence

Keep data in Australia East / Southeast where residency matters (Privacy Act, APRA CPS 234 for regulated entities); projections copy personal information, so they are in scope for retention and deletion.

4. UX patterns for eventual consistency

User clicks "Cancel order"
  -> POST /orders/42/cancel  -> 200 { status: "Cancelled", version: 7 }
  -> UI updates from the response (no re-query)
  -> list screen queries read model; if its version < 7, show "updating..." or poll briefly
  • Return the new state from the command.
  • Optimistic UI: show the expected result, reconcile later.
  • Version tokens: client sends the version it expects; read API waits briefly or flags staleness.
  • Read-your-writes: for the actor's own detail screen, read from the write store for a few seconds.
  • Say it in the UI when it matters ("Your change may take a few seconds to appear in reports").

5. CQRS without event sourcing

Most .NET systems that benefit from CQRS keep EF Core aggregates and add an outbox. Event sourcing adds history and replay, but also versioning and tooling cost. The two are independent decisions.

6. Failure modes

  • Projection falls behind (broker throttling, poison message): alert on lag, dead-letter and continue.
  • Projection bug: fix, rebuild under a new name, switch reads.
  • Out-of-order events: version checks in projections; sessions for per-entity ordering.

Try it yourself

  1. Take one slow screen, write a level-one AsNoTracking().Select(...) query and measure; then add a covering index and measure again before considering a read store.
  2. Build a projection that consumes outbox events into a summary table with a version check; replay the same events twice and verify idempotency.
  3. Add a lag metric (now minus event occurred-at) to Application Insights and chart p50 and p99.
  4. Implement a "return new state from command" endpoint and remove the follow-up GET from the client.
  5. Rebuild the projection under a new table name while the old one serves traffic, then switch.

💻 Code

A layout for a read-heavy system, the projection handler with a version check, and a query endpoint that reads the projection.

src/
  Ordering/                      # write side module (EF Core aggregates, outbox)
  Shipping/                      # write side module
  ReadModels/
    ReadModels.Projections/      # consumers of integration events, idempotent upserts
    ReadModels.Api/              # query endpoints, no business rules
  Contracts/                     # per-module integration event packages
namespace ReadModels.Projections;

using Microsoft.EntityFrameworkCore;
using Ordering.Contracts;

// A denormalised row shaped for one screen. It holds no business rules:
// the Ordering module's aggregate decides status changes; this only records them.
public sealed class OrderOverview
{
    public Guid OrderId { get; set; }
    public Guid CustomerId { get; set; }
    public string Status { get; set; } = "";
    public decimal Total { get; set; }
    public string? TrackingNumber { get; set; }
    public long Version { get; set; }   // the aggregate version of the last event applied
}

public sealed class OrderOverviewProjection(ReadModelsDbContext db)
{
    public async Task HandleAsync(OrderStatusChangedV1 e, CancellationToken ct)
    {
        var row = await db.OrderOverviews.FindAsync([e.OrderId], ct);
        if (row is null)
        {
            // First event we've seen for this order: create the row.
            db.OrderOverviews.Add(new OrderOverview
            {
                OrderId = e.OrderId, CustomerId = e.CustomerId, Status = e.Status, Total = e.Total, Version = e.Version
            });
        }
        else if (e.Version > row.Version)
        {
            // Why the version check: Service Bus delivers at least once and only orders within a session.
            // A duplicate has Version == row.Version, a late out-of-order event has Version < row.Version;
            // both are skipped, so replays and rebuilds are safe (the handler is idempotent).
            row.Status = e.Status;
            row.Total = e.Total;
            row.Version = e.Version;
        }
        // Duplicates and stale events fall through: SaveChanges has nothing to write and the message is completed.
        await db.SaveChangesAsync(ct);
    }
}
// ReadModels.Api/Program.cs: queries hit the projection only, never the write modules' tables,
// so module boundaries stay intact and the query is a single indexed lookup.
app.MapGet("/customers/{customerId:guid}/orders", async (Guid customerId, ReadModelsDbContext db, CancellationToken ct) =>
    await db.OrderOverviews.AsNoTracking()
        .Where(o => o.CustomerId == customerId)
        .OrderByDescending(o => o.Version)
        .Select(o => new { o.OrderId, o.Status, o.Total, o.TrackingNumber })
        .Take(50)
        .ToListAsync(ct));

⚠ Common mistakes

  • Mistake: Starting with separate read stores and a broker for a modest app. Why it is wrong: adds projections, lag and ops for screens SQL serves in milliseconds. Instead: climb the ladder; measure before each step.
  • Mistake: Assuming CQRS requires event sourcing. Why it is wrong: doubles the cost for no benefit when history isn't needed. Instead: state-based writes plus outbox events.
  • Mistake: Putting business rules in projections or query handlers. Why it is wrong: rules then exist in two places and drift. Instead: rules live on the write side; projections only reshape.
  • Mistake: Non-idempotent projections. Why it is wrong: at-least-once delivery and rebuilds double count. Instead: upsert with version checks and checkpoints.
  • Mistake: Ignoring the UX of lag. Why it is wrong: users click twice or report bugs when a list doesn't show their change. Instead: return new state, optimistic UI, read-your-writes.
  • Mistake: Projecting from another module's database tables. Why it is wrong: couples the read side to private schemas. Instead: project from published integration events.
  • Mistake: Not monitoring projection lag. Why it is wrong: stale reads go unnoticed until customers complain. Instead: lag as an SLO with alerts.
  • Mistake: Forgetting projections hold personal information. Why it is wrong: deletion and retention obligations apply to every copy. Instead: include read stores in privacy and retention design.

🏛 Senior insight: trade-offs

The senior move is to separate the decision to split models from the decision to split stores. Splitting models (the first tier) is almost always right; splitting stores is an infrastructure decision you justify with numbers. I write the trigger into the ADR, for example "move this screen to a separate read store when its p95 exceeds 300 ms after indexing, or when it needs data from more than one module".

The indicators I review before moving up a tier:

  • Read latency per screen (Application Insights request p95/p99) against its SLO, after indexing and projection tuning.
  • Database pressure: Azure SQL CPU/DTU or vCore utilisation, and Query Store top consumers. If one or two read queries dominate, a summary table or replica usually beats a new store.
  • Read/write ratio and growth: a 50:1 ratio growing 30% a quarter is a different decision from a flat one.
  • Boundary violations: cross-module joins or architecture-test exemptions.
  • Business need: free-text search, per-user feeds, or global latency that relational indexes can't meet.

After moving, I keep measuring: projection lag p50/p99, rebuild time, the cost of the read store, and "my change didn't show" support tickets. I also push back on the idea that eventual consistency is purely technical. It's a product decision: which screens can be a second behind, and what users see when they are. I agree that per screen with the product owner.

Option When it fits Cost When not to
Split handlers, one DB Any application Negligible Never a bad start
Read-optimised structures, same DB Hot queries, one module Index and write overhead Cross-module joins
Separate read store via projections Cross-module views, 50:1 reads, search Broker, projections, lag Small team, no messaging
Plus event sourcing History is a requirement Versioning, skills Everything else

🔗 Follow-ups the interviewer may ask

  1. When: Candidate jumps straight to separate stores without explaining CQRS itself. Why: Checks the pattern-level basics behind the architecture answer.
    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.

  2. When: Candidate mentions projections or event sourcing. Why: Checks they can separate CQRS from event sourcing and know when to add it.
    How to answer

    Event sourcing stores every state change as an immutable event in an append-only stream per aggregate, and derives current state by replaying those events. The event log is the source of truth; tables you query are projections built from it. Appends use the expected stream version for optimistic concurrency. Snapshots speed up replay for long streams, and events are evolved by additive changes and upcasting, never by editing history.

    It's worth it when the history itself is valuable: audit, temporal queries ("what did we know on 1 July?"), complex behaviour. It's a poor fit for CRUD and for teams new to it, because you pay in eventual consistency, schema evolution and harder queries.

  3. When: Candidate says screens need data from several modules. Why: Checks how module data ownership drives read models across modules.
    How to answer

    A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.

    • Each module owns its data: its own schema and DbContext, no cross-module joins or foreign keys.
    • Modules talk only through a public contract (an interface and DTOs) or integration events; everything else is internal.
    • Boundaries are enforced: separate projects, internal types, architecture tests, even per-schema database permissions.

    You get microservice-style boundaries with monolith-style operations: one pipeline, in-process calls, easy refactoring. The trade-off: one runtime, one release and one scaling unit, and it only works if the boundaries are enforced — otherwise it decays into a big ball of mud.

🛠 Real-world problems: how you handle them

Cross-module dashboard queries overloading Azure SQL
Situation
A [freight] modular monolith on Azure SQL (Australia East) had a customer dashboard that joined tables from [five] modules. Reads ran at [~50:1] against writes, with [~2,000] concurrent users at month end.
Signals
Dashboard p95 rose to [1.8 s]; Azure SQL DTU hit [95%] at month end; Query Store showed the dashboard query as the top consumer; architecture tests had an exemption list for it because it crossed module boundaries.
Investigation
Query Store and execution plans for the top queries; Application Insights dependency timings per screen; a review of which screens crossed module boundaries; a spike projecting outbox events into a single read table.
Resolution
Short term: covering indexes and a read replica for reporting. Long term: an `OrderOverview` read model in its own schema fed by integration events from each module, idempotent with version checks, with the dashboard reading only that table. Recorded in [an ADR] with a 5-second p99 lag SLO.
Prevention
Architecture tests with the exemption removed; projection lag alerts; a rule that new cross-module screens use projections; quarterly review of read SLOs.

How to tell it (STAR)

**S:** At [company], our dashboard joined [five] modules' tables and pushed Azure SQL to [95%] DTU at month end. **T:** As [tech lead], I needed to fix performance without breaking module boundaries further. **A:** I used Query Store to confirm the culprit, ran a [one-week] spike projecting outbox events into a read table, and wrote an ADR comparing that with a read replica. The team worried about stale data, so I agreed a lag SLO with the product owner and added a processing indicator. **R:** p95 dropped from [1.8 s] to [120 ms], DTU peaked at [55%], and we removed the last architecture-test exemption.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me