Separate commands and queries. Keep the architecture simple. Introduce complexity only when the requirements justify it.
Introduction
Imagine you're developing an e-commerce application using ASP.NET Core Web API, Entity Framework Core, and SQL Server.
Your application supports two important operations:
Place an Order: Validate product availability, calculate prices, enforce business rules, and save the order.
View Order History: Retrieve previous orders with filtering, sorting, pagination, and selected fields.
Both operations work with order data.
But do they have the same responsibilities?
Not really.
Placing an order focuses on business rules and maintaining data consistency.
Viewing order history focuses on retrieving information efficiently.
This is where CQRS (Command Query Responsibility Segregation) becomes useful.
A common misconception is that implementing CQRS requires two databases: one for reads and another for writes.
It doesn't.
In many applications, starting with separate command and query models while keeping a single database is a practical architectural choice.
Let's understand why.
1. What Is CQRS?
CQRS stands for Command Query Responsibility Segregation.
It is an architectural pattern that separates operations that change application state from operations that retrieve data.
There are two main responsibilities.
Commands — Write Operations
Commands represent an intention to change the system's state.
Examples:
PlaceOrderCommandUpdateProductCommandCancelOrderCommandRegisterStudentCommand
A command handler typically validates business rules, performs the required operation, and persists changes.
Queries — Read Operations
Queries retrieve information without intentionally modifying application state.
Examples:
GetOrderByIdQueryGetOrderHistoryQueryGetProductsQueryGetStudentDetailsQuery
A query handler focuses on retrieving and shaping data for a particular use case.
The core principle:
Commands change state. Queries return data.
The separation concerns responsibilities and models, not necessarily databases or microservices.
2. Traditional Architecture vs. CQRS
In a conventional application, a single service might handle both read and write operations.
public class OrderService
{
public Task<int> PlaceOrderAsync(...)
{
// Business rules and persistence
}
public Task<OrderDto> GetOrderAsync(...)
{
// Retrieve order
}
public Task<List<OrderDto>> GetHistoryAsync(...)
{
// Filtering and pagination
}
}This isn't inherently bad.
For small applications, a single service can be perfectly reasonable.
However, as business requirements grow, read and write logic may become increasingly complex.
For example, changing the order-history response shouldn't require modifying order-placement logic.
CQRS provides a way to separate these responsibilities.
Orders
|
+-- Commands
| |
| +-- PlaceOrderCommand
| +-- CancelOrderCommand
| +-- UpdateOrderCommand
|
+-- Queries
|
+-- GetOrderByIdQuery
+-- GetOrderHistoryQuery
+-- GetOrdersByCustomerQueryEach operation has a clear purpose and can evolve independently.
3. Why Start CQRS with One Database?
One of the most important architectural decisions is choosing how to store data.
Some developers associate CQRS with separate read and write databases.
But CQRS doesn't require that separation.
We can use:
Separate command handlers
Separate query handlers
Different request and response models
Different business and validation logic
The same EF Core DbContext
The same SQL Server database
Simple Architecture
ASP.NET Core API
|
Application Layer
|
+---------+---------+
| |
Commands Queries
| |
Command Handler Query Handler
| |
Business Rules Read Projection
| |
+---------+---------+
|
EF Core
|
SQL Server
One DatabaseThis provides logical separation without introducing the operational overhead of multiple databases.
Benefits
Lower complexity: No need to implement synchronization between separate databases.
Simpler deployment: One database to configure, monitor, back up, and maintain.
Immediate visibility: Once a transaction commits, queries against the same primary database can generally read the committed data, subject to transaction isolation and caching.
Easier debugging: Commands and queries use the same source of truth.
Independent code evolution: Read and write models can change separately.
For many business applications, these benefits make single-database CQRS a strong starting point.
4. Implementing CQRS in ASP.NET Core
Let's build a simple example using:
ASP.NET Core Web API
C#
Entity Framework Core
SQL Server
MediatR-style request handlers
We'll implement two operations:
Place an order.
Retrieve order history.
Step 1: Define the Order Entity
public class Order
{
public int Id { get; set; }
public int CustomerId { get; set; }
public DateTime CreatedAt { get; set; }
public decimal TotalAmount { get; set; }
public string Status { get; set; } = "Pending";
}The entity represents order data stored in SQL Server.
In a more complete application, an order would also contain order items, pricing information, and other business properties.
Step 2: Create a Command
using MediatR;
public record PlaceOrderCommand(
int CustomerId,
decimal TotalAmount
) : IRequest<int>;This command represents a request to place an order.
Step 3: Create the Command Handler
public class PlaceOrderHandler
: IRequestHandler<PlaceOrderCommand, int>
{
private readonly AppDbContext _context;
public PlaceOrderHandler(AppDbContext context)
{
_context = context;
}
public async Task<int> Handle(
PlaceOrderCommand request,
CancellationToken cancellationToken)
{
var order = new Order
{
CustomerId = request.CustomerId,
TotalAmount = request.TotalAmount,
CreatedAt = DateTime.UtcNow,
Status = "Pending"
};
_context.Orders.Add(order);
await _context.SaveChangesAsync(
cancellationToken);
return order.Id;
}
}The handler creates an order and persists it to SQL Server.
Production consideration: This is a simplified persistence example. In a real e-commerce application, never trust a client-supplied total amount. The server should calculate prices, validate inventory, enforce authorization, and handle concurrent stock updates within an appropriate transaction.
Step 4: Create a Query
Now we need to retrieve order history.
public record OrderDto(
int Id,
decimal TotalAmount,
string Status,
DateTime CreatedAt
);
public record GetOrderHistoryQuery(
int CustomerId
) : IRequest<List<OrderDto>>;Notice that the query returns a DTO rather than the complete database entity.
This is important because read operations often require only a subset of the available fields.
Step 5: Create the Query Handler
public class GetOrderHistoryHandler
: IRequestHandler<
GetOrderHistoryQuery,
List<OrderDto>>
{
private readonly AppDbContext _context;
public GetOrderHistoryHandler(
AppDbContext context)
{
_context = context;
}
public async Task<List<OrderDto>> Handle(
GetOrderHistoryQuery request,
CancellationToken cancellationToken)
{
return await _context.Orders
.AsNoTracking()
.Where(o =>
o.CustomerId == request.CustomerId)
.OrderByDescending(o => o.CreatedAt)
.ThenByDescending(o => o.Id)
.Take(20)
.Select(o => new OrderDto(
o.Id,
o.TotalAmount,
o.Status,
o.CreatedAt))
.ToListAsync(cancellationToken);
}
}Here we're using several EF Core optimizations:
AsNoTracking() avoids unnecessary change tracking for read-only data.
Where() filters records for the requested customer.
OrderByDescending() sorts recent orders first.
Take(20) limits the returned records.
Select() retrieves only the fields required by the response.
For a production order-history API, also implement pagination, authorization, and appropriate database indexes.
The key point is that the query handler is optimized for reading data, while the command handler focuses on business operations.
Both use the same database.
5. How CQRS Fits into Clean Architecture
CQRS works well with Clean Architecture because the application layer can organize business use cases into commands and queries.
A possible project structure is:
src/
|
+-- Domain/
| +-- Entities/
| +-- Order.cs
|
+-- Application/
| +-- Orders/
| +-- Commands/
| | +-- PlaceOrder/
| | +-- PlaceOrderCommand.cs
| | +-- PlaceOrderHandler.cs
| |
| +-- Queries/
| +-- GetOrderHistory/
| +-- GetOrderHistoryQuery.cs
| +-- GetOrderHistoryHandler.cs
|
+-- Infrastructure/
| +-- Persistence/
| +-- AppDbContext.cs
|
+-- API/
+-- Controllers/
+-- OrdersController.csFor stricter Clean Architecture boundaries, the application layer can depend on an abstraction such as IApplicationDbContext, with its implementation provided by the infrastructure layer.
This keeps EF Core implementation details outside the application use cases where appropriate.
6. Do We Need MediatR to Implement CQRS?
No.
CQRS is an architectural pattern.
MediatR is a library that can help dispatch requests to their corresponding handlers.
You can implement CQRS using plain C# classes and dependency injection without MediatR.
For example:
public class GetOrderHistoryHandler
{
private readonly AppDbContext _context;
public GetOrderHistoryHandler(
AppDbContext context)
{
_context = context;
}
public async Task<List<OrderDto>> HandleAsync(
int customerId,
CancellationToken cancellationToken)
{
return await _context.Orders
.AsNoTracking()
.Where(o => o.CustomerId == customerId)
.Select(o => new OrderDto(
o.Id,
o.TotalAmount,
o.Status,
o.CreatedAt))
.ToListAsync(cancellationToken);
}
}Both approaches are valid.
Use MediatR when its request dispatching and pipeline capabilities provide value to your application.
Don't introduce it simply because you're using CQRS.
7. When Should We Introduce Separate Read and Write Databases?
Now consider a much larger application.
Suppose your system processes a high volume of orders while also supporting expensive reporting and analytics queries.
The workload may have very different read and write requirements.
At this point, separate read and write databases might become useful.
Architecture with Separate Databases
ASP.NET Core API
|
Application Layer
|
+-----------+-----------+
| |
Commands Queries
| |
v v
Write Database Read Database
|
| Replication / Events
+---------------------->|The write database remains the source of truth.
Changes are propagated to the read database using an appropriate replication or event-driven mechanism.
The read database can be optimized for specific query patterns.
But What New Problems Does This Introduce?
Data synchronization: Changes must be reliably propagated between the databases.
Eventual consistency: A user might place an order and temporarily not see it in their order history.
Failure handling: Replication or event processing can fail and require retries.
Operational overhead: More infrastructure, monitoring, backups, and deployment complexity.
Data recovery: The system needs a strategy to rebuild or reconcile read models.
These are real engineering costs.
A separate read database should solve a measurable problem, not simply make the architecture appear more advanced.
8. CQRS with One Database vs. Two Databases
Consideration | One Database | Separate Databases |
|---|---|---|
Read/write code separation | Yes | Yes |
Infrastructure complexity | Lower | Higher |
Data synchronization | Not required between stores | Required |
Eventual consistency | Not inherently introduced | Often introduced |
Independent database scaling | Limited | Possible |
Operational cost | Usually lower | Usually higher |
Read model optimization | Possible through queries and indexes | Additional storage-level flexibility |
Best suited for | Many business applications | Workloads needing stronger read/write isolation |
One database doesn't prevent you from using CQRS effectively.
And two databases don't automatically make a system faster.
9. Common CQRS Mistakes Developers Should Avoid
Mistake 1: Assuming CQRS Requires Microservices
CQRS can be implemented inside a modular monolith or a single ASP.NET Core application.
Microservices are not a prerequisite.
Mistake 2: Creating Separate Databases Too Early
Introducing replication, messaging, and eventual consistency before they're needed can increase maintenance costs without delivering meaningful benefits.
Mistake 3: Using the Same Models for Every Operation
CQRS becomes less useful if command and query paths are separated only by class names while retaining unnecessarily coupled models.
Design each model around its use case.
Mistake 4: Overengineering Simple CRUD
Not every endpoint needs multiple handlers, validators, abstractions, and mapping layers.
For a simple CRUD application, traditional services may be easier to maintain.
Mistake 5: Ignoring Transaction Boundaries
Commands that update multiple related records must preserve business consistency.
Use appropriate transactions, concurrency controls, and domain rules.
CQRS doesn't automatically solve transactional consistency problems.
10. Senior .NET Developer Interview Questions
Q1. What problem does CQRS solve?
CQRS separates read and write responsibilities so that each can use models and logic suited to its specific requirements.
This reduces coupling between complex business operations and data retrieval.
Q2. Is a separate database mandatory for CQRS?
No. Commands and queries can use the same SQL Server database while maintaining separate code paths and models.
Q3. What is the difference between CQRS and the Repository Pattern?
CQRS separates read and write responsibilities.
The Repository Pattern abstracts data access behind collection-like interfaces.
They address different concerns and can be used together when appropriate.
Q4. Can we implement CQRS without MediatR?
Yes. CQRS is independent of MediatR and can be implemented using ordinary services and handlers.
Q5. When would you introduce a separate read database?
When measured workload requirements justify independent read scaling, specialized read models, or workload isolation, and the application can handle the additional synchronization and consistency complexity.
Q6. Does CQRS improve application performance automatically?
No. CQRS creates opportunities to optimize reads and writes independently, but performance improvements depend on actual implementation choices.
Q7. How would you explain CQRS in your project?
A practical interview answer:
"In our ASP.NET Core application, we separated commands and queries based on their responsibilities. Commands handled validation, business rules, and database updates, while queries focused on efficient data retrieval using EF Core projections and AsNoTracking. We used separate handlers for maintainability while keeping a shared SQL Server database. This allowed us to evolve read and write operations independently without introducing unnecessary data synchronization complexity."
Conclusion
CQRS is not about having two databases.
It's about recognizing that reading data and changing data are different responsibilities.
For many ASP.NET Core applications, separating command and query handlers while using a single SQL Server database provides a useful balance between maintainability and simplicity.
If your application later requires independent read scaling or specialized read models, you can evaluate additional database infrastructure based on actual requirements.
But that decision should be driven by evidence.
Key Takeaway
Start with separate read and write models. Keep one database until you have a clear reason to introduce another.
Good software architecture isn't about using the maximum number of patterns, databases, or services.
It's about solving the right problems with the least unnecessary complexity.
Official and Technical References
Microsoft Learn — CQRS Pattern
https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrsMicrosoft Learn — EF Core Efficient Querying
https://learn.microsoft.com/en-us/ef/core/performance/efficient-queryingMicrosoft Learn — EF Core Tracking vs. No-Tracking Queries
https://learn.microsoft.com/en-us/ef/core/querying/trackingMediatR — GitHub Repository
https://github.com/jbogard/MediatR
#DotNet #ASPNETCore #CQRS #CleanArchitecture #CSharp #EntityFrameworkCore #SQLServer #SoftwareArchitecture #BackendDevelopment #SystemDesign #Microservices


Join the conversation! Your thoughts help the community grow.