CQRS
A pattern that separates read and write operations into distinct models, allowing each to be optimized, scaled, and evolved independently.
Also known as: Command Query Responsibility Segregation, Command-Query Separation Architecture
Category: Software Development
Tags: architecture, software-design, patterns, domain-driven-design, scalability
Explanation
Command Query Responsibility Segregation (CQRS) is an architectural pattern that separates the read (query) and write (command) sides of an application into distinct models. Instead of using the same data model for both reading and writing, CQRS uses one model optimized for updates and another optimized for queries.
**Origins:**
CQRS evolved from Bertrand Meyer's Command-Query Separation (CQS) principle, which states that a method should either change state (command) or return data (query), never both. Greg Young extended this from the method level to the architectural level, creating CQRS as a pattern for entire systems.
**How it works:**
- **Command side (write model)**: Handles commands that change state. The model is optimized for enforcing business rules and maintaining consistency. Often uses domain-driven design patterns (aggregates, entities, value objects)
- **Query side (read model)**: Handles queries that return data. The model is optimized for read performance—denormalized views, materialized projections, or search indexes tailored to specific UI needs
- **Synchronization**: The read model is kept in sync with the write model, typically through domain events (eventually consistent) or database-level mechanisms
**Benefits:**
- **Independent optimization**: Read and write models can use different data stores, schemas, and scaling strategies
- **Simplified models**: Each side focuses on its specific concern, reducing complexity
- **Scalability**: Reads typically outnumber writes 10:1 or more; CQRS allows scaling each independently
- **Performance**: Read models can be pre-computed and denormalized for fast queries
- **Security**: Finer-grained control over who can read versus who can write
**CQRS + Event Sourcing:**
CQRS pairs naturally with event sourcing. The write side produces events, and the read side builds projections from those events. This combination provides both a complete audit trail and optimized read performance, but adds significant complexity.
**When to use:**
CQRS is most valuable when read and write workloads have very different characteristics, when you need different read models for different consumers, or when combined with event sourcing for complex domains. Avoid it for simple CRUD applications where a single model suffices.
Related Concepts
← Back to all concepts