| Multi Tenant Architecture :👈 | 👉:Domain-Driven Design (DDD) |
Implementing CQRS and Event-Driven Architecture in ASP.NET Core |
Implementing CQRS and Event-Driven Architecture in ASP.NET Core
1. Introduction
CQRS (Command Query Responsibility Segregation) and Event-Driven Architecture (EDA) are architectural patterns used to build scalable, maintainable, and loosely coupled applications.
CQRS separates operations that modify data from operations that retrieve data. Event-Driven Architecture allows different components or services to communicate through events without directly depending on each other.
They can be implemented independently or combined to build distributed applications and microservices.
2. What is CQRS?
CQRS stands for Command Query Responsibility Segregation.
It separates application operations into two categories:
- Command: Changes application state. Examples: CreateOrder, UpdateCustomer, CancelOrder.
- Query: Retrieves information without changing application state. Examples: GetOrder, GetCustomer, GetOrderHistory.
Traditional CRUD Architecture
In a traditional CRUD application, the same model and data access layer are generally used for both reading and writing.
Controller
|
v
Service
|
v
Repository
|
v
Database
CQRS Architecture
In CQRS, commands and queries have separate processing paths. They may still use the same database. or different databases.
CQRS Architecture Diagram Using SVG
4. What is Event-Driven Architecture?
Event-Driven Architecture is a software architecture in which components communicate by publishing and consuming events.
An event represents something that has already happened in the application.
Examples:
- OrderCreated
- PaymentCompleted
- CustomerRegistered
- OrderShipped
- InventoryUpdated
Important Components
- Event Producer: Component that publishes an event.
- Event Broker: Middleware that transports events. Examples: RabbitMQ, Azure Service Bus, Apache Kafka.
- Event Consumer: Component that receives and processes events.
- Event Handler: Code responsible for processing a particular event.
5. Event-Driven Architecture SVG Diagram
6. Combining CQRS and Event-Driven Architecture
CQRS and Event-Driven Architecture complement each other.
- CQRS separates commands and queries.
- Event-driven communication distributes business events.
- Events can update read models, notify other services, or initiate background processing.
Example: E-Commerce Order Processing
Consider an e-commerce application where a customer places an order.
- Customer sends a CreateOrder command.
- CreateOrderHandler validates and saves the order.
- The application publishes an OrderCreated event.
- Inventory Service receives the event and updates stock.
- Notification Service receives the event and sends an order confirmation.
- Read-model handler updates the order summary used by queries.
7. Combined CQRS and Event-Driven Architecture SVG Diagram
8. Implementing CQRS in ASP.NET Core
One common approach is to use MediatR to dispatch commands and queries to their respective handlers.
Step 1: Install NuGet Packages
dotnet add package MediatR
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Use package versions compatible with your .NET target framework and follow the current MediatR registration API.
Step 2: Create the Order Entity
public class Order
{
public int Id { get; set; }
public string CustomerName { get; set; } = "";
public decimal TotalAmount { get; set; }
public string Status { get; set; } = "Pending";
}
Step 3: Create the DbContext
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Order> Orders => Set<Order>();
}
Step 4: Create a Command
A command represents an operation that changes application state.
using MediatR;
public record CreateOrderCommand(
string CustomerName,
decimal TotalAmount
) : IRequest<int>;
The command contains the information required to create an order.
Step 5: Create a Command Handler
using MediatR;
public class CreateOrderHandler
: IRequestHandler<CreateOrderCommand, int>
{
private readonly AppDbContext _context;
public CreateOrderHandler(AppDbContext context)
{
_context = context;
}
public async Task<int> Handle(
CreateOrderCommand request,
CancellationToken cancellationToken)
{
var order = new Order
{
CustomerName = request.CustomerName,
TotalAmount = request.TotalAmount,
Status = "Pending"
};
_context.Orders.Add(order);
await _context.SaveChangesAsync(cancellationToken);
return order.Id;
}
}
The handler receives the command, creates an order, saves it, and returns its ID.
Step 6: Create a Query
using MediatR;
public record GetOrderQuery(int OrderId)
: IRequest<OrderDto?>;
public record OrderDto(
int Id,
string CustomerName,
decimal TotalAmount,
string Status
);
Step 7: Create a Query Handler
using MediatR;
using Microsoft.EntityFrameworkCore;
public class GetOrderHandler
: IRequestHandler<GetOrderQuery, OrderDto?>
{
private readonly AppDbContext _context;
public GetOrderHandler(AppDbContext context)
{
_context = context;
}
public async Task<OrderDto?> Handle(
GetOrderQuery request,
CancellationToken cancellationToken)
{
return await _context.Orders
.AsNoTracking()
.Where(x => x.Id == request.OrderId)
.Select(x => new OrderDto(
x.Id,
x.CustomerName,
x.TotalAmount,
x.Status))
.FirstOrDefaultAsync(cancellationToken);
}
}
Notice that the query uses AsNoTracking() because it only reads data and does not need EF Core change tracking.
Step 8: Register MediatR and DbContext
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddMediatR(configuration =>
configuration.RegisterServicesFromAssembly(
typeof(CreateOrderHandler).Assembly));
var app = builder.Build();
app.MapControllers();
app.Run();
Step 9: Create an API Controller
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly IMediator _mediator;
public OrdersController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> Create(
CreateOrderCommand command)
{
var orderId = await _mediator.Send(command);
return CreatedAtAction(
nameof(GetById),
new { id = orderId },
new { id = orderId });
}
[HttpGet("{id:int}")]
public async Task<IActionResult> GetById(int id)
{
var order = await _mediator.Send(
new GetOrderQuery(id));
if (order is null)
return NotFound();
return Ok(order);
}
}
Important: In a production application, use separate request DTOs for HTTP input rather than binding API requests directly to internal command types. Add validation and authorization as appropriate.
9. Implementing Event-Driven Architecture
After creating an order, the application can publish an event so that other components can react to it.
Step 1: Define an Event
An event describes something that has already happened. It should generally be immutable.
public record OrderCreatedEvent(
int OrderId,
string CustomerName,
decimal TotalAmount,
DateTime OccurredAtUtc
);
Step 2: Create an Event Publisher Abstraction
public interface IEventPublisher
{
Task PublishAsync<TEvent>(
TEvent eventMessage,
CancellationToken cancellationToken)
where TEvent : class;
}
This abstraction prevents business logic from depending directly on a particular message broker.
Step 3: Publish an Event After Creating an Order
For a simple demonstration, the handler can publish an event after saving the order.
public class CreateOrderHandler
: IRequestHandler<CreateOrderCommand, int>
{
private readonly AppDbContext _context;
private readonly IEventPublisher _eventPublisher;
public CreateOrderHandler(
AppDbContext context,
IEventPublisher eventPublisher)
{
_context = context;
_eventPublisher = eventPublisher;
}
public async Task<int> Handle(
CreateOrderCommand request,
CancellationToken cancellationToken)
{
var order = new Order
{
CustomerName = request.CustomerName,
TotalAmount = request.TotalAmount,
Status = "Pending"
};
_context.Orders.Add(order);
await _context.SaveChangesAsync(cancellationToken);
var orderCreatedEvent = new OrderCreatedEvent(
order.Id,
order.CustomerName,
order.TotalAmount,
DateTime.UtcNow
);
await _eventPublisher.PublishAsync(
orderCreatedEvent,
cancellationToken);
return order.Id;
}
}
Production warning: Saving the database record and publishing the event are two separate operations. If the database save succeeds but publishing fails, the order exists without its event being delivered. Use the Transactional Outbox Pattern to address this reliability problem.
10. Event Consumer Example
A consumer receives an event and performs an independent task.
public class OrderCreatedHandler
{
public async Task Handle(
OrderCreatedEvent message,
CancellationToken cancellationToken)
{
Console.WriteLine(
$"Order created: {message.OrderId}");
// Update inventory.
// Send notification.
// Start another business workflow.
await Task.CompletedTask;
}
}
In a real broker integration, the consumer is typically hosted as a background service or implemented using a messaging library. It receives messages, invokes the handler, and acknowledges successful processing.
11. RabbitMQ Example
RabbitMQ is a message broker that supports asynchronous communication between services.
Typical Message Flow
- Order Service creates an order.
- Order Service publishes an OrderCreated message.
- RabbitMQ routes the message to the appropriate queue or queues.
- Inventory Service consumes the message.
- Notification Service consumes the message independently.
For production use, configure durable exchanges and queues, persistent messages, publisher confirms, acknowledgements, retry handling, and dead-letter queues as appropriate.
12. CQRS with Separate Read and Write Databases
In larger applications, the write model and read model can use separate databases.
- Write database: Stores the authoritative application data.
- Read database: Stores data optimized for queries, reports, and dashboards.
- Events: Update the read database when the write-side state changes.
This architecture is useful when read traffic is significantly higher than write traffic or when read queries require specialized data structures.
Read Model Update Flow
Command
|
v
Command Handler
|
v
Write Database
|
v
Outbox Event
|
v
Message Broker
|
v
Projection Consumer
|
v
Read Database
|
v
Query Handler
|
v
API Response
13. Eventual Consistency
When read and write databases are separate, updates to the read database may happen asynchronously.
This means a customer may create an order successfully but not see it immediately in a read-model query.
This behavior is called eventual consistency.
Example:
- 10:00:00 – Order is saved in the write database.
- 10:00:01 – OrderCreated event is published.
- 10:00:02 – Consumer receives the event.
- 10:00:03 – Read database is updated.
The delay depends on the system and workload. Applications should decide how to handle temporarily stale read data.
14. Transactional Outbox Pattern
The Transactional Outbox Pattern ensures that a business update and its corresponding event record are saved in the same database transaction.
Instead of publishing directly to RabbitMQ inside the command handler:
- Save the order.
- Save an event record in an Outbox table.
- Commit both changes in one database transaction.
- A background worker reads pending Outbox records.
- The worker publishes events to the message broker.
- After successful publication, the record is marked as processed.
Transactional Outbox SVG Diagram
Important: The Outbox Pattern normally provides at-least-once delivery, not guaranteed exactly-once processing. Consumers must be idempotent so duplicate messages do not cause duplicate business effects.
15. Idempotency in Event Consumers
A message broker may deliver the same event more than once. An idempotent consumer ensures that processing the same event repeatedly does not repeat its business effect.
For example, an inventory consumer should not deduct stock twice for the same OrderCreated event.
Common approaches:
- Give each event a unique EventId.
- Maintain a ProcessedEvents table.
- Check whether the EventId has already been processed.
- Record successful processing atomically with the business update.
- Use unique constraints to prevent duplicate processing records.
16. CQRS vs Event-Driven Architecture
| Aspect | CQRS | Event-Driven Architecture |
|---|---|---|
| Purpose | Separates reads and writes | Enables event-based communication |
| Main concepts | Commands and queries | Events, producers, consumers, brokers |
| Communication | Often request-response inside an application | Often asynchronous messaging |
| Database | May use one or separate databases | May use multiple service-owned databases |
| Example | CreateOrder and GetOrder | OrderCreated and PaymentCompleted |
| Primary benefit | Independent read/write optimization | Loose coupling and asynchronous workflows |
17. When Should You Use CQRS?
- Applications have complex business operations.
- Read and write workloads have significantly different requirements.
- Reporting queries need different data structures from transactional writes.
- Different read and write models improve maintainability or performance.
18. When Should You Use Event-Driven Architecture?
- Multiple services need to react to the same business event.
- Long-running background tasks should not block HTTP requests.
- Services need asynchronous communication.
- Independent components need to scale separately.
- Business workflows span multiple services.
19. When Should You Avoid Them?
- Small CRUD applications with straightforward business requirements.
- Applications where a simple service and repository architecture is sufficient.
- Systems where immediate consistency is essential and asynchronous processing adds unacceptable complexity.
- Teams without the operational capability to monitor and manage message brokers.
- Projects where the extra infrastructure and maintenance costs outweigh the benefits.
20. Best Practices
- Keep command handlers focused on one business operation.
- Keep query handlers read-only.
- Use DTOs for API responses rather than exposing database entities.
- Use asynchronous operations and cancellation tokens.
- Use the Transactional Outbox Pattern when database changes must reliably produce events.
- Make event consumers idempotent.
- Use retry policies with bounded attempts and appropriate backoff.
- Configure dead-letter queues for messages that cannot be processed.
- Version event contracts carefully.
- Use correlation IDs and distributed tracing to follow requests across services.
- Monitor queue depth, processing failures, event latency, and consumer throughput.
- Avoid introducing separate read databases unless there is a real need.
21. Common Mistakes
- Using CQRS everywhere: It adds complexity and is not necessary for every CRUD operation.
- Publishing events before committing data: Consumers may receive an event for a transaction that later fails.
- Ignoring duplicate messages: Duplicate delivery can cause repeated business operations.
- No dead-letter handling: Poison messages can repeatedly fail without a recovery path.
- Assuming immediate read consistency: Asynchronous projections can temporarily be stale.
- Creating too many event types: Poorly designed events make systems difficult to maintain.
- Putting business logic in controllers: Keep controllers thin and delegate to application handlers.
22. Interview Questions and Answers
Q1. What is CQRS?
CQRS is an architectural pattern that separates commands, which modify data, from queries, which retrieve data.
Q2. What is the difference between a command and an event?
A command requests an operation, such as CreateOrder. An event records something that has already happened, such as OrderCreated.
Q3. What is MediatR?
MediatR is a .NET library that provides in-process message dispatching. It helps send commands and queries to their handlers without controllers directly depending on those handlers.
Q4. Does CQRS require separate databases?
No. CQRS requires separate logical responsibilities for reading and writing. Both models can use the same database.
Q5. What is Event-Driven Architecture?
It is an architecture in which components communicate by publishing and consuming events, often through a message broker.
Q6. What is eventual consistency?
Eventual consistency means that different data representations may temporarily differ but should converge after asynchronous updates are processed.
Q7. What is the Transactional Outbox Pattern?
It stores the business data change and an event record in the same database transaction. A background worker later publishes the event to the broker.
Q8. Why is idempotency important?
Because messages may be delivered more than once. Idempotency prevents duplicate processing from causing repeated business effects.
Q9. What is the difference between RabbitMQ and Kafka?
RabbitMQ is commonly used as a message broker with flexible routing and work queues. Kafka is a distributed event streaming platform designed for durable, partitioned event logs and high-throughput streaming.
Q10. Can CQRS and Event-Driven Architecture be used together?
Yes. CQRS handles read and write separation, while events communicate changes to other components and can update read models.
Q11. What is a projection in CQRS?
A projection transforms events or source data into a read-optimized representation used by query handlers.
Q12. What is a dead-letter queue?
A dead-letter queue stores messages that could not be processed successfully after the configured delivery or retry policy.
Q13. What is the difference between MediatR and RabbitMQ?
MediatR dispatches messages within the same application process. RabbitMQ enables communication between separate processes or services through a broker.
Q14. What is a saga?
A saga coordinates a long-running business transaction across multiple services using a sequence of local transactions and compensating actions when necessary.
Q15. Is CQRS the same as Event Sourcing?
No. CQRS separates read and write responsibilities. Event Sourcing stores changes as a sequence of events and reconstructs state by replaying them. They can be used together, but neither requires the other.
23. Final Summary
- CQRS: Separates commands and queries.
- MediatR: Dispatches commands and queries inside a .NET process.
- Event-Driven Architecture: Allows components and services to communicate through events.
- RabbitMQ / Kafka: Provide messaging and event transport capabilities.
- Transactional Outbox: Reliably records events alongside database changes.
- Idempotency: Protects consumers against duplicate message processing.
- Eventual Consistency: Allows asynchronous read-model updates.
The key idea is to use CQRS when separating read and write responsibilities provides a real benefit, and use event-driven communication when components need to react to changes asynchronously and independently.
| Multi Tenant Architecture :👈 | 👉:Domain-Driven Design (DDD) |