25 - CQRS: Command-Query Responsibility Segregation
CRUD isn’t the only way! Lance and JS talk about how separating reads from writes in your domain models can open up a world of possibilities.
CQRS (Command-Query Responsibility Segregation)
- Conceptual model where we can Create, Read, Update, and Delete a record in a datastore for that model.
- At it’s simplest: using a different model or service from writing and reading information.
It’s taking CRUD and turning it into R CUD
- This allows for multiple differents representations of data, sometimes simultaneously. Different access patterns depending on the domain.
- For very complex use cases, having the same conceptual model for commands and queries makes things more difficult to follow and requires compromises for both these queries and commands.
- Much more flexible. Eg. Reads could be run on a completely separate physical server.
Most people take it a few steps further
- Update and read models are separate but are no longer backed by the same table or datastore.
- Allows independent scaling, access patterns and optimization strategies for reads and writes
- Allows complex modeling like reads which depend on multiple models, collapsing multiple writes into a single read, read from different models based on complex validation, etc.
- Requires some sort of propagation from write system to read system
- More complexity and maintenance (eg. multiple models to know about)
- If using separate tables or databases, achieving full consistency becomes less straight-forward and can lead to resorting to eventual consistency instead.
- Highly available, but not guarantees around safety.
- Fits well with event-based programming models, event collaboration, event sourcing