| REST vs gRPC :👈 | 👉:Repository Pattern vs direct EF Core |
CQRS vs CRUD |
CQRS vs CRUD
CQRS (Command Query Responsibility Segregation) and CRUD (Create, Read, Update, Delete) describe different approaches to handling data in an application.
CRUD describes the four basic operations performed on data. CQRS is an architectural pattern that separates operations that change data from operations that read data.
Key point: CRUD and CQRS are not direct alternatives. An application can use CRUD operations within a CQRS architecture.
1. What Is CRUD?
CRUD stands for:
- Create: Add new data.
- Read: Retrieve existing data.
- Update: Modify existing data.
- Delete: Remove data.
CRUD is the most common approach for applications that perform straightforward data operations.
Example: Product Management
Consider an ASP.NET Core application that manages products.
The application exposes operations such as:
| Operation | HTTP Method | Example Endpoint |
|---|---|---|
| Create | POST | /api/products |
| Read | GET | /api/products/101 |
| Update | PUT | /api/products/101 |
| Delete | DELETE | /api/products/101 |
Example CRUD implementation in C#
public class ProductService
{
private readonly AppDbContext _db;
public ProductService(AppDbContext db)
{
_db = db;
}
public async Task<Product?> GetByIdAsync(int id)
{
return await _db.Products.FindAsync(id);
}
public async Task<Product> CreateAsync(Product product)
{
_db.Products.Add(product);
await _db.SaveChangesAsync();
return product;
}
public async Task<bool> UpdateAsync(Product product)
{
var existing = await _db.Products
.FindAsync(product.Id);
if (existing is null)
return false;
existing.Name = product.Name;
existing.Price = product.Price;
await _db.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteAsync(int id)
{
var product = await _db.Products.FindAsync(id);
if (product is null)
return false;
_db.Products.Remove(product);
await _db.SaveChangesAsync();
return true;
}
}
Note: This is a simplified example. Production implementations should also consider validation, authorization, concurrency, and error handling.
Advantages of CRUD
- Simple to understand and implement.
- Less architectural complexity.
- Easy to maintain for straightforward business applications.
- Works well with relational databases and standard ORM tools such as Entity Framework Core.
- Supports transactional operations using the database's normal transaction mechanisms.
Limitations of CRUD
- Read and write operations may become tightly coupled in a large application.
- Complex business workflows can become difficult to organize if all operations are implemented as generic data updates.
- Read-heavy and write-heavy workloads may have different scaling requirements.
- Complex read screens may require queries that differ significantly from the structure used to update data.
These are potential challenges, not inevitable problems. A well-designed CRUD application can handle substantial workloads without CQRS.
2. What Is CQRS?
CQRS stands for Command Query Responsibility Segregation.
It separates the application logic for changing data from the application logic for retrieving data.
- Command: Requests a change to application state.
- Query: Requests data without changing application state.
Commands and queries have different responsibilities, and they can use different code paths or models.
How CQRS works
The diagram shows a CQRS architecture with separate read and write data stores. This is one possible implementation, not a requirement of CQRS.
CQRS can use a single database while keeping command and query responsibilities separate in the application code.
Example: Product Management using CQRS
Instead of calling a generic service to update a product, the application sends a specific command:
To retrieve product information, the application uses a separate query:
The command expresses the intention to change data, while the query describes the information required.
Example command in C#
public record UpdateProductCommand(
int Id,
string Name,
decimal Price);
public class UpdateProductCommandHandler
{
private readonly AppDbContext _db;
public UpdateProductCommandHandler(AppDbContext db)
{
_db = db;
}
public async Task Handle(
UpdateProductCommand command)
{
var product = await _db.Products
.FindAsync(command.Id);
if (product is null)
throw new InvalidOperationException(
"Product not found.");
if (command.Price < 0)
throw new ArgumentException(
"Price cannot be negative.");
product.Name = command.Name;
product.Price = command.Price;
await _db.SaveChangesAsync();
}
}
Example query in C#
public record GetProductByIdQuery(int Id);
public record ProductDto(
int Id,
string Name,
decimal Price);
public class GetProductByIdQueryHandler
{
private readonly AppDbContext _db;
public GetProductByIdQueryHandler(AppDbContext db)
{
_db = db;
}
public async Task<ProductDto?> Handle(
GetProductByIdQuery query)
{
return await _db.Products
.AsNoTracking()
.Where(p => p.Id == query.Id)
.Select(p => new ProductDto(
p.Id,
p.Name,
p.Price))
.FirstOrDefaultAsync();
}
}
The examples use separate command and query handlers but share the same database. This is CQRS without separate read and write databases.
Advantages of CQRS
- Separates business operations that change state from operations that retrieve data.
- Allows commands to enforce business rules explicitly.
- Allows queries to use read-optimized projections or DTOs.
- Can support independent scaling of read and write components when the architecture requires it.
- Can simplify complex business workflows by representing actions as meaningful commands.
- Can support different read and write data models.
Limitations of CQRS
- Introduces more classes, handlers, and architectural concepts.
- May increase development and maintenance effort.
- Separate read and write stores can introduce data synchronization complexity.
- Asynchronous projections can cause eventual consistency, where reads temporarily return older data.
- Requires careful monitoring, error handling, and retry strategies in more distributed implementations.
3. CQRS vs CRUD: Key Differences
| Aspect | CRUD | CQRS |
|---|---|---|
| Meaning | Create, Read, Update, Delete | Command Query Responsibility Segregation |
| What it describes | Basic data operations | An architectural pattern separating reads from writes |
| Read/write separation | Not required | Required at the responsibility or model level |
| Application structure | Often organized around entities and data operations | Organized around commands and queries |
| Database requirement | Can use one database | Can use one database or separate read and write stores |
| Read model | Often reads directly from the main data model | Can use a separate read-optimized model |
| Write model | Often uses standard create, update, and delete operations | Uses commands to represent requested state changes |
| Business rules | Can enforce business rules in services or domain logic | Commands provide an explicit place to handle business operations |
| Complexity | Usually lower for simple applications | Can be higher, especially with separate stores and asynchronous updates |
| Scalability | Can scale effectively using conventional techniques | Can enable independent read/write scaling when needed |
| Consistency | Often straightforward with a single transactional database | Can retain strong consistency with one database; separate asynchronous read stores may be eventually consistent |
| Best suited for | Standard business applications and straightforward data management | Complex domains or workloads with distinct read and write needs |
4. Real-World Example: E-Commerce Application
Consider an e-commerce system with product browsing, order placement, payments, inventory, and reporting.
Using CRUD
Product API
|
v
Product Service
|
v
SQL Server
The application uses conventional services and repositories to create, retrieve, update, and delete product records. This is often sufficient for product administration and many basic business requirements.
Using CQRS
The write side handles order placement and business rules, such as validating an order and checking applicable constraints. The read side returns a product catalog or reporting projection optimized for retrieving the required information.
In a more advanced architecture, the read projection might be updated asynchronously from events. In that case, the catalog or report may briefly lag behind the authoritative data.
5. When Should You Choose CRUD?
CRUD is usually a good starting point when:
- The application mainly performs straightforward data operations.
- Read and write requirements are relatively similar.
- The business rules are simple or can be handled cleanly in existing services.
- A single relational database satisfies performance and consistency requirements.
- The team wants to minimize unnecessary architectural complexity.
- The application is an administration portal, directory, inventory tool, or basic business application.
Example: An employee management application that creates employee records, displays employee details, updates contact information, and deletes obsolete records may not need CQRS.
6. When Should You Choose CQRS?
CQRS may be appropriate when:
- Read and write operations have substantially different performance requirements.
- Commands involve complex business rules or workflows.
- Read screens require projections combining data from multiple sources.
- Read and write components need independent scaling.
- Different models are useful for transactional updates and reporting.
- The architecture benefits from explicit command and query boundaries.
Example: A banking or booking system may have complex state-changing operations and numerous read models for account summaries, operational dashboards, and reports. CQRS can help separate those responsibilities, although it does not replace appropriate transaction and consistency controls.
7. Does CQRS Require Microservices?
No. CQRS can be implemented within a monolithic application or within individual microservices.
- Monolith: Separate command and query handlers within one application and one database.
- Microservices: Use command and query separation inside a service, with optional independent read stores.
- Distributed CQRS: Separate write and read models across components, potentially using messaging and asynchronous projections.
Do not introduce microservices, message brokers, or separate databases solely because you are implementing CQRS. Add those components only when the requirements justify them.
8. Does CQRS Require Event Sourcing?
No. CQRS and Event Sourcing are different patterns that can be used independently.
- CQRS: Separates command responsibilities from query responsibilities.
- Event Sourcing: Stores state changes as a sequence of events from which application state can be reconstructed.
An application can use CQRS with ordinary SQL tables and updates. It can also use Event Sourcing without adopting a fully separated CQRS architecture, although the two patterns are frequently combined in advanced systems.
9. CQRS and MediatR in ASP.NET Core
MediatR is a .NET library commonly used to dispatch requests to handlers. It can help organize CQRS commands and queries, but it does not implement CQRS automatically.
For example:
CreateProductCommandrequests the creation of a product.UpdateProductCommandrequests a product update.GetProductByIdQueryretrieves one product.GetProductsQueryretrieves a collection of products.
MediatR can reduce direct coupling between controllers and handlers. However, for a small application, straightforward services may be simpler and easier to maintain.
10. Common Mistakes to Avoid
- Using CQRS everywhere: Simple CRUD screens often do not benefit enough to justify the added complexity.
- Assuming CQRS requires two databases: Separate command and query responsibilities can share one database.
- Confusing CQRS with Event Sourcing: They are separate patterns.
- Assuming CQRS automatically improves performance: Performance depends on the implementation and workload.
- Adding a message broker without a requirement: A single-database CQRS implementation can work without messaging.
- Ignoring eventual consistency: If read projections update asynchronously, the application must handle potentially stale reads.
- Creating unnecessary abstractions: Use commands and queries to clarify responsibilities, not merely to create more classes.
11. Quick Decision Table
| Requirement | Recommended Approach |
|---|---|
| Simple create, read, update, and delete operations | CRUD |
| Small administration application | CRUD |
| Complex business commands and workflows | Consider CQRS |
| Read and write workloads need different scaling | Consider CQRS |
| Read projections differ significantly from the write model | Consider CQRS |
| Strong consistency with one relational database | CRUD or CQRS with a shared database |
| Asynchronous reporting and read projections | Consider distributed CQRS if the complexity is justified |
12. Final Recommendation
Start with CRUD when it satisfies the application's requirements. It is simple, maintainable, and often sufficient for ordinary business applications.
Introduce CQRS when separating state-changing operations from read operations provides a clear benefit, such as clearer business workflows, specialized read models, or independent scaling.
You can begin with CQRS in a single application and a single database, then introduce separate read stores or asynchronous messaging only when needed. This avoids unnecessary complexity while preserving room for architectural evolution.
13. Interview Answer
CQRS vs CRUD: CRUD represents the four basic data operations: Create, Read, Update, and Delete. CQRS is an architectural pattern that separates commands, which change application state, from queries, which retrieve data. CRUD is often sufficient for straightforward business applications, whereas CQRS can help when read and write requirements differ significantly or when business commands and read models become complex. CQRS does not require separate databases, microservices, or Event Sourcing. I would choose the simplest approach that meets the application's business, performance, and maintainability requirements.
| REST vs gRPC :👈 | 👉:Repository Pattern vs direct EF Core |