Design Patterns (GoF) (50 Qs)•Part 2: Behavioral Patterns & Communication (11 - 24)
What is the CQRS (Command Query Responsibility Segregation) Pattern?
junior LevelCode ExampleBehavioral
In Simple Words: Segregates the data model for write operations (Commands) from the data model for read operations (Queries):
- Command Model: Optimized strictly for validating business rules, transactions, and maintaining invariants (writes to normalized relational DB).
- Query Model: Optimized strictly for fast read performance (denormalized views stored in Elasticsearch, Redis, or read replicas).
- Eliminates the tension of trying to design a single database schema that is optimal for both high-concurrency writes and complex analytical queries.
text
CQRS Architecture:
[User Action]
│
├─► [Command Path] ──► [Domain Model] ──► [Write DB (ACID)]
│ │ (Event Stream / CDC)
│ ▼
└─► [Query Path] ◄── [Read DB (Denormalized Cache / Elastic)]