Tutorials Microservices & Event-Driven Architecture (EDA) Mastery

CQRS (Command Query Responsibility Segregation) with MediatR

On this page

Mastering CQRS

Command Query Responsibility Segregation (CQRS) says that the model used for **Writing** data should be different from the model used for **Reading** data.

1. The "Write side" (Commands)

Optimized for business rules and consistency. This is where your DDD Aggregates live. It usually uses a relational database like SQL Server to ensure ACID compliance.

2. The "Read side" (Queries)

Optimized for the UI. No complex joins. No business logic. Often uses a NoSQL DB like **Elasticsearch** or **Redis** where the data is already pre-formatted for display. This makes 'Read' performance blazing fast, regardless of how complex the 'Write' logic is.

3. MediatR: The Glue

In .NET, we use the **MediatR** library to implement CQRS. It decouples your controllers from your business logic. The controller just sends a 'Command' or 'Query' to MediatR, and MediatR finds the one specific 'Handler' to process it. This leads to **Highly Testable** and **Thin Controllers**.

4. Interview Mastery

Q: "Do I ALWAYS need separate databases for CQRS?"

Architect Answer: "No. You can start with a single database and use CQRS to separate your **Code**. Use one model for updates and an 'AutoMapper' or 'Dapper' projection for reads. Only move to separate databases (and the resulting eventual consistency) when you've hit a performance bottleneck that can't be solved with indexing."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Microservices & Event-Driven Architecture (EDA) Mastery
Course syllabus
1. Foundations of Microservices
2. Communication Patterns
3. Event-Driven Architecture (EDA)
4. Distributed Transactions & Resiliency
5. Observability & Monitoring
6. Security & Identity
7. Infrastructure & Deployment
8. FAANG Microservices Case Studies
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details