CQRS vs Classical n-layer application


When building an API the typical practice is to divide it into parts, simplest would be presentation, service / business logic and data access layers



3-layer architecture


There is nothing wrong with this approach but questions araise when application becomes bloated and unreadable.I prepared simple user’s microservice with basic functionality to make case-study on it. But first things first.


CQS

Must be mentioned before. It stands for Command-query Separation. The simplest explanation would be:


CQS


It separates two main sections of our application. Queries are thoose actions which doesn’t change data (in most cases) and return something whereas commands are those which change data and return nothing (again, in most cases). Most likely that you used it even without knowing it because it’s kinda natural approach to the problem. It allows us to:

  1. Distributed responsibility. When working in team, less experienced developers may receive queries to take care about because they don’t mess up with data.

  2. Clean code. However, this argument is often overused. I’ll explained it later.


CQRS

Command Query Responsibility Segregation, idea presented by Greg Young and Udi Dahan. Let’s stop for a moment. In most modern frameworks we use OOP right? Yeah but where thoose objects can be seen in above diagrams? I’m not talking about singleton pattern, which creates single instance of eg. service class in the app because it serves another purpose and would be cheap answer.


And that’s the problem. Actions in classic CQS are handled by methods in the end. CQRS is handling them by objects, an instance of action class with one or more methods.