In this blog we will talk about, What is CQRS and Why the requirement of using CQRS occurs.
CQRS stands for Command, Query, Responsibility Segregation.
As we know Segregation means
1. Separating a Microservice for each logic business operation from a Monolith.
2. In same way, Segregate the read side from the write side.
This helps in increasing the performance, scalability, and security.
A project is basically treated as a CRUD in which we can create, read, update and delete some records present in the database. In this our main focus is on interacting with the database. But we need more sophisticated way of designing our data so we can easily retrieve the data and in case of update we can apply some validation techniques by which the validation of specific user can be tested.
In this way when the user wants to retrieve some data from the database and when some updation is being performed we may use only one Data Transfer Object(DTO) which is good for basically small Business Logic project but when the complexity of the project will increase it becomes difficult to manage or we can say it becomes complex in terms of conceptual representation.
CRUD has some disadvantages
- Same DTO is used for both reading and writing so mismatch can occur between the representation of data. In such a case we may need to maintain operation for this which is basically not a part of our main function.
- It risks data connection when multiple users are reading and updating the data simultaneously then concurrency conflict can occur.
CQRS is the solution to this, in which we split the Model in two parts:-
1. Query Model
2. Command Model (CommandQuery separation).
CQRS has some advantages
1. CQRS is used to handle complex queries by dividing the data store into two parts (read and write ),which increase the performance and increase scalability also.
2. Typical approach to deploy eventual consistency is to use event sourcing in conjunction with CQRS. So that the write model is an append-only stream of events driven by the execution of commands.
If your domain is not suited for CQRS but still u have some complex queries or performance problems. In such case few part which is easy to handle by RDBMS is being handled by RDBMS itself and which part is not handled by RDBMS that only part can use CQRS to handle it.
In CQRS we may have two things:
EagerReadDerivation:- Much of the logic is needed when you are updating so it may make sense to use EagerReadDerivation to simplify your query-side models.
EventPosters:- It makes an MemoryImages which can be used to allow for reading so that there will be less interaction with database, this is best suitable when update query increases so interaction with the database is must in that case.
Hope this blog will help you.