CQRS stands for Command Query Responsibility Segregation. CQRS is an architectural pattern. It says that the data read operation and data write operation should be separated.
Example of bad design without CQRS
- public interface IStudentRepository
- {
- Customer GetById(int studentId);
- Customer GetByEmail(string email);
- int Save(Student student);
- void Delete(Student student);
- }
With CQRS
- public interface IStudentRepositoryRead
- {
- Customer GetById(int studentId);
- Customer GetByEmail(string email);
- }
- public interface IStudentRepositoryWrite
- {
- int Save(Student student);
- void Delete(Student student);
- }
- Reading the data is more frequent than writing. Generally, it is in ratio of 10:1 or sometimes 100:1.
- Reading operation should be fast. A user feels frustrated, if a query takes more than half second.
- The user can tolerate the write operation slowness, as they know that some important action happens in the system.
- Write operation changes the state of system. World looks different before and after the write.
- Read operation wants to retrieve quite a bit of data while writing effects only one or two rows at a time.
- Write operation changes the state. Thus, they have the side effects.
Reading data
Since reading the data should be fast enough, we should make sure of the following.
- The data should be accessed in a manner, which needs least amount of DB queries possible for necessary context only.
- Aggregated data should not be calculated on the fly. Rather it should pre-calculated.
- No business logic should be executing while reading the data. It should execute while writing.
- Read operation should not have any side effect because they do not make any change.
Writing data
- Writing operation should not return any result except the status message (success or failure).
- Write should send the limited set of the data, which is mostly one row at a time to write or update.
Like
- public class AddProductToShoppingCart
- {
- public int ShoppingCartId {
- get;
- set;
- }
- public int ProductId {
- get;
- set;
- }
- public int Quantity {
- get;
- set;
- }
- }
Ketan KokatePosted Oct 3, 2019, 6:57 AM
Nice explain in simple words
Guest UserPosted Aug 2, 2018, 7:59 AM
Nice article
Abhijit KakadePosted May 2, 2017, 10:19 AM
Very nice explained Ahmad. Thank you