CQRS && Validation && Business Rules

Validation and business rules within a CQRS architecture [1][2] continue to raise issues for those who first hear of it. Three specific questions are often asked: how does the validation of commands work, how can one enforce business rules on large collections (state) and how does the enforcement of business rules on multiple aggregates work? Hopefully I can help some readers with my three replies. First the questions.

  1. If asynchronous commands to be handled, how can I do the validation on the server and notify the user that validation failed?
  2. How do we enforce business rules that depend on state that is very large. Familiar example: a user must have a unique username.
  3. If aggregates are completely separate, how do we enforce business rules over multiple aggregates?

I wanted to share my ideas, because I think that these questions have proper answers. In a (renewed) attempt to write a short post, here are my three answers:

  1. Make declaratively valid commands. Validate on the client. Ignore non-valid commands on the server. See also [3]
  2. Save this state initially in-memory in a part of the aggregate that represents the scope (see also [4] for an explanation of why there is always some scope). Optimize the state to use out of memory storage when necessary. Using the read database is an extra optimization.
  3. You cannot do this. At least, not in the form of invariants, because those only apply within aggregates. Possible solutions: fuse the aggregates as they appear inextricably linked, check if you do not miss an aggregate specifically enforcing this invariant or send out events from one aggregate to another according to the usual scenario and solve exceptions with compensating actions.

To be brief, this post is stripped of all additional explanation. I can imagine that there are questions that remain, which I would like to hear.


[1] See this post by Mark Nijhof for a clear description of what I mean by “CQRS architecture” 
[2] Greg Young himself says CQRS is not an architecture, I agree. It often is accompanied by one, but it does not have a name for itself yet. Proposal: “Circular Architecture”? 
[3] This is explained nicely in this post by Udi Dahan. Search for “Commands and validation”. 
[4] An explanation can be found in a fine post by Jérémie Chassaing.

Written by Rick | Tags: , |

No Comments - Leave a comment »

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress | Aeros Theme | WordPress Themes

Better Tag Cloud