CQRS: Making Software Less Confusing (or More, Depending on Your Perspective)
What is CQRS?
CQRS, short for Command Query Responsibility Segregation, is a fancy way of saying:
“What if we separate the logic that changes data (commands) from the logic that reads data (queries)?”
This pattern is often linked to Martin Fowler (Wikipedia), though Greg Young also played a huge role in its popularization (Wikipedia).
The idea is simple: instead of having one model that does both reading and writing (which is what we usually do), we create two models—one for writes (commands) and one for reads (queries).
Relationship to the Gang of Four Patterns
CQRS is not one of the original Gang of Four patterns (Wikipedia), but it draws inspiration from:
- Command Pattern (Wikipedia): CQRS commands encapsulate a request to change state.
- Observer Pattern (Wikipedia): Often used with CQRS for event sourcing.
- Mediator Pattern (Wikipedia): CQRS can use a mediator to manage communication between commands and queries.
Commands, Queries, Results, and Envelopes
Commands
A command represents an action that modifies the state of the system.
|
|
Queries
A query retrieves data without modifying anything.
|
|
Results
A result is what comes back from a query.
|
|
Envelopes
An envelope wraps commands or queries to add metadata.
|
|
CQRS vs. MVC: The Ultimate Battle
CQRS and MVC (Model-View-Controller) are often compared, so let’s break it down:
Feature | CQRS | MVC |
---|---|---|
Separation of Concerns | Strong separation between commands and queries | Everything handled in one model |
Complexity | Higher (more moving parts) | Lower (easier to grasp) |
Scalability | Very scalable, ideal for distributed systems | Can be hard to scale when reads/writes compete |
Data Consistency | Eventual consistency (when combined with event sourcing) | Immediate consistency |
Learning Curve | Steep | Easy (until you realize you’ve overcomplicated your controllers) |
Key Takeaways
Key Idea | Explanation |
---|---|
CQRS separates read and write models | Commands change state, queries fetch data |
CQRS is influenced by GoF patterns | Uses Command, Observer, and Mediator patterns |
Envelopes wrap data | Adds metadata for tracking |
CQRS vs. MVC | CQRS is great for scalability, MVC is simpler but can get messy |
References
- CQRS: https://en.wikipedia.org/wiki/Command_query_responsibility_segregation
- Martin Fowler: https://en.wikipedia.org/wiki/Martin_Fowler_%28software_engineer%29
- Gang of Four Patterns: https://en.wikipedia.org/wiki/Design_Patterns
- Command Pattern: https://en.wikipedia.org/wiki/Command_pattern
- Observer Pattern: https://en.wikipedia.org/wiki/Observer_pattern
- Mediator Pattern: https://en.wikipedia.org/wiki/Mediator_pattern
- MVC: https://en.wikipedia.org/wiki/Model–view–controller