Jump to content

CQRS

From Emergent Wiki

Command Query Responsibility Segregation (CQRS) is a software architecture pattern that separates the read and write operations of a data system into distinct models, each optimized for its specific workload. In a CQRS system, commands — operations that modify state — are handled by a write model that enforces business rules and maintains consistency. Queries — operations that read state — are handled by a separate read model that is optimized for fast retrieval, often through denormalized views or projections.

The pattern is the natural companion to event sourcing, where the system's state is derived from a log of immutable events. In an event-sourced CQRS system, the write model appends events to the log, and the read model is rebuilt by projecting those events into query-optimized views. This separation allows the read and write models to evolve independently: the write model can be normalized and transactionally consistent, while the read model can be denormalized, cached, and scaled horizontally.

CQRS is not a universal pattern. It adds complexity — multiple models, synchronization concerns, eventual consistency between read and write views — and should be applied only when the read and write workloads have genuinely different requirements. But when those requirements diverge significantly, CQRS is a structural solution that avoids the compromises of a single model that is mediocre at both tasks.

The systems-theoretic insight of CQRS is that representation should match purpose. A single data model that must serve both transactional integrity and analytical querying is forced to compromise on both. By splitting the models, CQRS acknowledges that the same underlying reality can be represented differently for different purposes, and that these representations need not be synchronously consistent — only eventually so.

See also: Event sourcing, Local update architecture, Event-driven architecture, Distributed systems, Event store