Pages

Friday, May 10, 2019

CQRS

Software architecture has evolved a long way from the standard 3 tier architecture. A lot of the previous architectures were optimized for the constraints present at that time like limited resources but with time such restrictions no longer apply.
The most promising of the new architecture is the Domain Centric Architecture which places domain right at the center of the architecture. But more on the domain driven design later.
Another interesting concept is CQRS – Command Query Responsibility Segregation. This is useful for creating a system optimized for performance. The principle is simple, keep the command and query separate.
Command is anything that changes the state of the system on the other hand query requests some information from the system. A query should never alter the state of the system and the command should ideally not return some information. Of-course, a strong distinction is not always possible, a command does often return whether it was successful or not but keeping them separate leads to a lot of benefits.
Code level:
CQRS should be even strived at a code level. A function responsible for fetching some information should never alter the state of the class. As the codebase grows, a public facing getter API can be called from different modules. It’s next to impossible to control that and other modules may not have enough information to identify when a simple get call ended up altering the state of system inadvertently.
Architecture level:
A lot of the features in the software are data-read heavy and usually a smaller set of features in the software actually update the data. If we keep them separate we can scale them independently. The ‘Query’ module having optimized for fast reads and ‘Command’ module optimized for writes. In a little more advanced version of CQRS, both the stacks can have independent databases. Every write into the main database is then synchronized with the database meant for ‘read’. For short duration these databases will be out of sync but this leads to highly performant systems and the performance won’t degrade as you scale the system.
There are downsides of it too. Implementing CQRS makes the architecture complex and should not be used if the performance and scalability are not the primary needs of the software. Also, the query and command stacks will have data which will be out of sync which leads to additional complexity in the system.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.