📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📰 When CQRS Is Overkill: How I Decide in Real .NET Projects

When CQRS Is Overkill: How I Decide in Real .NET Projects

When CQRS Is Overkill: How I Decide in Real .NET Projects

CQRS shows up in a lot of .NET job ads, conference talks and starter templates. Sometimes it's presented as the "proper" way to build an application, as if every project should have a folder full of commands, queries and handlers from day one.

I've used it on real projects, and I like it. But it can also add a lot of ceremony to code that doesn't need it. So this post is about the question I now ask before I reach for it: does this project actually have the problem CQRS solves?

From 2022 to 2023 I worked as a Mid-Level .NET Developer at Fintech Solutions in Kathmandu. On those projects we applied CQRS and MediatR, alongside dependency injection, FluentValidation, Serilog and Hangfire, and I owned design, coding, integration and bug fixing on large-scale projects. This post is what that taught me about when the pattern earns its place, and when it's overkill.

To keep this practical, I'll use a typical payments back office as the running example: customers, beneficiaries, transfers and approvals. It's the kind of domain where the trade-offs show up clearly.

What CQRS actually is (the short version)

CQRS stands for Command Query Responsibility Segregation. Strip away the long name and the idea is simple:

  • Commands change state. "Create a transfer", "approve a customer", "cancel a booking". They don't return data beyond an id or a result.
  • Queries read state. "Get this customer's transactions", "list pending approvals". They never change anything.

You keep those two paths separate in your code. That's it. Everything else people attach to CQRS (separate read and write databases, event sourcing, message buses) is optional, and it's where most of the complexity comes from.

In .NET, the common way to do this is with MediatR: each command or query is a small request object, and each has one handler. Controllers stop calling services directly and send requests instead.

A minimal example

Here's a generic example of what that looks like. This is illustrative code written for this post, not code from any of my projects.

// Example only: a command and its handler with MediatR.
public sealed record CreateCustomerCommand(string FullName, string Email) : IRequest<Guid>;

public sealed class CreateCustomerHandler : IRequestHandler<CreateCustomerCommand, Guid>
{
    private readonly AppDbContext _db;

    public CreateCustomerHandler(AppDbContext db) => _db = db;

    public async Task<Guid> Handle(CreateCustomerCommand request, CancellationToken ct)
    {
        var customer = new Customer(request.FullName, request.Email);
        _db.Customers.Add(customer);
        await _db.SaveChangesAsync(ct);
        return customer.Id;
    }
}

// Example only: a query reads data and returns a DTO, never an entity.
public sealed record GetCustomerQuery(Guid Id) : IRequest<CustomerDto?>;

public sealed class GetCustomerHandler : IRequestHandler<GetCustomerQuery, CustomerDto?>
{
    private readonly AppDbContext _db;

    public GetCustomerHandler(AppDbContext db) => _db = db;

    public Task<CustomerDto?> Handle(GetCustomerQuery request, CancellationToken ct) =>
        _db.Customers
            .AsNoTracking()
            .Where(c => c.Id == request.Id)
            .Select(c => new CustomerDto(c.Id, c.FullName, c.Email))
            .FirstOrDefaultAsync(ct);
}

And the controller becomes very thin:

// Example only.
[ApiController]
[Route("api/customers")]
public sealed class CustomersController : ControllerBase
{
    private readonly ISender _sender;

    public CustomersController(ISender sender) => _sender = sender;

    [HttpPost]
    public async Task<IActionResult> Create(CreateCustomerCommand command, CancellationToken ct)
    {
        var id = await _sender.Send(command, ct);
        return CreatedAtAction(nameof(Get), new { id }, null);
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> Get(Guid id, CancellationToken ct) =>
        await _sender.Send(new GetCustomerQuery(id), ct) is { } dto ? Ok(dto) : NotFound();
}

Looks tidy. But notice what it costs: for one simple "create" and one simple "get", we now have four types, two handlers and an extra layer of indirection. Whether that's worth it depends entirely on the project.

Where CQRS earns its place

The value of CQRS isn't the folders. It's what you can hang off the pipeline once every use case goes through it.

Cross-cutting concerns in one place. With MediatR, pipeline behaviours run around every request. Validation, logging and transaction handling can be written once instead of copied into every service method. This is where the "supporting cast" fits in nicely: FluentValidation for the rules, Serilog for structured logs.

// Example only: run FluentValidation for every request before its handler.
public sealed 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())
        {
            var context = new ValidationContext<TRequest>(request);
            var results = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, ct)));
            var failures = results.SelectMany(r => r.Errors).Where(f => f is not null).ToList();

            if (failures.Count > 0)
                throw new ValidationException(failures);
        }

        return await next();
    }
}

Reads and writes that genuinely look different. In financial systems, the write side is strict: rules, checks, audit, and state that must never be wrong. The read side is often reports, lists and dashboards that join a lot of data and don't care about business rules at all. Forcing both through the same rich domain model makes reads slow and awkward. Separating them lets queries be simple, fast projections with AsNoTracking, while commands keep all the rules.

Many developers, many features. One handler per use case means small files with one job. When several people work on the same codebase, that cuts down on merge conflicts in giant service classes, and new developers can find "the thing that approves a transfer" by name.

Here's a practical example of where that pays off. Say a new requirement arrives: every request in the system must be logged with its name and how long it took, so support can trace slow or failing transfers. Without a pipeline, that's a change to every service method, and someone will miss one. With MediatR, it's one class:

// Example only: log every request with its name and duration.
public sealed 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;
        var sw = Stopwatch.StartNew();
        try
        {
            return await next();
        }
        finally
        {
            _logger.LogInformation("Handled {RequestName} in {ElapsedMs} ms", name, sw.ElapsedMilliseconds);
        }
    }
}

Register it once, and every command and query is covered, including the ones added next month by someone who has never heard of this requirement.

Where it's overkill

Here's the part that templates don't tell you. I'd skip CQRS, or at least MediatR, when:

The app is mostly CRUD. If most screens are "create a record, edit a record, list records", commands and queries just mirror the database tables. You end up with CreateXCommand, UpdateXCommand, GetXQuery and GetXListQuery for every entity, each with a handler that does one line of real work.

One or two developers, and a small surface. The organisational benefits of CQRS show up when lots of people touch lots of features. On a small app, a plain service class is easier to read top to bottom.

Nobody needs the pipeline. If you're not using pipeline behaviours for validation, logging or transactions, MediatR is mostly an indirection layer. "Go to definition" on _sender.Send(...) doesn't take you to the code that runs, which slows down everyone reading it.

You're tempted by the "full" version. Separate read and write databases, eventual consistency and event sourcing are powerful, but they bring real operational cost. Most line-of-business apps don't need them. Adding them "for later" usually means paying for them now.

A practical example: a small admin screen for managing lookup data, like a list of supported currencies or countries. It needs add, edit, delete and list. With full CQRS and MediatR, that's four request types, four handlers, probably four validators, and a controller that just forwards calls. A single CurrencyService with four methods does the same job in one file that anyone can read in a minute. When the logic is that thin, the pattern is mostly paperwork.

The middle ground I like

CQRS isn't all or nothing. The idea of separating reads from writes is useful even without a library.

// Example only: CQRS-style separation without MediatR.
public interface ICustomerCommands
{
    Task<Guid> CreateAsync(string fullName, string email, CancellationToken ct);
}

public interface ICustomerQueries
{
    Task<CustomerDto?> GetAsync(Guid id, CancellationToken ct);
}

Two small interfaces, registered with normal dependency injection. Reads and writes are still separate, queries still return DTOs, and "go to definition" works. If the project grows and you need a pipeline, moving to MediatR from here is easy, because the split already exists.

How I decide now

Before adding CQRS to a .NET project, I ask a few questions:

  1. Are the reads and writes really different? Different shapes, different performance needs, different rules? If yes, separate them.
  2. Will I use the pipeline? Validation, logging, transactions, authorisation checks across many use cases? If yes, MediatR pays for itself.
  3. How many people will work on this, and for how long? A long-lived system with a team benefits from one-handler-per-use-case. A small tool usually doesn't.
  4. Is this mostly CRUD? If yes, keep it simple and revisit later.
  5. Am I adding it for the project, or for the CV? This one's uncomfortable, but worth asking.

If I answer "yes" to the first two, I use CQRS with MediatR. If it's only the first, I split interfaces without a library. If it's neither, I write plain services and move on.

What I'd tell a developer starting out

Learn CQRS properly. Understand why it exists, build something with it, and be able to explain the trade-offs. It comes up in interviews for a reason, and on the right project it makes the code genuinely easier to work with.

But treat it as a tool, not a default. The best design decision I can make on a small project is often to not add a pattern yet, and leave the code simple enough that adding it later is easy.

In practice, that means I'm happy to start a small internal tool with plain services and DTOs, and I reach for CQRS with MediatR when the system has real business rules, a busy read side and more than a couple of people working on it.

Have you used CQRS on a project where it really helped, or one where it just got in the way? Tell me in the comments.

X / Twitter LinkedIn

Comments (0)

No comments yet. Be the first!

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me