CQRS
Command Query Responsibility Segregation
In short
CQRS is an architectural pattern that separates the code that changes data, called commands, from the code that reads data, called queries, into two models.
What is CQRS?
CQRS, short for Command Query Responsibility Segregation, splits an application's operations into two sides. Commands change state, such as PlaceOrder or ChangeAddress, and return little or nothing; queries read state, such as fetching an order history, and never change anything. Each side gets its own model, designed for its own job.
The write model focuses on business rules and validation, while the read model is shaped for fast, convenient display, often as pre-joined, denormalized views. In simple setups both sides use the same database with different code paths. In more advanced setups the read side has its own database or tables, kept up to date by events published from the write side, which means reads can lag slightly behind writes, a property known as eventual consistency.
An analogy is a restaurant: orders go to the kitchen, which follows strict rules to prepare each dish, while guests read a printed menu that is designed for quick browsing. CQRS is useful when reads vastly outnumber writes, when reading and writing need very different data shapes, or in complex business domains, and it is often combined with event sourcing and domain-driven design.
CQRS is often contrasted with CRUD, where a single model and one set of tables handle create, read, update, and delete operations alike. CRUD is simpler and is the right default for most applications, while CQRS adds extra code, more moving parts, and possible lag between writes and reads. CQRS is also different from event sourcing, which stores every change as an event: the two work well together, but either can be used without the other.
Key takeaways
- Commands change data; queries read data and never change it.
- Each side has its own model, optimized for its purpose.
- The read side can use separate, denormalized views or databases.
- Separate read stores are often eventually consistent with the write side.
- Use CQRS where it clearly helps; plain CRUD is simpler for most apps.
Example
// Command side: validates business rules and changes state
async function placeOrder(cmd: { customerId: string; items: string[] }) {
if (cmd.items.length === 0) throw new Error("An order needs at least one item");
const order = await writeDb.orders.insert({ ...cmd, status: "placed" });
await events.publish("order.placed", order); // used to update the read model
}
// Query side: reads from a view shaped for the screen and never changes data
async function getOrderSummaries(customerId: string) {
return readDb.orderSummaries.find({ customerId }); // pre-joined, denormalized
}Readers ask
What is the difference between CQRS and CRUD?
CRUD uses one model for creating, reading, updating, and deleting data. CQRS splits writes and reads into separate models so each can be optimized independently, at the cost of more complexity.
Do you need two databases for CQRS?
No. CQRS only requires separating the command and query models in your code. Using separate read and write databases is an optional step for systems that need to scale reads or store data in very different shapes.
What is the difference between CQRS and event sourcing?
CQRS separates reading from writing, while event sourcing stores the full history of changes as a sequence of events instead of only the current state. They are often used together, but each can be used on its own.
See also
- Domain-Driven DesignSoftware Architecture, p. 15Domain-driven design is an approach to building software that models the code closely on the business domain, using the same language as the domain experts.
- Event-Driven ArchitectureSoftware Architecture, p. 18Event-driven architecture is a software design style in which services communicate by producing and reacting to events, such as an order being placed.
- DatabaseDatabases, p. 6A database is an organized collection of data stored on a computer, managed by software that lets applications save, search, and update it efficiently.
- MicroservicesSoftware Architecture, p. 27Microservices are an architectural style where an application is split into small, independently deployable services that communicate over a network.
- Separation of ConcernsSoftware Architecture, p. 37Separation of concerns is a design principle that divides a program into distinct parts, each responsible for one clearly defined aspect of its behavior.
Spotted a mistake or something missing on this page?Suggest an edit