Documentation
View infrastructure documentation
Brief Documentation: CQRS Pattern
What is CQRS?
CQRS (Command Query Responsibility Segregation) is an architectural pattern that separates data read operations (Queries) from write and update operations (Commands) into two completely distinct logical and physical models.
The Problem it Solves
In most systems, read and write operations have diametrically opposed performance and consistency requirements. Forcing both flows through the same data model (and the same database) often creates bottlenecks, especially in high-traffic (high-read) systems.
How the Architecture Works
The pattern divides the application into two separate paths:
-
The Write Model (Command Service)
- It is optimized for consistency and business rules.
- It handles validating operations and processing state changes, typically saving data in a transactional database (e.g., Relational DBMS).
-
The Read Model (Query Service)
- It is optimized for throughput (high performance and speed).
- It responds to user requests by reading data from pre-calculated or denormalized stores (e.g., Document DBMS, search engines like a Search Platform, or a Key-Value Cache).
How do the two worlds communicate? (Synchronization)
Since the databases are separated, a mechanism is needed to keep them aligned. Typically:
- When the Command Service makes a change, it publishes an event to a messaging platform (e.g., an Event Topic).
- A dedicated component (called a Projector) listens to these events in real-time and updates the read databases (Read Store) accordingly.