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.
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.
"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
Orderaggregate withSubmit()andCancel(), loaded whole, changed through its methods, saved through the unit of work. The read model is about answering a screen's question fast: anOrderSummaryDtowith 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
Selectprojections 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."
| 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 |
| 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 |
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.
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
Red flags
Stack.Pop() breaks it on purpose. 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)
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.
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.
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.
The write side publishes events (through an outbox so they're never lost), and a projector updates a separate store. Requirements:
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.
OrdersController into command and query handlers; give the query side AsNoTracking projections and compare SQL.OrderSummaries table updated in the same transaction; prove it stays consistent when the save fails.BackgroundService; make the projector idempotent with a version column and replay the same events twice.System.Diagnostics.Metrics) and view it with dotnet-counters.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);
}
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.
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.
Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.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.
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.
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.
DbContext with Select and AsNoTracking. Never return IQueryable from a repository.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.
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.
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].
Last updated 18 Nov 2026.