Cloud & ArchitectureComplete guide

CQRS & MediatR

Command Query Responsibility Segregation splits an application's write model, optimized for enforcing invariants, from its read model, optimized for the shapes a UI or report actually needs.

Overview

CQRS separates intent to change state from requests to read state so each path can use contracts, validation, models, data access, and scaling suited to its job. Logical separation can begin in one process and one database: commands enforce authorization, invariants, idempotency, and transaction boundaries, while queries project only caller-required fields and never mutate. MediatR is an optional in-process dispatcher, not the architecture itself; request handlers improve discovery and pipeline behaviors can apply validation, tracing, transactions, and other cross-cutting policy in a deliberate order. Physical read stores and asynchronous projections add eventual consistency, replay, lag, reconciliation, schema evolution, and operating cost, so they should follow measured needs. CQRS does not imply event sourcing, microservices, separate databases, or one handler per trivial property update.

What you will learn

  • Separate commands and queries by responsibility and contract.
  • Design command handlers around invariants, authorization, idempotency, and transactions.
  • Build read projections shaped for callers without mutating state.
  • Use MediatR request handlers and ordered pipeline behaviors deliberately.
  • Choose synchronous or asynchronous projections from consistency needs.
  • Operate projection lag, rebuilds, reconciliation, and contract evolution.

Prerequisites

  • ASP.NET Core, dependency injection, async C#, persistence, and testing.
  • Transactions, optimistic concurrency, messaging, and eventual consistency basics.
  • Understanding of domain models and purpose-built read projections.

When to use CQRS & MediatR

Good fit

  • Read and write shapes, rules, or scaling differ materially.
  • Named requests and pipeline policy improve feature ownership.
  • Asynchronous projections solve a measured isolation or throughput need.

Choose another approach when

  • Straightforward CRUD has aligned read and write models.
  • Handlers merely forward every call through extra indirection.
  • The team cannot operate projection lag, replay, and reconciliation.

Key concepts

Commands vs queries

Commands express an intent to change state and stay narrow; queries return data shaped for a specific read need and never mutate anything.

Single handler per request

Each command or query type is matched to exactly one handler, keeping request-to-behavior mapping explicit and easy to locate.

Pipeline behaviors

Cross-cutting concerns—validation, logging, transactions, authorization—wrap every request through a shared pipeline instead of being repeated per handler.

Read models

Query handlers can read from denormalized or differently shaped projections instead of the same model the write side uses.

Logical versus physical separation

Commands and queries can share one store initially; separate stores add operational and consistency cost.

Idempotent commands

A stable request identifier lets repeated delivery return the original outcome without duplicate side effects.

Projection consistency

Synchronous projections are immediately visible; asynchronous projections expose lag and need reconciliation.

Mediator trade-offs

Dispatch improves pipelines and discovery but can hide control flow or add handlers with no useful behavior.

Architecture

A mediator routes each command or query to its handler; write handlers change the domain model while read handlers return projections shaped for their caller.

Caller
Mediator
Command handler / Query handler
Domain model / Read model

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated sample uses a small mediator-compatible request/handler abstraction so command/query separation and pipeline ordering stay visible without hiding behavior behind a package.

  1. 01
    Separate intent

    Name commands as business actions and queries as read needs with explicit results.

  2. 02
    Build command handlers

    Authenticate context, authorize resources, validate intent, enforce invariants, and commit one outcome.

  3. 03
    Build query handlers

    Project bounded fields directly into caller-specific read contracts.

  4. 04
    Order pipeline behavior

    Place tracing, validation, authorization, idempotency, transactions, and exception mapping deliberately.

  5. 05
    Choose projection timing

    Use synchronous updates for immediate consistency or durable events for asynchronous reads.

  6. 06
    Test delivery semantics

    Cover duplicates, concurrency, rollback, lag, missing reads, and cancellation.

  7. 07
    Operate projections

    Measure checkpoints and lag and provide rebuild, replay, and reconciliation tools.

Code example

A command and its handler stay narrow, returning only what the caller needs to continue.

PlaceOrderCommand.cs
public sealed record PlaceOrderCommand(Guid CustomerId, IReadOnlyList<OrderLine> Lines)
    : IRequest<Guid>;

public sealed class PlaceOrderHandler(IOrderRepository orders, IUnitOfWork unitOfWork)
    : IRequestHandler<PlaceOrderCommand, Guid>
{
    public async Task<Guid> Handle(PlaceOrderCommand command, CancellationToken ct)
    {
        var order = Order.Place(command.CustomerId, command.Lines);
        await orders.AddAsync(order, ct);
        await unitOfWork.SaveChangesAsync(ct);
        return order.Id;
    }
}

Testing strategy

Test commands for safe state change and queries for accurate bounded projection.

  • Prove validation and authorization fail before side effects.
  • Test invariants, concurrency, transaction rollback, and cancellation.
  • Replay the same command identifier and assert one outcome.
  • Verify query filters, pagination, tenant scope, and no mutation.
  • Test pipeline ordering explicitly.
  • Exercise projection lag, replay, rebuild, poison events, and reconciliation.

Security considerations

Request dispatch is not authorization; each handler must apply trusted actor and resource policy.

  • Derive identity and tenant from verified context.
  • Authorize command and query resources independently.
  • Do not trust IDs, ownership, or roles in request bodies.
  • Bound query complexity and returned fields.
  • Redact request payloads and results from pipeline logs.

Performance and scalability

CQRS enables tailored optimization but adds dispatch and consistency overhead.

  • Project only needed columns and paginate reads.
  • Measure handler latency, allocations, query count, and pipeline cost.
  • Keep transactions short and avoid remote work inside them.
  • Track projection throughput, checkpoint, and lag.
  • Scale stores separately only after evidence.

Deployment and operations

Command contracts, read models, and projection schemas must coexist across rolling deployments.

  • Use additive request and event evolution.
  • Deploy projection consumers before dependent readers.
  • Use expand-contract migrations.
  • Preserve idempotency records across restarts.
  • Smoke-test command-to-read visibility and rollback.

Common problems and fixes

A command executes twice.

Likely cause: Retries lack idempotency.

Fix: Persist a request key and original outcome atomically.

A query returns stale data.

Likely cause: Projection lag is hidden.

Fix: Expose checkpoints and define freshness behavior.

Transactions do not wrap handlers.

Likely cause: Pipeline order or async flow is wrong.

Fix: Test ordering and place commit after the handler succeeds.

Queries load domain aggregates.

Likely cause: Read and write models remain coupled.

Fix: Use direct bounded projections.

Mediator hides control flow.

Likely cause: Too many notifications or pass-through handlers.

Fix: Use named requests only where the boundary adds value.

Projection cannot rebuild.

Likely cause: Source events or version handling are incomplete.

Fix: Retain replayable inputs and test deterministic rebuilds.

Best practices

  • Keep command handlers focused on one business outcome; split a handler that is doing two unrelated things.
  • Let query handlers bypass the domain model and read directly from a projection when that projection already exists.
  • Put validation, logging, and transaction handling in pipeline behaviors instead of repeating them in every handler.
  • Version read models independently from the write model once their shapes genuinely diverge.
  • Make commands idempotent wherever clients or transports can retry.
  • Keep pipeline order explicit and scope transactions around side effects only.
  • Measure projection lag and provide rebuild and reconciliation paths.
  • Use direct calls when mediator indirection adds no useful policy boundary.

Production checklist

  • Commands express business intent and queries never mutate.
  • Authorization, validation, idempotency, concurrency, and transactions are explicit.
  • Pipeline order is documented and tested.
  • Read contracts are bounded and purpose-built.
  • Projection consistency and freshness are communicated.
  • Lag, checkpoints, failures, and retries are observable.
  • Rebuild and reconciliation are rehearsed.
  • CQRS complexity is justified by measured needs.

Common interview questions

What does CQRS require?

Separate command and query responsibilities; it does not require separate databases, event sourcing, or microservices.

What do pipeline behaviors solve?

They apply ordered cross-cutting policy such as tracing, validation, authorization, idempotency, and transactions around handlers.

When is CQRS not worth it?

When read and write needs are simple and aligned and separate models add indirection without benefit.

Does CQRS require MediatR?

No. MediatR is an optional dispatcher; CQRS is the responsibility separation.

How is a command idempotent?

Use a stable request key, store the result atomically with state, and return it on duplicate delivery.

Where should transaction behavior run?

Around command side effects after validation and authorization, committing only when the handler succeeds.

How do read models recover?

Track checkpoints, retain replayable events, make updates idempotent, and rehearse rebuild plus reconciliation.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

CQRS Orders Mediator

A dependency-free .NET 10 implementation of CQRS request handlers and mediator-style pipeline behaviors with separate write and read models, validation, idempotency, and focused tests.

.NET 10CQRSMediator PatternxUnit
dedicated-samplecommands-queriespipeline-behavioridempotency
Run
dotnet run --project src/CqrsOrdersMediator
Test
dotnet test CqrsOrdersMediator.slnx