CQRS (Command Query Responsibility Segregation)
Separate the Write model from the Read model
“We can use different models to update information and read information.” – Greg Young
When to use
Systems with high read/write disparity, or complex domains where the “Read” view is very different from the “Write” structure.
Why it matters
- Optimization: You can scale Reads (MongoDB, ElasticSearch) independently from Writes (PostgreSQL).
- Simplicity: The Write model focuses on complex validation logic. The Read model focuses on returning DTOs quickly.
Signs of Violation
- Using a giant polymorphic “User” class for both massive complex updates and simple “User List” views (loading 50 unused fields).
Explanation
Problem
A single model (e.g., ORM entity) is often too complex because it tries to handle validation rules AND view formatting.
Solution
Split the system.
- Command Side:
CreateUserCommand,UpdateAddressCommand. optimized for transactional integrity. - Query Side:
UserListQuery,UserDetailsQuery. Optimized for speed (maybe querying a denormalized view).
Real world analogy
A library.
- Command: Adding a book involves cataloging, stamping, RFID tagging (Complex process in the back room).
- Query: Searching for a book involves looking at the index cards or computer (Simple read-only view). You don’t interact with the stamping machine to find a book.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- CQS: CQRS is CQS applied to the whole architecture (often separate databases).
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Good (Adherence)