# CQRS (Command Query Responsibility Segregation)

CQRS is an architectural pattern that separates the data structures (models) used for reading information from those used for writing information.

## 1. The Problem with CRUD

In traditional CRUD (Create, Read, Update, Delete) architectures, the same entity model is often used for both database operations and presenting data to the user.
*   **Mismatch:** The data required by the UI (Read) is often different from the data stored in the database (Write).
*   **Performance:** Complex queries might require joining multiple tables, slowing down the system, while writes might be simple.

## 2. The Solution: Segregation

CQRS splits the application into two distinct sides:

### The Command Side (Write)
*   **Responsibility:** Handles business logic, validation, and state changes.
*   **Input:** Commands (e.g., `BookHotelRoom`, `CancelOrder`).
*   **Output:** Void (or success/failure status), but **no data**.
*   **Optimization:** Optimized for transactional integrity and write throughput.

### The Query Side (Read)
*   **Responsibility:** Handles data retrieval.
*   **Input:** Queries (e.g., `GetRoomAvailability`, `FindOrders`).
*   **Output:** Data Transfer Objects (DTOs).
*   **Optimization:** Optimized for read speed (often denormalized).

## 3. Levels of Implementation

1.  **Code Level:** Separate classes for Commands and Queries, but they talk to the same database.
2.  **Database Level:** Separate databases for Read and Write. The Read DB is updated asynchronously (Eventual Consistency).

## 4. Benefits

*   **Independent Scaling:** Scale the Read side (100 instances) separately from the Write side (2 instances).
*   **Security:** Ensure only the right people can perform specific Commands.
*   **Simplicity:** Complex validation logic is removed from Read models.

## 5. Challenges

*   **Complexity:** Requires more code and infrastructure.
*   **Eventual Consistency:** If using separate databases, the Read model might be slightly out of date.

[[programming/event-driven-architecture]]
[[programming/domain-driven-design]]
[[programming/microservices-architecture]]