Skip to content

C# Interview Guide: CQRS with MediatR — Commands, Queries, Pipeline Behaviours

Q27 — CQRS with MediatR — Commands, Queries, Pipeline Behaviours Level: Senior | Topic: Architecture CQRS in a Nutshell Command Query Responsibility Segregation separates operations that change state (Commands) from oper...

Ekanatha Reddy Urivakili12 min1,882 words

Q27 — CQRS with MediatR — Commands, Queries, Pipeline Behaviours

Level: Senior | Topic: Architecture

CQRS in a Nutshell

Command Query Responsibility Segregation (CQRS) is an architectural pattern that strictly separates operations that change state (Commands) from those that read state (Queries). This separation allows you to optimize, scale, and maintain these operations independently.

  • Commands: Mutate state and typically return a result such as an identifier or void. They should have no read operations.
  • Queries: Return data and must not have side effects or mutate state.

MediatR implements the Mediator pattern, which decouples senders (like controllers) from handlers. Instead of directly invoking services, controllers dispatch requests to handlers registered with MediatR. This simplifies dependency management and increases testability.

Why Use CQRS with MediatR?

  • Single Responsibility per Handler: Each request handler addresses one use case.
  • Clear Separation: Read operations can be optimized independently from write operations.
  • Cross-cutting Concerns via Pipeline Behaviours: MediatR allows middleware-like behaviours to wrap handlers, e.g., logging, validation, caching.
  • Improved Testability: Handlers are regular classes with injected dependencies.

MediatR Pipeline Behaviours — The Middleware for Requests

Pipeline behaviours in MediatR are akin to middleware in HTTP pipelines. They intercept requests and can execute code before and/or after the handler is called.

Common Pipeline Behaviours

BehaviourConcernWhat it doesApplies to
LoggingObservabilityLogs start and finish of every requestCommands & Queries
ValidationInput correctnessRuns FluentValidation validatorsCommands (mostly)
TransactionAtomicity, consistencyWraps commands in transactionsCommands
CachingPerformance optimizationReturns cached query result if availableQueries

Architecture Diagram (High Level)

flowchart LR
    A[Client/Controller] -->|Send Command/Query| B(MediatR Mediator)
    B --> C[Pipeline Behaviour 1: Logging]
    C --> D[Pipeline Behaviour 2: Validation]
    D --> E[Pipeline Behaviour 3: Transaction]
    E --> F[Request Handler]
    F --> G[Repository / Read Model / External Systems]
    G --> F
    F --> E
    E --> D
    D --> C
    C --> B
    B --> A

High-level flow of a CQRS request through MediatR pipeline behaviours to handler and data store


Sequence Diagram: PlaceOrderCommand Flow

sequenceDiagram
    participant Controller
    participant Mediator
    participant LoggingPB as Logging Behaviour
    participant ValidationPB as Validation Behaviour
    participant TxPB as Transaction Behaviour
    participant Handler
    participant Repo as Order Repository
    participant EventBus

    Controller->>Mediator: Send PlaceOrderCommand
    Mediator->>LoggingPB: Handle(request)
    LoggingPB->>ValidationPB: Handle(request)
    ValidationPB->>TxPB: Handle(request)
    TxPB->>Handler: Handle(PlaceOrderCommand)
    Handler->>Repo: SaveAsync(order)
    Handler->>EventBus: PublishAsync(OrderCreatedEvent)
    Repo-->>Handler: Save complete
    EventBus-->>Handler: Publish complete
    Handler-->>TxPB: return orderId
    TxPB-->>ValidationPB: return orderId
    ValidationPB-->>LoggingPB: return orderId
    LoggingPB-->>Mediator: return orderId
    Mediator-->>Controller: return orderId

Step-by-step interaction for placing an order command through MediatR pipeline and handler


Deep Dive: Command, Query, and Pipeline Behaviour Code Examples

Minimal Example: Simple Command and Handler

public record PingCommand() : IRequest<string>;

public class PingHandler : IRequestHandler<PingCommand, string>
{
    public Task<string> Handle(PingCommand request, CancellationToken cancellationToken)
        => Task.FromResult("Pong");
}

Notice how succinct a command and handler are—just a record and a class implementing IRequestHandler.


Realistic Example: PlaceOrder with Validation and Events

// Command — request to place an order
public record PlaceOrderCommand(string CustomerId, List<OrderLineRequest> Lines) : IRequest<string>;

// Validation with FluentValidation
public class PlaceOrderCommandValidator : AbstractValidator<PlaceOrderCommand>
{
    public PlaceOrderCommandValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty().MaximumLength(100);
        RuleFor(x => x.Lines).NotEmpty().WithMessage("Order must have at least one line");
        RuleForEach(x => x.Lines).ChildRules(line =>
        {
            line.RuleFor(l => l.Quantity).GreaterThan(0);
            line.RuleFor(l => l.UnitPrice).GreaterThan(0);
        });
    }
}

// Command Handler — business logic, state changes and events
public class PlaceOrderHandler : IRequestHandler<PlaceOrderCommand, string>
{
    private readonly IOrderRepository _repo;
    private readonly IEventPublisher _events;

    public PlaceOrderHandler(IOrderRepository repo, IEventPublisher events)
    {
        _repo = repo;
        _events = events;
    }

    public async Task<string> Handle(PlaceOrderCommand cmd, CancellationToken ct)
    {
        var order = Order.Create(cmd.CustomerId, cmd.Lines.Select(l =>
            new OrderLine(l.ProductId, l.Quantity, l.UnitPrice)));

        await _repo.SaveAsync(order, ct);
        await _events.PublishAsync(new OrderCreatedEvent(order.Id, cmd.CustomerId), ct);
        return order.Id;
    }
}

This example demonstrates full flow with validation, data creation, persistence, and domain event publishing.


Pipeline Behaviour: Logging vs Validation

// Logging Behaviour — logs start and end time of the request handler
public class LoggingBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    private readonly ILogger<LoggingBehaviour<TRequest, TResponse>> _logger;

    public LoggingBehaviour(ILogger<LoggingBehaviour<TRequest, TResponse>> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request,
        RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var name = typeof(TRequest).Name;
        _logger.LogInformation("Handling {RequestName}", name);
        var sw = Stopwatch.StartNew();

        try
        {
            return await next();
        }
        finally
        {
            sw.Stop();
            _logger.LogInformation("Handled {RequestName} in {ElapsedMilliseconds}ms", name, sw.ElapsedMilliseconds);
        }
    }
}

// Validation Behaviour — runs FluentValidation validators registered for the request type
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }

    public async Task<TResponse> Handle(TRequest request,
        RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        if (!_validators.Any()) return await next();

        var context = new ValidationContext<TRequest>(request);
        var failures = _validators.Select(v => v.Validate(context))
            .SelectMany(r => r.Errors).Where(f => f != null).ToList();

        if (failures.Any())
            throw new ValidationException(failures);

        return await next();
    }
}

These behaviours cleanly separate concerns from the business logic inside handlers.


Controller Layer: Thin Delegating Controllers

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly IMediator _mediator;

    public OrdersController(IMediator mediator)
        => _mediator = mediator;

    [HttpPost]
    public async Task<IActionResult> PlaceOrder([FromBody] PlaceOrderCommand cmd, CancellationToken ct)
    {
        var orderId = await _mediator.Send(cmd, ct);
        return CreatedAtAction(nameof(GetOrder), new { id = orderId }, new { id = orderId });
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetOrder(string id, CancellationToken ct)
    {
        var order = await _mediator.Send(new GetOrderQuery(id), ct);
        return order is null ? NotFound() : Ok(order);
    }
}

Controllers act as thin adapters that convert HTTP calls into MediatR requests.


Detailed Comparison: Commands vs Queries vs Events

AspectCommandQueryEvent
PurposeChange system stateRetrieve dataNotify after state change
Method SignatureReturns ID or nothingReturns DTO / dataReturns void
Side EffectsAllowedNoneAllowed (side effects occur)
Validations RequiredYesMinimalTypically none
Typical Handler TasksBusiness logic, persistenceData retrieval, cachingNotify other components
Pipeline BehavioursLogging, Validation, TransactionLogging, CachingLogging
ExamplePlaceOrderCommandGetOrderQueryOrderCreatedEvent

Observability in CQRS with MediatR

Building maintainable systems requires comprehensive observability:

What to Log

  • Incoming request details: type, payload summary (avoid sensitive info)
  • Validation failures: which rules failed and why
  • Handler execution time and success/failure
  • Side effects triggered (e.g., events published)
  • Exceptions and stack traces

Structured Log Example (using Serilog)

{
  "Timestamp": "2024-06-01T12:00:00Z",
  "Level": "Information",
  "RequestType": "PlaceOrderCommand",
  "OrderId": "1234abcd",
  "DurationMs": 150,
  "Event": "OrderCreated",
  "CustomerId": "cust-5678",
  "Message": "Handled PlaceOrderCommand in 150ms"
}

Key Metrics

Metric NameTypeDescriptionRecommended Monitoring Tool
Request RateCounterNumber of commands and queries processed per secondPrometheus/Grafana
Error RateCounterNumber of handler exceptions per secondPrometheus/Grafana
Request LatencyHistogramProcessing time per requestPrometheus/Grafana
Validation FailuresCounterNumber of failed validationsPrometheus/Grafana
Event Publish LatencyHistogramTime to publish domain eventsPrometheus/Grafana

Distributed Tracing with OpenTelemetry

Use OpenTelemetry to trace asynchronous requests across services and database calls.

// Example: configuring OpenTelemetry tracing in ASP.NET Core
services.AddOpenTelemetryTracing(builder =>
{
    builder
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("MediatR")
        .AddJaegerExporter();
});

// In PipelineBehaviour
using OpenTelemetry.Trace;

public class TracingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    private static readonly ActivitySource ActivitySource = new("MediatR");

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        using var activity = ActivitySource.StartActivity(typeof(TRequest).Name);
        return await next();
    }
}

SLI/SLO Examples

SLISLOMeasurement Method
Requests Served≥ 99.9% within 500msPercentile latency in tracing
Error Rate≤ 0.1% errorsException counters
Validation Failures≤ 0.05% of commandsValidation failure counters
Event Publish Success≥ 99.9%Event publish success metrics

Worth Paging Alerts

  • Handler exception rate spike above threshold
  • Validation failure spike (potential client or schema issues)
  • Latency exceeding SLA for commands or queries consistently
  • Event publishing failures causing potential state inconsistency

Senior Engineer Insights

  • Keep handlers small and focused; handlers depending on 5+ services likely violate SRP.
  • Pipeline behaviours provide AOP-like capabilities but avoid overloading them; keep cross-cutting concerns lightweight and composable.
  • Validation should run early to fail fast and reduce waste downstream.
  • Queries can safely benefit from caching behaviours; commands should be transactional.
  • Consider eventual consistency for complex command transactions using domain events and asynchronous processing.
  • Structure logs and metrics consistently; cultivate a strong DevOps feedback loop to detect issues before users do.

This guide equips you to leverage CQRS with MediatR effectively in C# — designing maintainable, testable, and observable systems. Questions in interviews on this topic probe not only your coding skills but also architectural judgment and operational considerations.

Internal Workings of the MediatR Pipeline and CQRS Handlers

Understanding the internal mechanics of MediatR’s pipeline behaviours and CQRS handlers is crucial to designing robust and efficient systems. The pipeline behaves like a nested chain of delegates, each wrapping the subsequent handler or behaviour. This lets you compose cross-cutting concerns as middleware.

The Pipeline as Nested Delegates

Internally, MediatR builds the pipeline dynamically by calling each registered IPipelineBehavior<TRequest,TResponse> in sequence. Each behaviour receives a delegate RequestHandlerDelegate<TResponse> that it must invoke to continue the chain:

sequenceDiagram
    participant Caller
    participant PB1 as PipelineBehaviour1
    participant PB2 as PipelineBehaviour2
    participant Handler

    Caller->>PB1: Handle(request, next)
    PB1->>PB2: Handle(request, next)
    PB2->>Handler: Handle(request)
    Handler-->>PB2: response
    PB2-->>PB1: response
    PB1-->>Caller: response
  • Each behaviour can execute before and after calling next().
  • Behaviours can short-circuit the chain by returning a response early, useful for caching or authorization checks.
  • Exceptions propagate up the call stack, allowing centralised error logging behaviours.

Pipeline Behaviour Life Cycle and Registration

Pipeline behaviours are singletons and stateless in typical usage, allowing safe reuse across requests. Their invocation order respects registration order in the DI container. For example:

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TransactionBehaviour<,>));

Here Logging will execute first (outermost) and Transaction last (innermost) before the handler starts, and in reverse order after handler completion.

Handler Execution Semantics

Handlers implement IRequestHandler<TRequest, TResponse>, encapsulating the core business logic. CQRS commands are idempotent per request but not necessarily overall; commands may mutate state and must be resilient to retries and failures.

Key internal expectations:

  • No side effects outside handler: Side effects, such as publishing events, must be explicit and ideally transactional together with persistence.
  • Minimal blocking: Use async calls for IO-bound operations to avoid thread starvation.
  • Short-lived state: Avoid storing state in handler fields to prevent concurrency bugs.

End-to-End Production Scenario: Order Placement with Failure Recovery

Let’s walk through a realistic, production-grade scenario of processing a PlaceOrderCommand with transactional integrity and failure handling.

Step 1: Receiving the Command

An HTTP POST request arrives at OrdersController.PlaceOrder, mapping JSON to PlaceOrderCommand. The controller calls:

var orderId = await _mediator.Send(cmd, ct);

Through dependency injection, MediatR dispatches the command into the pipeline:

  • LoggingBehaviour logs start.
  • ValidationBehaviour runs FluentValidation rules; failures throw ValidationException.
  • TransactionBehaviour begins a new database transaction.

Step 2: Command Handler Execution

The PlaceOrderHandler performs:

  • Create an in-memory order aggregate.
  • Persist order aggregate to the repository.
  • Publish domain event OrderCreatedEvent to asynchronous event bus.
  • Return order identifier.

Step 3: Transaction Commit and Event Dispatching

The transaction behaviour commits the underlying database transaction after the handler completes successfully. This ensures atomicity for order state persistence and event dispatching.

Failure Mode: Event Publishing Failure

If the event bus PublishAsync call fails (e.g., network partition), the handler can:

  • Roll back the transaction to avoid partial state change.
  • Retry event dispatch synchronously or queue the event for later processing.
  • Use Outbox pattern (store events with the order in the same transaction, and asynchronously relay them later).

Outbox Pattern Integration (Simplified Pseudocode)

// During SaveAsync
using var tx = await _db.BeginTransactionAsync(ct);
await _db.Orders.AddAsync(order, ct);
await _db.EventOutbox.AddAsync(new OutboxEvent(order.Id, "OrderCreated", eventPayload), ct);
await tx.CommitAsync(ct);

// Separate background service reads outbox and sends events to EventBus

This ensures exactly-once event delivery semantics and resilience against partial failures.


Edge Cases and Failure Handling in CQRS Pipelines

Despite CQRS’s clarity, real systems must deal with subtle failure modes:

1. Validation Failures

  • Occur early in pipeline; result in ValidationException.
  • Must map to HTTP 400 responses with clear error messages.
  • Validation rules often evolve; version and deprecate carefully.

2. Transaction Rollbacks

  • Database deadlocks or constraint violations (e.g., unique indexes) can cause rollbacks.
  • TransactionBehaviour must catch DB exceptions and translate or rethrow.
  • Retries with exponential backoff may be necessary (handled upstream or by queue workers).

3. Handler Exceptions

  • Unhandled exceptions bubble up to ASP.NET Core middleware.
  • Configure global exception handler to convert to 500 Internal Server Error.
  • Health of request pipeline depends on robust exception management.

4. Long-Running Commands

  • Some commands may take seconds or minutes (e.g., external payment gateways).
  • Avoid blocking HTTP requests; implement async eventual consistency with command queues and callbacks.
  • Pipeline behaviours should support cancellation tokens and timeout enforcement.

5. Query Caching Invalidation

  • Cached queries improve read performance but stale caches can return erroneous data.
  • Pipeline must include cache invalidation strategies on data modification commands, e.g.:
public class CacheInvalidationBehaviour<TRequest, TResponse> 
    : IPipelineBehavior<TRequest, TResponse> 
    where TRequest : IRequest<TResponse>
{
    private readonly ICache _cache;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var response = await next();

        if (request is ICommand)  // Pseudocode: invalidates cache on commands
        {
            await _cache.InvalidateAsync(GetCacheKey(request));
        }

        return response;
    }
}

Performance Considerations in CQRS with MediatR

Optimizing throughput and latency demands awareness about pipeline and command-handler implementation.

Pipeline Overhead

Each pipeline behaviour adds additional async calls and method invocations:

  • Keep behaviours lightweight, avoid expensive operations inside pipeline.
  • Group multiple validation rules to run in parallel when possible.
  • Minimize synchronous blocking code (e.g., Task.Result) inside pipelines.

Commands vs Queries Performance

  • Queries often dominate load; apply aggressive caching, denormalized read models, and async data fetching.
  • Commands require strong consistency; optimize by:
    • Using batch operations to reduce DB roundtrips.
    • Avoiding unnecessary domain event publication if not consumed.
    • Implementing idempotency keys to handle retries safely.

MediatR Scalability

  • MediatR itself is synchronous per request but can dispatch multiple parallel requests with separate scopes.
  • Use concurrency/parallelism patterns if high throughput is needed.
  • For distributed scale: offload commands to message queues (RabbitMQ, Kafka) and handlers consume asynchronously.

Sample Telemetry Injection to Profile Handler

public class ProfilingBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
    private readonly ILogger _logger;
    public ProfilingBehaviour(ILogger logger) => _logger = logger;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken ct)
    {
        var timer = Stopwatch.StartNew();
        var result = await next();
        timer.Stop();
        _logger.LogInformation("Handled {Request} in {ElapsedMs} ms", typeof(TRequest).Name, timer.ElapsedMilliseconds);
        return result;
    }
}

Observability Checklist for CQRS with MediatR in Production

Observability is mission-critical. Here’s a checklist and sample implementation snippets:

What to Log

Data PointPurposeExample
Request Type & PayloadTrace request flow"RequestType": "PlaceOrderCommand", "CustomerId": "cust-01"
Validation FailuresExplain failures for clients"ValidationErrors": ["Quantity must be > 0"]
Handler Execution TimePerformance debugging"DurationMs": 123
Side EffectsAudit and replayability"EventsPublished": ["OrderCreated"]
Exception DetailsRoot cause analysis"Exception": "SqlException", "StackTrace": "..."

Key Metrics with Example Prometheus Names

MetricTypeLabelsDescription
mediator_requests_totalCounterrequest_type, outcome(success/fail)Total number of MediatR requests
mediator_request_duration_secondsHistogramrequest_typeRequest processing latency
mediator_validation_failures_totalCounterrequest_typeNumber of validation failures
mediator_event_publishes_totalCounterevent_typeDomain events published
mediator_handler_exceptions_totalCounterrequest_type, exception_typeExceptions raised in handlers

Distributed Tracing Span Structure

sequenceDiagram
    participant Controller
    participant MediatR
    participant LoggingPB
    participant ValidationPB
    participant TransactionPB
    participant Handler
    participant Repository
    participant EventBus

    Controller->>MediatR: Start trace span "HTTP Request"
    MediatR->>LoggingPB: Start span "Logging Behaviour"
    LoggingPB->>ValidationPB: Start span "Validation Behaviour"
    ValidationPB->>TransactionPB: Start span "Transaction Behaviour"
    TransactionPB->>Handler: Start span "Handler Execution"
    Handler->>Repository: Start span "Repository Access"
    Repository-->>Handler: End span "Repository Access"
    Handler->>EventBus: Start span "Event Publishing"
    EventBus-->>Handler: End span "Event Publishing"
    Handler-->>TransactionPB: End span "Handler Execution"
    TransactionPB-->>ValidationPB: End span "Transaction Behaviour"
    ValidationPB-->>LoggingPB: End span "Validation Behaviour"
    LoggingPB-->>MediatR: End span "Logging Behaviour"
    MediatR-->>Controller: End trace span "HTTP Request"

Each pipeline behaviour and handler creates child spans so latency hotspots and failures can be traced precisely.


Decision Checklist for Adopting CQRS with MediatR

Before committing to CQRS and the MediatR pipeline, consider the following:

QuestionWhy It MattersDecision Notes
Is command/query separation beneficial here?Improves maintainability, but adds complexityUse if business logic benefits from clear separation
Are read and write loads imbalanced?Optimizes scaling and caching strategiesCQRS benefits read-heavy or write-heavy systems
Do you need cross-cutting concerns modularized?Pipeline behaviours support AOP style preprocessingMediatR pipeline simplifies cross-cutting management
Will eventual consistency acceptable?Synchronous commands are simpler but less scalableUse async messaging for complex workflows
Is the team familiar with the pattern?CQRS adds cognitive load and boilerplateProvide training or start with small features
Can you integrate observability properly?Critical for debugging distributed commandsInstrument pipelines, handlers, events consistently

This deeper dive equips you to architect CQRS-based solutions with MediatR focusing on internal mechanisms, production reliability, performance tuning, and observability practices critical to senior engineers building complex distributed systems.