What Is CQRS?
Command Query Responsibility Segregation
CQRS separates read and write operations into different models. Commands (writes) use a model optimized for validation and business rules. Queries (reads) use a model optimized for data retrieval. This allows independent scaling and optimization of reads vs writes.
How CQRS Works
An e-commerce system: write model validates orders, applies business rules, stores normalized data. Read model denormalizes into views optimized for display — order history, dashboards, search results. The read model is updated asynchronously when the write model changes.
Key Concepts
- Commands — Operations that change state — CreateOrder, UpdateProfile, CancelSubscription
- Queries — Operations that return data without side effects — GetOrderHistory, SearchProducts
- Separate Models — Write model enforces rules; read model optimizes display — different schemas for different needs
Frequently Asked Questions
When is CQRS worth it?
When read and write patterns differ significantly — complex write validation but simple read queries, or when you need to scale reads independently from writes. Overkill for simple CRUD apps.