Pragmatic CQRS: Verifying username uniqueness when registering a new user

Introduction

Most people who get started with CQRS have issues with this classical example: "how do we verify username uniqueness when a new user registers ?".

While user authentication is something that has been implemented numerous amounts of times before, and one should usually not reinvent the wheel but use an existing software library for this particular case, the problem in itself is rather interesting, and happens quite a lot in a domain.

In this small article I will show you a simple proper way to resolve the issue respecting CQRS/DDD principles.


Is that really what we want ?

Let us think about another way to solve the issue. I will rewrite the scenario a little bit:


Great, now we have a pending registration ! How is that helpful ?

Not so quick! I have a rule of thumb: whenever I have to communicate between different AR's (even the ones of the same AR type), I use a saga. What is uniqueness validation when you think about it ? Exactly !! A question to all the other AR's whether an entity with the same properties exists. So let us have a second scenario for the saga:

Please note that scenario's for sagas are a little different:


Example code


Conclusion

There you have it, a simple and elegant solution to a problem everybody struggles with in the beginning.

Bookmark and Share