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

📚 Interview question

What is CQRS? Explain separating commands and queries into different models, the levels from separate handlers on one database to separate read stores updated by events, how it relates to CQS and to MediatR, how you handle eventual consistency in the UI, and when CQRS is overkill.

CQRS (Command Query Responsibility Segregation): CQS (Meyer) vs CQRS (Young), separate write model (aggregates, invariants) and read model (projections/DTOs), levels from handlers on one database to a synchronous denormalised table to a separate read store fed by events, eventual consistency and read-your-writes in the UI, relationship to MediatR and event sourcing, and when CQRS is overkill.

Mid-Level Theory Intermediate cqrs design-patterns domain-driven-design ef-core eventual-consistency read-models

🎯 Key points

  • CQS (Bertrand Meyer): a method either changes state or returns data, not both; CQRS (Greg Young) applies that split to whole models
  • Write model: aggregates with invariants loaded through repositories; read model: flat DTOs/projections shaped for each screen
  • Level 1: separate command and query handlers on one database (reads project with Select/AsNoTracking or Dapper) - cheap and usually enough
  • Level 2: denormalised read tables or indexed views updated in the same transaction - still strongly consistent
  • Level 3: separate read store (Azure SQL replica, Cosmos DB, Elasticsearch) updated asynchronously from events, ideally via an outbox - eventually consistent, with replay, idempotent projections and lag monitoring to operate
  • Eventual consistency needs UI handling: return the new state from the command, read-your-writes from the primary, version numbers with polling until caught up, or explicit 'processing' states
  • MediatR is a dispatch mechanism, not CQRS; CQRS doesn't require MediatR or event sourcing
  • Overkill for CRUD with simple reads and writes on the same shape; it pays off when read and write shapes, scale (e.g. 100:1 read/write) or rules diverge

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"CQRS starts from Bertrand Meyer's CQS: a method should either change state or return data, not both. Greg Young took that up a level: use different models for writing and reading. The write model is about protecting invariants: an Order aggregate with Submit() and Cancel(), loaded whole, changed through its methods, saved through the unit of work. The read model is about answering a screen's question fast: an OrderSummaryDto with customer name, total and status, projected straight from the database with no tracking and no aggregate.

I describe it as levels, because people jump to the most expensive one. Level one is separate command and query handlers on the same database. Commands go through aggregates; queries use Select projections or Dapper. That's nearly free and solves most of the problem. Level two adds denormalised read tables, or an indexed view, updated in the same transaction as the write, so it's still strongly consistent. Level three uses a separate read store, like Elasticsearch for search or Cosmos DB for a high-traffic catalogue, updated asynchronously from events. That's where you get independent scaling, and also eventual consistency. Events should come from an outbox, and projections must be idempotent and monitored for lag. For example, at [company] we [moved order search to a separate read store fed by events], and [a stuck projection meant customers saw stale order statuses for [n] minutes]. I [added projection-lag monitoring and returned the new state directly from the command], and [complaints about stale data stopped].

Two things I always clarify. MediatR isn't CQRS: it's an in-process dispatcher you can use with or without it. And CQRS doesn't require event sourcing; they work well together but they're separate decisions. The mistake I see is a CRUD admin service with a command, a handler, a validator, a query and a read model for every field edit, which is five files where one endpoint would do. I start at level one and only move up when the read and write shapes, scale or consistency needs actually diverge."


CQRS levels

Level What it is Consistency Cost Fits when
0 One model, one service Strong None CRUD
1 Separate command/query handlers, same DB Strong Low Most business services
2 Denormalised read tables/indexed views, same transaction Strong Medium Expensive joins on hot reads
3 Separate read store fed by events Eventual High Search, very high read scale, different query engines
+ ES Event-sourced write side Eventual reads Highest Audit-critical domains needing full history

Handling eventual consistency

Technique How
Return state from the command API responds with the new order status, so the UI doesn't re-query
Read-your-writes Query the primary for the user's own recent changes
Version/sequence checks Read model stores the last applied version; UI waits or polls until it's caught up
Explicit pending states Show "Processing" rather than stale data
Lag monitoring Alert when projection lag passes a threshold

Production example

A product catalogue served about 3,000 reads a second against 20 writes a second. Moving search and listing to an Azure AI Search index fed by outbox events took listing p95 from about 350 ms to 40 ms and removed most read load from Azure SQL. Projection lag was normally under 2 seconds, with an alert at 30 seconds.

🔍 What the interviewer is checking

Checks whether the candidate understands CQRS as separate models with a range of implementations, and can handle eventual consistency and judge when it's overkill.

Green flags

  • Distinguishes CQS from CQRS.
  • Describes levels, starting with handlers on one database.
  • Explains eventual consistency and concrete UI strategies.
  • Separates CQRS from MediatR and event sourcing.
  • Names when not to use it.

Red flags

  • "CQRS means using MediatR."
  • Always requires two databases and event sourcing.
  • Ignores stale reads.
  • Applies it to every CRUD screen.

📚 Learn in depth

1. CQS to CQRS

  • CQS (Meyer, Object-Oriented Software Construction): methods are commands (void, change state) or queries (return a value, no side effects). Stack.Pop() breaks it on purpose.
  • CQRS (Young, around 2010): two objects/models where there was one. Commands target the write model; queries target the read model.
           Command (PlaceOrder)                    Query (GetOrderSummaries)
                 |                                          |
        Command handler                              Query handler
                 |                                          |
   Repository -> Order aggregate (invariants)       SELECT ... projection (no tracking)
                 |                                          ^
         SaveChanges + outbox  ---- events ---->  Projection updates read model
                 |                                  (level 3 only)
           Write database                      Read store (same DB at levels 1-2)

2. Why the models diverge

Write models are normalised and behaviour-rich so rules hold; read models are denormalised and shaped per screen so queries are cheap. Forcing one model to do both gives aggregates with display-only properties, or DTOs with business rules.

3. Level 1 in .NET

Command handlers take a repository or DbContext and commit; query handlers project with AsNoTracking().Select(...), or use Dapper/raw SQL for complex reports. Can run queries against a readable secondary (Azure SQL ApplicationIntent=ReadOnly) for scale, accepting replica lag.

4. Level 2

A denormalised OrderSummaries table updated in the same SaveChanges as the aggregate, or a SQL Server indexed view. Strongly consistent; the cost is write amplification and keeping the projection code correct.

5. Level 3

The write side publishes events (through an outbox so they're never lost), and a projector updates a separate store. Requirements:

  • Idempotent projections: events arrive at least once and sometimes out of order; store a per-aggregate version and ignore older events.
  • Rebuildability: you can replay events or re-project from the write database to rebuild the read store.
  • Lag monitoring: time between event and projection, exposed as a metric.

6. Eventual consistency in the UI

The classic bug: user submits, the page redirects to a list served by the read store, and the new item isn't there yet. Fixes: return the result from the command, read the user's own data from the primary, include a version and wait for the read model to reach it, or show a pending state.

7. CQRS, MediatR and event sourcing

  • MediatR dispatches requests to handlers in process. You can do CQRS with direct handler injection, minimal API endpoints, or any dispatcher. (MediatR's own licence changed in July 2025; see the Mediator question.)
  • Event sourcing stores events as the source of truth. It pairs naturally with CQRS because the event log feeds projections, but CQRS works with a state-based write model.

8. When it's overkill

  • Reads and writes have the same shape (admin CRUD).
  • One team, low traffic, simple rules.
  • The team can't yet operate async projections (monitoring, replay, dead letters).

Try it yourself

  1. Split an OrdersController into command and query handlers; give the query side AsNoTracking projections and compare SQL.
  2. Add a denormalised OrderSummaries table updated in the same transaction; prove it stays consistent when the save fails.
  3. Feed a read model from events with a BackgroundService; make the projector idempotent with a version column and replay the same events twice.
  4. Measure projection lag with a custom metric (System.Diagnostics.Metrics) and view it with dotnet-counters.
  5. Reproduce the "redirect shows stale list" bug, then fix it by returning the new state from the command.

💻 Code

Level 1 CQRS (separate command and query handlers on one database), plus a level 3 idempotent projection.

namespace Shop.Orders.Commands;

using Shop.Infrastructure;

public sealed record SubmitOrder(Guid OrderId);
public sealed record SubmitOrderResult(Guid OrderId, string Status, int Version);

// Write side: aggregate + invariants + one commit; returns the new state so the UI needn't re-query a lagging read model
public sealed class SubmitOrderHandler(IOrderRepository orders, IUnitOfWork unitOfWork)
{
    public async Task<SubmitOrderResult> HandleAsync(SubmitOrder command, CancellationToken ct)
    {
        var order = await orders.GetAsync(command.OrderId, ct) ?? throw new KeyNotFoundException();
        order.Submit();                                   // raises OrderSubmitted, written to the outbox on save
        await unitOfWork.SaveChangesAsync(ct);
        return new SubmitOrderResult(order.Id, order.Status.ToString(), order.Version);
    }
}
namespace Shop.Orders.Queries;

using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;

public sealed record OrderSummaryDto(Guid Id, string CustomerName, string Status, decimal Total);

// Read side: no aggregate, no tracking, only the columns this screen needs
public sealed class GetOrderSummariesHandler(ShopDbContext db)
{
    public Task<List<OrderSummaryDto>> HandleAsync(Guid customerId, CancellationToken ct) =>
        db.Orders
          .AsNoTracking()
          .Where(o => o.CustomerId == customerId)
          .OrderByDescending(o => o.CreatedAt)
          .Select(o => new OrderSummaryDto(o.Id, o.Customer.Name, o.Status.ToString(), o.Lines.Sum(l => l.Quantity * l.UnitPrice)))
          .Take(50)
          .ToListAsync(ct);
}
namespace Shop.ReadModel;

using Microsoft.EntityFrameworkCore;

public sealed record OrderStatusChanged(Guid OrderId, string Status, int Version, DateTimeOffset OccurredAt);

public sealed class OrderView
{
    public Guid OrderId { get; set; }
    public string Status { get; set; } = "";
    public int Version { get; set; }               // last applied event version: makes the projection idempotent
    public DateTimeOffset UpdatedAt { get; set; }
}

// Level 3: events arrive at least once and possibly out of order, so ignore anything not newer
public sealed class OrderViewProjector(ReadModelDbContext db)
{
    public async Task ApplyAsync(OrderStatusChanged e, CancellationToken ct)
    {
        var view = await db.OrderViews.SingleOrDefaultAsync(v => v.OrderId == e.OrderId, ct);
        if (view is null)
        {
            db.OrderViews.Add(new OrderView { OrderId = e.OrderId, Status = e.Status, Version = e.Version, UpdatedAt = e.OccurredAt });
        }
        else if (e.Version > view.Version)
        {
            view.Status = e.Status;
            view.Version = e.Version;
            view.UpdatedAt = e.OccurredAt;
        }
        else
        {
            return;                                   // duplicate or stale event: nothing to do
        }
        await db.SaveChangesAsync(ct);
    }
}

public sealed class ReadModelDbContext(DbContextOptions<ReadModelDbContext> options) : DbContext(options)
{
    public DbSet<OrderView> OrderViews => Set<OrderView>();
    protected override void OnModelCreating(ModelBuilder b) => b.Entity<OrderView>().HasKey(v => v.OrderId);
}

⚠ Common mistakes

  • Mistake: Jumping straight to a separate read database and event-driven projections. Why it is wrong: It adds eventual consistency, replay and monitoring work before there's a need. Instead: Start with separate handlers on one database and move up only when reads and writes diverge.
  • Mistake: Equating CQRS with MediatR. Why it is wrong: MediatR is an in-process dispatcher; you can use it without CQRS, or do CQRS without it. Instead: Describe CQRS as separate models, and choose dispatch separately.
  • Mistake: Assuming CQRS requires event sourcing. Why it is wrong: A state-based write model with projections works fine. Instead: Treat event sourcing as a separate decision for audit or history needs.
  • Mistake: Redirecting to a list served by an eventually consistent read model after a command. Why it is wrong: Users don't see their own change and resubmit. Instead: Return the new state from the command, or read the user's own data from the primary.
  • Mistake: Non-idempotent projections. Why it is wrong: At-least-once delivery and reordering corrupt the read model. Instead: Track a version per aggregate and ignore older or duplicate events.
  • Mistake: Loading aggregates for queries. Why it is wrong: It over-fetches and tracks entities just to map them. Instead: Project directly on the read side.
  • Mistake: Applying full CQRS ceremony to CRUD screens. Why it is wrong: Five files per field edit slows delivery with no benefit. Instead: Use simple endpoints for CRUD areas and CQRS where the domain needs it.

🏛 Senior insight: trade-offs

CQRS is a spectrum, and most of its value comes from the cheapest step: stop pushing reads through aggregates. I move to a separate store only for a concrete reason (search, a read/write ratio in the hundreds, a different query engine), and when I do, I budget for the operational work: outbox, idempotent projections, replay, lag metrics and UI handling of stale reads.

Option When it fits Cost When not to
One model CRUD, simple rules None Read and write shapes diverge
Level 1 handlers Most services Minimal Never really wrong
Level 2 read tables Hot reads with expensive joins Write amplification Writes dominate
Level 3 separate store Search, massive read scale Eventual consistency, ops Team can't run async projections
+ Event sourcing Full history/audit is a requirement Highest complexity Ordinary business CRUD

I measure read p95, database CPU split between reads and writes, and projection lag (alert threshold agreed with the product owner) before and after each step.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes commands handled by command handlers Why: Checks the Command pattern behind the write side
    How to answer

    Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.

    • GoF style: the command has Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.
    • Modern style: an immutable record (PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.

    A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.

    The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.

  2. When: Candidate mentions MediatR in a CQRS design Why: Checks MediatR as a dispatcher, its licence, and alternatives
    How to answer

    The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).

    MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.

    It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.

    Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.

    Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.

  3. When: Candidate says queries bypass aggregates and repositories Why: Checks repositories on the write side vs projections on the read side
    How to answer

    I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.

    • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
    • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
    • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
    • EF Core 10 ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.

    My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.

  4. When: Candidate says level 3 read models are updated from events Why: Checks how events reliably reach a separate read model
    How to answer

    The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.

    The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.

    A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.

🛠 Real-world problems: how you handle them

A stuck projection showed customers stale order statuses
Situation
Order tracking at [company]: writes to Azure SQL, order status read model in [Cosmos DB] updated by a projector consuming Service Bus events. About [50,000] orders a day; customers check status in the mobile app.
Signals
Spike in support calls saying 'my order still shows Processing' after shipping emails went out; Application Insights showed the projector's processed-message rate dropping to zero; Service Bus subscription active message count climbing to [40,000]; no alert fired because none existed for lag.
Investigation
Service Bus metrics showed one message being redelivered until it hit the max delivery count; the dead-letter queue held a message with a schema change the projector couldn't deserialise. Before it dead-lettered, it blocked a session ([sessions per order id]), stalling later events. Application Insights exceptions confirmed a `JsonException` on a renamed field.
Resolution
Immediate: deployed a projector fix that handled both field names, resubmitted the dead-lettered messages, and let the backlog drain in [15] minutes. Real fix: versioned event contracts with tolerant readers, a projection-lag metric (now - event OccurredAt) with an alert at [60 s], and the command API returning the new status so the app no longer depended on the read model straight after an action.
Prevention
Contract tests for event schemas in CI; alert on dead-letter count > 0 and on projection lag; a runbook for replaying events into the read model; an ADR recording which screens may read eventually consistent data.

How to tell it (STAR)

**S:** At [company], our order-tracking read model was fed by events, and one day customers saw 'Processing' for orders that had already shipped. **T:** I was on call and needed to restore correct statuses and stop it happening silently again. **A:** Service Bus metrics showed a growing backlog and a dead-lettered event with a renamed field that our projector couldn't read. I shipped a tolerant-reader fix, resubmitted the dead letters, then added a projection-lag metric with an alert, contract tests for event schemas, and changed the command API to return the new status. **R:** The backlog of [40,000] cleared in [15] minutes, lag alerts have since caught [two] issues before customers noticed, and stale-status support calls dropped to [near zero].

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me