C CQRS — Complete Reference
/
ARCHITECTURE REFERENCE · C# / .NET 10

One model to write, another to read

CQRS splits a system's write side from its read side into separate models, each optimized for what it actually does. It is not microservices, not event sourcing, and not two databases — it's a narrower, sharper idea that gets bigger every time someone reinvents it as an "architecture."

18 sections 22 diagrams 27 code samples ~35 min read
INTENT DB COMMAND VIEW QUERY
scroll to explore
1

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.

2

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.

YearMilestoneWhat it contributed
1988Bertrand Meyer, Object-Oriented Software ConstructionCommand-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–2009Greg Young, DDD/CQRS community talksLifted CQS from methods to whole object models: separate objects, later separate models, for the write and read sides of a bounded context.
2010Greg Young formalizes "CQRS"Names the pattern, ties it to task-based UIs and DDD aggregates, explicitly pairs it (optionally) with Event Sourcing.
2011Martin Fowler's CQRS bliki entryDescribes 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.
2012Microsoft 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.

Lineage — from CQS to CQRS
flowchart LR A["Command-Query Separation
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;
3

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).

  1. 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.
  2. 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.
  3. Commands are imperative and task-based, not CRUD-shaped. CancelOrder, not UpdateOrder(orderId, { status: "cancelled" }). The command names the business intent; this is what makes CQRS compose naturally with DDD.
  4. 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.

4

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).
Component map — command side vs. query side
flowchart TB subgraph CMD["Command Side"] C1[Command object] --> C2[Command handler] C2 --> C3[Aggregate / domain model] C3 --> C4[(Write store)] end subgraph QRY["Query Side"] Q1[Query object] --> Q2[Query handler] Q2 --> Q3[(Read store / projection)] end C4 -. sync or async projection .-> Q3 classDef cmd fill:#F1EEFD,stroke:#6D28D9,color:#16142A; classDef qry fill:#EEF0FE,stroke:#4F46E5,color:#16142A; class C1,C2,C3,C4 cmd; class Q1,Q2,Q3 qry;
5

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.

The fork — classification at the boundary
flowchart LR In["Inbound request"] --> Fork{"Command or Query?"} Fork -->|"Intent to change state"| CmdPath["Command pipeline
→ 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.

6

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.

Text
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

ProjectReferencesReferenced by
Domain—Application, Infrastructure, Tests
ApplicationDomainInfrastructure, Api, Tests
InfrastructureDomain, ApplicationApi
ApiApplication, Infrastructure—
C#
// 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();
7

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

C#
// 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

C#
// 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

C#
// 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.

8

Runtime Flows

8.1 Happy path — command then query

Happy path — PlaceOrder → projection → GetOrderSummary
sequenceDiagram participant UI participant API participant CmdH as PlaceOrderHandler participant Agg as Order (aggregate) participant WDB as Write store participant Proj as Projector participant RDB as Read store UI->>API: POST /orders API->>CmdH: PlaceOrder CmdH->>Agg: AddLine, Submit Agg-->>CmdH: OrderSubmitted event CmdH->>WDB: SaveChanges WDB-->>Proj: OrderSubmitted Proj->>RDB: upsert order_summary_view UI->>API: GET /orders/{id}/summary API->>RDB: query RDB-->>UI: OrderSummary

8.2 Failure path — command rejected by invariant

Failure path — invariant violation rolls back the command
sequenceDiagram participant UI participant API participant CmdH as PlaceOrderHandler participant Agg as Order (aggregate) participant WDB as Write store UI->>API: POST /orders (empty lines) API->>CmdH: PlaceOrder CmdH->>Agg: Submit Agg-->>CmdH: throws DomainException CmdH-->>API: 422 Unprocessable API-->>UI: validation error Note over WDB: no write occurs — read model never touched

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.

Read-your-own-write race under eventual consistency
sequenceDiagram participant UI participant CmdH as PlaceOrderHandler participant WDB as Write store participant Proj as Projector (async) participant RDB as Read store UI->>CmdH: PlaceOrder CmdH->>WDB: SaveChanges (committed) CmdH-->>UI: 201 Created {orderId} par immediately UI->>RDB: GET summary (too soon) RDB-->>UI: 404 — projection not yet applied and asynchronously WDB-->>Proj: OrderSubmitted event Proj->>RDB: upsert view (arrives late) end

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.

9

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 typeExampleBlast radius
Additive command fieldAdd optional PromoCode to PlaceOrderLow — old callers still valid
Required field addedMake ShippingAddress mandatoryMedium — every caller must be updated in lockstep
Command split/renamedUpdateOrder → CancelOrder + AmendOrderHigh — callers must pick the correct new intent
Invariant tightenedOrders now require ≥1 line at submit, not at addMedium — silently changes when errors surface
Read projection schema changeorder_summary_view adds a denormalized columnLow if additive, high if it changes the rebuild strategy
Consistency model changeSync same-transaction read model → async projectorVery high — every reader must now tolerate staleness

Walkthrough 1 — additive field (safe)

Additive command field — low blast radius
flowchart LR Old["Existing callers
(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)

Command split — UpdateOrder becomes two intents
flowchart TB Before["UpdateOrder(status, lines, address)"] --> Decide{"Split by intent"} Decide --> C1["CancelOrder"] Decide --> A1["AmendOrder(lines)"] Decide --> S1["ChangeShippingAddress"] classDef warn fill:#FDF3E4,stroke:#B45309,color:#16142A; class Before,Decide,C1,A1,S1 warn;

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.

C#
// ❌ 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);
}
Sharp edge — validating against a stale read model
sequenceDiagram participant CmdH as CancelOrderHandler participant RDB as Read store (stale) participant WDB as Write store (authoritative) Note over RDB: still shows "Submitted" — projector lags CmdH->>RDB: check status (WRONG source) RDB-->>CmdH: "Submitted" (stale!) CmdH->>WDB: publish OrderCancelled anyway Note over WDB: order was actually already "Shipped" —
invariant silently violated
10

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.

ModelHow it worksRead-your-writes?Cost
Same-transaction syncRead model updated in the same DB transaction as the writeAlwaysNo independent read scaling; write-path latency increases
Synchronous projection, separate storeCommand handler pushes to the read store before returningAlways (adds latency)Command latency includes projection cost
Async, near-real-timeDomain event → message bus → projector, typically <1sNo — brief windowBest scaling; needs UX/idempotency handling for the gap
Async, batch/periodicScheduled rebuild, minutes to hoursNoCheapest infra; unsuitable for anything the user expects to see reflected quickly
Consistency spectrum, from strict to eventual
flowchart LR A["Same-transaction
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.

11

Testing Strategy Per Component

Test pyramid mapped to CQRS components
flowchart TB E2E["End-to-end
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)

C#
// 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

C#
// 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);
    }
}
12

When To Use It — And When Not To

Decision tree — should this bounded context use CQRS?
flowchart TD Q1{"Do reads and writes
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.
13

Pros and Cons, Honestly

ProsCons
Independent scaling of read and write pathsTwo models (at minimum) to build, evolve, and keep mentally in sync
Read models can be denormalized freely without corrupting domain integrityEventual 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 languageMore infrastructure: projectors, possibly a second store, possibly a message bus
Read side is disposable and rebuildable — safe to experiment with shapesDebugging 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 matterOnboarding 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.

14

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).

Structural comparison — CRUD vs. CQRS vs. CQRS+ES
flowchart LR subgraph CRUD["Plain CRUD"] direction TB M1["One model"] --> D1[(One store)] end subgraph CQRS1["CQRS"] direction TB W1["Write model"] --> DW1[(Write store)] R1["Read model"] --> DR1[(Read store)] DW1 -.-> R1 end subgraph CQRSES["CQRS + Event Sourcing"] direction TB W2["Write model"] --> ES[(Event store,
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;
DimensionPlain CRUDCQRSCQRS + Event SourcingVertical Slice (VSA)
Origin / author / yearImplicit, pre-dates namingGreg Young, 2010Young / event-sourcing community, ~2010Jimmy Bogard, ~2016
Primary organizing axisEntity / tableCommand vs. query responsibilitySequence of events as source of truthFeature / use case
Dependency directionUI → service → data, one pathTwo independent paths from a shared boundaryWrite appends events; reads derive from themOrthogonal — organizes files, not data flow
Best-fit scenarioSimple, symmetric read/write needsInvariant-rich core domain, divergent read shapesAuditability, temporal queries, complex state historyAny of the above — pairs well with CQRS (§14.1)
Main failure modeGod-object model straining under divergent readsValidating 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.

15

Common Mistakes and Anti-Patterns

Mistake 1 — CRUD-shaped commands

C#
// ❌ 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

C#
// ❌ 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

C#
// ❌ 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);
16

Adoption Path

Incremental adoption from an existing CRUD codebase
flowchart LR S1["1. Rename existing
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

Markdown
# 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
17

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)
18

Sources

Primary

Analysis and comparison

Tooling