TL;DR
CQRS separates the model that changes state (commands) from the model that reads it (queries). The trade you're making: you give up a single, symmetric model of your domain in exchange for the freedom to shape each side around what it's actually for — transactional correctness on the write side, fast denormalized shapes on the read side.
The core rule, stated the way Bertrand Meyer stated its ancestor, Command-Query Separation: a method should either change state or return data, never both. CQRS takes that method-level discipline and lifts it to the level of whole models. A Command mutates state and returns nothing meaningful; a Query returns data and touches nothing. Once you take that seriously, you stop pretending one Order class needs to simultaneously enforce invariants on write and paginate efficiently on read — you build two.
The trade-off, named plainly: you get independently scalable, independently modeled read and write paths, at the cost of two things to keep in sync (whether synchronously in one transaction or asynchronously with eventual consistency), and genuinely more moving parts than a single CRUD model. CQRS is worth adopting for the write-heavy, invariant-rich, high-read-fan-out slice of a system — not for the system as a whole. Applied everywhere by default, it's the single most common way teams overengineer a boring CRUD app.
Origins and the Problem It Solves
CQRS traces its lineage through a single, narrow line of thinking about method purity, applied at increasing scope over two decades.
| Year | Milestone | What it contributed |
|---|---|---|
| 1988 | Bertrand Meyer, Object-Oriented Software Construction | Command-Query Separation (CQS): a method is either a command (side effect, no return) or a query (return value, no side effect) — never both, at the method level. |
| ~2005–2009 | Greg Young, DDD/CQRS community talks | Lifted CQS from methods to whole object models: separate objects, later separate models, for the write and read sides of a bounded context. |
| 2010 | Greg Young formalizes "CQRS" | Names the pattern, ties it to task-based UIs and DDD aggregates, explicitly pairs it (optionally) with Event Sourcing. |
| 2011 | Martin Fowler's CQRS bliki entry | Describes CQRS as using a different model to update information than the model used to read information, while cautioning that for most systems it adds risky complexity. |
| 2012 | Microsoft patterns & practices "CQRS Journey" | First major vendor-backed deep-dive, explicit "when to use / when to avoid" guidance for enterprise .NET teams. |
Greg Young introduced CQRS in 2010 as a way to separate the responsibility of handling write operations from handling read operations in a system, and developed it around the same time that event sourcing was emerging as a related idea. Crucially, Young was explicit that he used the same definition of commands and queries that Meyer had used, keeping the same insistence on purity — the difference is that CQRS splits the responsibility across two objects instead of enforcing purity within one.
The pathology it responded to
The target was the single, symmetric domain model doing double duty: an Order aggregate that has to enforce business invariants on every write (can't ship an order with no line items, can't apply a discount past its expiry) while also being reshaped, joined, and paginated for every read screen a UI designer dreams up. As read requirements diverge — dashboards, search, exports, mobile summaries — the "one true model" either grows god-object joins and projection logic bolted onto the domain, or the domain gets watered down until it can't protect its own invariants. CQRS's fix: stop asking one model to do both jobs.
Bertrand Meyer, 1988
method-level purity"] --> B["DDD aggregate + read model split
Greg Young, mid-2000s"] B --> C["CQRS named
Greg Young, 2010"] C --> D["Popularized + cautioned
Martin Fowler, 2011"] C --> E["Optionally paired with
Event Sourcing"] classDef milestone fill:#F1EEFD,stroke:#6D28D9,color:#16142A; class A,B,C,D,E milestone;
Core Tenets
Four non-negotiables define membership in this pattern — deviate from any one and you have something else (usually plain layered CRUD with extra ceremony).
- Purity of intent. A command changes state and returns, at most, an acknowledgment/ID — never domain data. A query returns data and must never have a side effect. Mixing the two anywhere is a CQS violation, and CQRS inherits it wholesale.
- Separate models, not just separate methods. The write side models invariants and behavior (an aggregate). The read side models shape — whatever a specific screen, report, or API consumer needs, denormalized as far as is useful. They do not have to share a class, a schema, or even a database engine.
- Commands are imperative and task-based, not CRUD-shaped.
CancelOrder, notUpdateOrder(orderId, { status: "cancelled" }). The command names the business intent; this is what makes CQRS compose naturally with DDD. - The read side is allowed to lag. Not required to — synchronous, same-transaction read model updates are valid CQRS — but the pattern must tolerate eventual consistency if you choose it, because that's what unlocks independent scaling of the two sides.
Greg Young himself pushes back on treating CQRS as a top-level architecture: you should not use CQRS as part of your top-level architecture — implement it only in those bounded contexts where it brings clear benefit. That's tenet zero, really: CQRS is a per-bounded-context decision, not a system-wide default.
The Components, In Detail
CQRS is better described in terms of the two sides and the seam between them than in terms of "layers" — there's no dependency-inversion ring here, just a fork.
4.1 The Command Side
- Command objects — immutable data carrying user intent (
PlaceOrder,CancelOrder). Never a query, never returns domain state. - Command handlers — one per command, load the aggregate, invoke behavior, persist. No branching business logic lives in the handler itself; that belongs on the aggregate.
- Aggregates / domain model — the sole place invariants are enforced. If you find yourself validating business rules in a handler, controller, or (worse) the read model, that's the defining test for "in the wrong place."
- Write store — normalized, transactional, optimized for consistency, not for query flexibility.
4.2 The Query Side
- Query objects — a request for a specific shape of data (
GetOrderSummary,ListOverdueInvoices). No side effects, ever — the defining test for whether something belongs here is: "could I run this twice with no consequence?" - Query handlers — thin, typically a direct mapping to a read-optimized query (SQL view, Dapper query, cached projection) with no domain logic.
- Read models / projections — denormalized, per-use-case shapes. Never enforce invariants; that's not their job, and putting validation here is a common anti-pattern (§14).
- Read store — can be the same database as the write store (a view, a second schema, a read replica) or a wholly separate one (Elasticsearch for search, Redis for hot paths).
The Central Mechanic: The Fork
Every architecture has one structural trick that makes it work. For Onion it's dependency inversion. For CQRS, it's the fork at the boundary: every inbound request is classified, once, as either an intent-to-change (command) or a request-for-information (query), and from that single classification point the two paths never merge again until (optionally) they resync through a projection.
This is subtler than "two folders." The fork has to happen at a place that cannot be bypassed — usually the application/API boundary, via distinct message types or distinct HTTP verbs mapped to distinct handler pipelines — because the entire value of CQRS evaporates the moment a "query" handler is allowed to sneak in a write, or a "command" handler is allowed to return rich query-shaped data as a convenience. The discipline is enforced at the fork, not policed later.
→ aggregate → write store"] Fork -->|"Request for information"| QryPath["Query pipeline
→ projection → read store"] classDef fork fill:#F1EEFD,stroke:#6D28D9,color:#16142A; class Fork fork;
In .NET, the fork is typically enforced by convention plus the type system: commands and queries are distinct marker interfaces (ICommand/ICommand<TResult> vs. IQuery<TResult>), routed through a dispatcher whose pipeline behaviors differ per kind — commands get validation + transaction + domain-event dispatch; queries get caching + read-store routing and nothing that writes.
Full Solution Structure and Wiring
Given MediatR's move toward commercial licensing for some usage, this reference uses Wolverine (MIT-licensed, part of the "Critter Stack") for command/query dispatch, since it gives .NET teams a single consistent abstraction for both in-process and cross-process messaging and is the option most actively recommended as a drop-in replacement as of 2026. If your team is already committed to MediatR under its current terms, or prefers Brighter, the shapes below translate directly — only the dispatcher registration changes.
Ordering.sln
├── src/
│ ├── Ordering.Domain/ # aggregates, value objects, domain events
│ │ └── Orders/Order.cs
│ ├── Ordering.Application/ # commands, queries, handlers, validators
│ │ ├── Commands/PlaceOrder/
│ │ └── Queries/GetOrderSummary/
│ ├── Ordering.Infrastructure/ # EF Core write store, Dapper read store
│ │ ├── Write/OrderingDbContext.cs
│ │ └── Read/OrderReadDbConnectionFactory.cs
│ └── Ordering.Api/ # minimal API endpoints, composition root
│ └── Program.cs
└── tests/
├── Ordering.Domain.Tests/
└── Ordering.Application.Tests/
Project-reference matrix
| Project | References | Referenced by |
|---|---|---|
Domain | — | Application, Infrastructure, Tests |
Application | Domain | Infrastructure, Api, Tests |
Infrastructure | Domain, Application | Api |
Api | Application, Infrastructure | — |
// Ordering.Api/Program.cs — composition root
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseWolverine(opts =>
{
opts.Discovery.IncludeAssembly(typeof(PlaceOrderHandler).Assembly);
opts.Policies.AutoApplyTransactions();
opts.Policies.OnAnyException().RetryWithCooldown(
250.Milliseconds(), 500.Milliseconds(), 1.Seconds());
});
builder.Services.AddDbContext<OrderingDbContext>(o =>
o.UseNpgsql(builder.Configuration.GetConnectionString("Write")));
builder.Services.AddScoped<IOrderReadStore, DapperOrderReadStore>();
var app = builder.Build();
app.MapPost("/orders", async (PlaceOrder cmd, IMessageBus bus) =>
{
var orderId = await bus.InvokeAsync<Guid>(cmd);
return Results.Created($"/orders/{orderId}", new { orderId });
});
app.MapGet("/orders/{id:guid}/summary", async (Guid id, IOrderReadStore reads) =>
await reads.GetSummaryAsync(id) is { } summary
? Results.Ok(summary)
: Results.NotFound());
app.Run();
A Complete Worked Example
The running domain: a small order-placement system — a customer places an order with line items, the order is validated against stock and a discount policy, and confirmed orders appear on a read-optimized order summary screen.
Write side: the aggregate
// Domain/Orders/Order.cs
public sealed class Order
{
private readonly List<OrderLine> _lines = [];
public Guid Id { get; private init; }
public Guid CustomerId { get; private init; }
public OrderStatus Status { get; private set; } = OrderStatus.Draft;
public IReadOnlyList<OrderLine> Lines => _lines;
public IReadOnlyList<IDomainEvent> Events => _events;
private readonly List<IDomainEvent> _events = [];
public static Order Start(Guid customerId) =>
new() { Id = Guid.NewGuid(), CustomerId = customerId };
public void AddLine(Sku sku, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify a submitted order.");
if (quantity <= 0)
throw new DomainException("Quantity must be positive.");
_lines.Add(new OrderLine(sku, quantity, unitPrice));
}
public void Submit()
{
if (_lines.Count == 0)
throw new DomainException("Cannot submit an order with no lines.");
Status = OrderStatus.Submitted;
_events.Add(new OrderSubmitted(Id, CustomerId, Total()));
}
public Money Total() => _lines.Aggregate(Money.Zero,
(sum, l) => sum + l.UnitPrice * l.Quantity);
}
Write side: command and handler
// Application/Commands/PlaceOrder/PlaceOrder.cs
public sealed record PlaceOrder(
Guid CustomerId,
IReadOnlyList<PlaceOrderLine> Lines);
public sealed record PlaceOrderLine(string Sku, int Quantity, decimal UnitPrice);
public sealed class PlaceOrderHandler(OrderingDbContext db, IStockChecker stock)
{
public async Task<Guid> Handle(PlaceOrder cmd, CancellationToken ct)
{
var order = Order.Start(cmd.CustomerId);
foreach (var line in cmd.Lines)
{
await stock.EnsureAvailableAsync(line.Sku, line.Quantity, ct);
order.AddLine(new Sku(line.Sku), line.Quantity, new Money(line.UnitPrice));
}
order.Submit();
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return order.Id;
}
}
Read side: query and handler
// Application/Queries/GetOrderSummary/OrderSummary.cs
public sealed record OrderSummary(
Guid OrderId, string CustomerName, string Status,
decimal Total, int LineCount, DateTimeOffset SubmittedAt);
public interface IOrderReadStore
{
Task<OrderSummary?> GetSummaryAsync(Guid orderId, CancellationToken ct = default);
}
// Infrastructure/Read/DapperOrderReadStore.cs
public sealed class DapperOrderReadStore(NpgsqlDataSource dataSource) : IOrderReadStore
{
public async Task<OrderSummary?> GetSummaryAsync(Guid orderId, CancellationToken ct)
{
await using var conn = await dataSource.OpenConnectionAsync(ct);
return await conn.QuerySingleOrDefaultAsync<OrderSummary>(
"""
SELECT o.order_id AS OrderId, c.name AS CustomerName,
o.status AS Status, o.total AS Total,
o.line_count AS LineCount, o.submitted_at AS SubmittedAt
FROM order_summary_view o
JOIN customers c ON c.customer_id = o.customer_id
WHERE o.order_id = @orderId
""", new { orderId });
}
}
Note the asymmetry, deliberately: the write side works through a rich aggregate with a normalized EF Core model; the read side goes straight to Dapper against a denormalized view. Neither side knows the other's internal shape — they agree only on the projection contract.
Runtime Flows
8.1 Happy path — command then query
8.2 Failure path — command rejected by invariant
8.3 The structurally interesting path — read-your-own-write race
This is CQRS's own sharp edge, and it's the path every other pattern's runtime-flow section doesn't need: a client submits a command, then immediately queries, before the projection has caught up.
Handled correctly with one of: returning the write-side state directly from the command response (skip the read model for the immediate confirmation UI), a client-side optimistic update, or a version token the client polls/waits on. Handled incorrectly, it becomes a support ticket that "the order didn't save," when it did.
Change-Impact Analysis
CQRS's signature question is: what happens when a command's shape changes? Because commands are contracts between the API surface, the handler, and (if you're event-sourcing or projecting asynchronously) every downstream projector, a shape change ripples further than it would in a single CRUD model.
Taxonomy of change types
| Change type | Example | Blast radius |
|---|---|---|
| Additive command field | Add optional PromoCode to PlaceOrder | Low — old callers still valid |
| Required field added | Make ShippingAddress mandatory | Medium — every caller must be updated in lockstep |
| Command split/renamed | UpdateOrder → CancelOrder + AmendOrder | High — callers must pick the correct new intent |
| Invariant tightened | Orders now require ≥1 line at submit, not at add | Medium — silently changes when errors surface |
| Read projection schema change | order_summary_view adds a denormalized column | Low if additive, high if it changes the rebuild strategy |
| Consistency model change | Sync same-transaction read model → async projector | Very high — every reader must now tolerate staleness |
Walkthrough 1 — additive field (safe)
(no PromoCode)"] --> H["PlaceOrderHandler"] New["New callers
(with PromoCode)"] --> H H --> Agg["Order aggregate
PromoCode defaults to null"] classDef ok fill:#E7F6EF,stroke:#047857,color:#16142A; class Old,New,H,Agg ok;
Walkthrough 2 — command split (breaking, coordinated)
Walkthrough 3 — the dangerous one: validating on transition, not on write
The Onion doc's sharp edge was "validate on transition, not rehydration." CQRS's equivalent trap is subtler and more common: validating a command against the read model instead of the write model's current, authoritative state. It's tempting — the read model is right there, already denormalized, already fast to query — but if it's even slightly stale, you validate against yesterday's truth.
// ❌ WRONG — validating a command against the (possibly stale) read model
public async Task Handle(CancelOrder cmd, CancellationToken ct)
{
var summary = await _readStore.GetSummaryAsync(cmd.OrderId, ct);
if (summary is { Status: "Shipped" })
throw new DomainException("Cannot cancel a shipped order.");
// If the projector hasn't caught up with a just-recorded "Shipped"
// event yet, this check passes and we cancel an order that has,
// on the write side, already shipped.
await _bus.PublishAsync(new OrderCancelled(cmd.OrderId));
}
// ✅ RIGHT — validate against the write-side aggregate, the sole
// source of truth for invariants (§4.1's "defining test").
public async Task Handle(CancelOrder cmd, CancellationToken ct)
{
var order = await _db.Orders.FindAsync([cmd.OrderId], ct)
?? throw new NotFoundException(cmd.OrderId);
order.Cancel(); // throws DomainException internally if already shipped
await _db.SaveChangesAsync(ct);
}
invariant silently violated
Consistency Models
This section exists because CQRS lives or dies on a decision the base template has no dedicated slot for: how far apart are the write and read sides allowed to drift, and for how long? Contrary to popular belief, Greg Young never said CQRS requires two databases or eventual consistency — you can implement it with a single table, updating the read model synchronously in the same transaction as the write. The spectrum below is a real design choice, not a fixed property of the pattern.
| Model | How it works | Read-your-writes? | Cost |
|---|---|---|---|
| Same-transaction sync | Read model updated in the same DB transaction as the write | Always | No independent read scaling; write-path latency increases |
| Synchronous projection, separate store | Command handler pushes to the read store before returning | Always (adds latency) | Command latency includes projection cost |
| Async, near-real-time | Domain event → message bus → projector, typically <1s | No — brief window | Best scaling; needs UX/idempotency handling for the gap |
| Async, batch/periodic | Scheduled rebuild, minutes to hours | No | Cheapest infra; unsuitable for anything the user expects to see reflected quickly |
sync"] --> B["Sync projection
separate store"] --> C["Async
near-real-time"] --> D["Async
batch"] classDef strict fill:#EAF0FE,stroke:#1D4ED8,color:#16142A; classDef loose fill:#FDF3E4,stroke:#B45309,color:#16142A; class A,B strict; class C,D loose;
Practical guidance: default to same-transaction sync unless you have a measured reason not to — it's the version Fowler's caution about "risky complexity" applies least to, since you never actually leave ACID. Move to async only for the specific read paths where fan-out (search, dashboards, analytics) genuinely needs a different store or shape than the write side can serve.
Testing Strategy Per Component
API → command → projection → query"] --> Int["Integration
handler + real DB (Testcontainers)"] Int --> Unit["Unit
aggregate invariants, pure"] classDef top fill:#FCEAEA,stroke:#B91C1C,color:#16142A; classDef mid fill:#FDF3E4,stroke:#B45309,color:#16142A; classDef base fill:#E7F6EF,stroke:#047857,color:#16142A; class E2E top; class Int mid; class Unit base;
Unit tests — the aggregate (innermost layer)
// Ordering.Domain.Tests/OrderTests.cs
public class OrderTests
{
[Fact]
public void Submit_WithNoLines_ThrowsDomainException()
{
var order = Order.Start(Guid.NewGuid());
var act = () => order.Submit();
act.Should().Throw<DomainException>()
.WithMessage("*no lines*");
}
[Fact]
public void AddLine_AfterSubmit_ThrowsDomainException()
{
var order = Order.Start(Guid.NewGuid());
order.AddLine(new Sku("SKU-1"), 1, new Money(10m));
order.Submit();
var act = () => order.AddLine(new Sku("SKU-2"), 1, new Money(5m));
act.Should().Throw<DomainException>();
}
}
Integration tests — the command handler against a real database
// Ordering.Application.Tests/PlaceOrderHandlerTests.cs
public class PlaceOrderHandlerTests : IAsyncLifetime
{
private readonly PostgreSqlContainer _pg =
new PostgreSqlBuilder().WithImage("postgres:17-alpine").Build();
public Task InitializeAsync() => _pg.StartAsync();
public Task DisposeAsync() => _pg.DisposeAsync().AsTask();
[Fact]
public async Task Handle_ValidOrder_PersistsAndReturnsId()
{
await using var db = CreateContext(_pg.GetConnectionString());
var handler = new PlaceOrderHandler(db, new AlwaysAvailableStockChecker());
var id = await handler.Handle(new PlaceOrder(
Guid.NewGuid(), [new PlaceOrderLine("SKU-1", 2, 9.99m)]),
CancellationToken.None);
var saved = await db.Orders.FindAsync(id);
saved.Should().NotBeNull();
saved!.Status.Should().Be(OrderStatus.Submitted);
}
}
When To Use It — And When Not To
need genuinely different
models/shapes?"} -->|No| CRUD["Use plain CRUD"] Q1 -->|Yes| Q2{"Is this a core,
invariant-rich subdomain?"} Q2 -->|No, generic/supporting| Simple["Use simplest tool
(Active Record / Transaction Script)"] Q2 -->|Yes, core domain| Q3{"Read:write ratio
heavily skewed,
or divergent read shapes?"} Q3 -->|No| Light["Light CQRS:
same-transaction sync"] Q3 -->|Yes| Q4{"Can the UI/consumers
tolerate brief staleness?"} Q4 -->|Yes| Full["Full CQRS:
async projection"] Q4 -->|No| Light classDef go fill:#E7F6EF,stroke:#047857,color:#16142A; classDef stop fill:#FCEAEA,stroke:#B91C1C,color:#16142A; class CRUD,Simple stop; class Light,Full go;
Use it when
- The write side enforces real invariants (order fulfillment, financial postings, inventory) that would get diluted by also serving reads.
- Read traffic is an order of magnitude larger than write traffic, or read shapes genuinely diverge (dashboard vs. detail vs. export).
- You're already doing Event Sourcing — the read side is nearly free at that point, since you're building projections anyway.
- Different teams or services legitimately own the write and read paths and need an explicit contract between them.
Don't use it when
- It's a CRUD-shaped subdomain (settings, reference data, most admin screens) — the "two databases and eventual consistency" ceremony (per §13's "overkill for 90%" critique) buys nothing there.
- Your team can't yet reason correctly about eventual consistency in production — the read-your-own-write race (§8.3) will produce real incidents before it produces real value.
- The whole system is being reached for as a top-level architecture, rather than applied per bounded context — this is the mistake Greg Young himself has repeatedly warned against.
Pros and Cons, Honestly
| Pros | Cons |
|---|---|
| Independent scaling of read and write paths | Two models (at minimum) to build, evolve, and keep mentally in sync |
| Read models can be denormalized freely without corrupting domain integrity | Eventual consistency, if chosen, is a real UX and support-desk concern, not just a technical footnote |
| Commands map naturally to task-based UX and DDD ubiquitous language | More infrastructure: projectors, possibly a second store, possibly a message bus |
| Read side is disposable and rebuildable — safe to experiment with shapes | Debugging spans two models; a bug can live in the write model, the projector, or the read model |
| Composes cleanly with Event Sourcing when audit/temporal queries matter | Onboarding cost — engineers have to unlearn "just query the entity," which is the majority instinct |
A genuinely contested trade-off
Is "CQRS with a single database and no eventual consistency" still CQRS, or is it just well-organized CRUD with extra ceremony? One camp argues the two-databases-and-eventual-consistency picture that dominates blog posts is semantic diffusion — Greg Young never required it, and the original idea (separate commands and queries) is simple and useful on its own. The other camp — including practitioners pushing back on "CQRS is just read replicas" — argues that if you're not also separating storage and accepting some staleness, you haven't actually unlocked the pattern's main practical benefit (independent scaling), and you've just added indirection for its own sake. Reasonable engineers land on both sides; which one you land on should follow from whether your read and write paths actually need to scale independently, not from a purity argument either way.
Comparison vs Adjacent Architectures
CQRS's neighborhood: plain CRUD/layered (what it's reacting against), Event Sourcing (its frequent but optional companion), and Vertical Slice Architecture (a complementary organizational principle, not a competing structural one).
append-only)] ES --> R2["Projections
(rebuildable)"] end classDef c1 fill:#F6F5FC,stroke:#A29DBD,color:#16142A; classDef c2 fill:#F1EEFD,stroke:#6D28D9,color:#16142A; classDef c3 fill:#EEF0FE,stroke:#4F46E5,color:#16142A; class M1,D1 c1; class W1,DW1,R1,DR1 c2; class W2,ES,R2 c3;
| Dimension | Plain CRUD | CQRS | CQRS + Event Sourcing | Vertical Slice (VSA) |
|---|---|---|---|---|
| Origin / author / year | Implicit, pre-dates naming | Greg Young, 2010 | Young / event-sourcing community, ~2010 | Jimmy Bogard, ~2016 |
| Primary organizing axis | Entity / table | Command vs. query responsibility | Sequence of events as source of truth | Feature / use case |
| Dependency direction | UI → service → data, one path | Two independent paths from a shared boundary | Write appends events; reads derive from them | Orthogonal — organizes files, not data flow |
| Best-fit scenario | Simple, symmetric read/write needs | Invariant-rich core domain, divergent read shapes | Auditability, temporal queries, complex state history | Any of the above — pairs well with CQRS (§14.1) |
| Main failure mode | God-object model straining under divergent reads | Validating against a stale read model (§9) | Event schema evolution debt (§15) | Duplicated logic across slices if not disciplined |
14.1 CQRS and Vertical Slice Architecture aren't rivals
CQRS and Vertical Slice Architecture are commonly used together — CQRS provides the conceptual model of separate commands and queries, while VSA provides the organizational principle of grouping by feature rather than technical layer. The comparison table above lists VSA because people frequently ask "CQRS or VSA," but the honest answer is usually both: VSA decides where a PlaceOrder command's files live; CQRS decides that PlaceOrder and GetOrderSummary are different kinds of things in the first place.
Common Mistakes and Anti-Patterns
Mistake 1 — CRUD-shaped commands
// ❌ WRONG — a generic "update" command hides intent and invites a
// grab-bag of unrelated invariant checks in one handler.
public sealed record UpdateOrder(Guid OrderId, string? Status,
List<PlaceOrderLine>? Lines, Address? ShippingAddress);
// ✅ RIGHT — each command names one business intent; each handler
// enforces exactly the invariants relevant to that intent.
public sealed record CancelOrder(Guid OrderId, string Reason);
public sealed record AmendOrderLines(Guid OrderId, List<PlaceOrderLine> NewLines);
public sealed record ChangeShippingAddress(Guid OrderId, Address NewAddress);
Mistake 2 — enforcing invariants in the read/projection layer
// ❌ WRONG — the projector silently "fixes" bad data instead of the
// write side ever having rejected it. Now the read model and the
// write model disagree about what's true, permanently.
public async Task Handle(OrderSubmitted evt, CancellationToken ct)
{
var total = evt.Total < 0 ? 0 : evt.Total; // masking a write-side bug
await _readDb.UpsertOrderSummaryAsync(evt.OrderId, total, ct);
}
// ✅ RIGHT — projectors are dumb and faithful; invariants are the
// aggregate's job alone (§4.1's defining test).
public async Task Handle(OrderSubmitted evt, CancellationToken ct) =>
await _readDb.UpsertOrderSummaryAsync(evt.OrderId, evt.Total, ct);
Mistake 3 — one handler doing both a command and a query
// ❌ WRONG — "GetOrCreateCart" both reads and writes; callers can no
// longer treat it as side-effect-free, breaking the CQS tenet (§3.1).
public async Task<Cart> GetOrCreateCart(Guid customerId, CancellationToken ct)
{
var cart = await _db.Carts.FindAsync([customerId], ct);
if (cart is null)
{
cart = Cart.Create(customerId);
_db.Carts.Add(cart);
await _db.SaveChangesAsync(ct); // hidden write inside a "getter"
}
return cart;
}
// ✅ RIGHT — split back into a query and an explicit command.
public Task<Cart?> GetCart(Guid customerId, CancellationToken ct);
public Task<Guid> Handle(StartCart cmd, CancellationToken ct);
Adoption Path
service methods into
Command/Query intent"] --> S2["2. Split the model class
into a write model +
a read DTO, same DB"] S2 --> S3["3. Introduce a dispatcher
(Wolverine) for the
highest-value slice only"] S3 --> S4["4. Add a denormalized
read view for that
slice's hot queries"] S4 --> S5["5. Only if scaling demands it:
move to async projection
+ separate read store"] classDef step fill:#F1EEFD,stroke:#6D28D9,color:#16142A; class S1,S2,S3,S4,S5 step;
ADR template, scoped to CQRS
# ADR-NNN: Adopt CQRS for [bounded context]
## Status
Proposed | Accepted | Superseded
## Context
- What invariants does the write side need to protect that the current
model dilutes?
- What read shapes are actually diverging (list them)?
- What is the current read:write ratio, measured, not assumed?
## Decision
- Scope: [this bounded context only / these commands only]
- Consistency model chosen (§10): [same-transaction sync / async]
- Dispatcher: [Wolverine / Brighter / hand-rolled], reason:
## Consequences
- New failure modes the team must own (read-your-own-write race, §8.3)
- Rollback plan if this doesn't pay off in [N] months
- Who owns the read-model rebuild story when its schema changes
Reference Checklist
- Every command changes state and returns nothing domain-shaped (§3.1)
- Every query is provably side-effect-free — could run it twice safely (§4.2)
- Invariants live only on the write-side aggregate, never in a projector or read handler (§15.2)
- Commands are named for business intent, not CRUD verbs (§15.1)
- The consistency model (§10) was chosen deliberately and is written down in an ADR (§16)
- Any command that validates against the read model has been re-checked against §9's sharp edge
- CQRS is scoped to a specific bounded context, not applied as the whole system's top-level architecture (§3, §12)
- Read-your-own-write UX has an explicit answer, not an assumption (§8.3)
Sources
Primary
- Martin Fowler, "CQRS" — bliki
- Jeremy D. Miller, JasperFx's plans for Marten & Wolverine
Analysis and comparison
- Vertical Slices, CQRS, and Semantic Diffusion — Architecture Weekly
- Tackling Complexity in CQRS — dev.to
- Read Replicas Are NOT CQRS — CodeOpinion
- CQRS Is Overkill For 90% Of Backends — The Atomic Architect