Introduction to CQRS — In Microservices
--
Are you dealing with an application that involves complex business logic?
If that’s the case, then Command and Query Responsibility Segregation (CQRS) architectural pattern might be the solution you were looking for.
In recent years the focus on improving user experience has been notable -
The way users perceive applications has changed enormously.
Nowadays, users expect applications to be lighting fast, especially when performing queries.
The problem is that as applications become more complex, the handling of detailed queries and validation rules also grows in complexity. In this type of scenario, the conventional Create, Read, Update, and Delete (CRUD) data model could become cumbersome to implement and maintain.
In this article, Introduction to CQRS, we will explore the principles behind the CQRS pattern, as well as its pros and cons, to assist you in deciding whether or not the CQRS pattern is right for your project.
How CQRS works
The best way to illustrate how CQRS works is with an example. Let’s say you are designing a simple todo application — Following the traditional CRUD data model, you may implement a service in charge of creating, listing, updating, and deleting tasks. A simple solution that reads/updates the data store.
The Command and Query Responsibility Segregation (CQRS) pattern propose separating the write data model from the read data model. This separation of responsibilities would provide the flexibility to decide whether the read and write services should coexist in the same data store or be managed in completely different databases.
In the CQRS context, commands are methods whose sole purpose is performing an action. Simply put, commands in our example would be responsible for creating, updating, and deleting tasks (write operations). In the CQRS architecture, commands cannot return data, since that functionality is unique to queries. In that regard, queries are methods that are only able to read and return data without modifying it. Therefore, in our example queries would perform read-only operations such as listing tasks or returning the status of a particular task.