There is a common situation that at the point of the creation of an aggregate we need to do a uniqueness check.
For example for the creation of a User
aggregate we want email
fields to be unique across all aggregates (example taken from [1]).
I believe that this problem is a general instance of the larger ‘Set Validation’ problem mentioned in [2]. To resolve the problem we would need “to validate the uniqueness against an immediately consistent datastore” (e.g. database table with unique constraint on the email
column) before dispatching the command [2].
There are many ways to implement this within Axon:
- In [3], Steven Grimm describes “the old-fashioned way” of placing a a constraint on a SQL
table in the query model. - Working with a distributed lock would also work. I think [4] is a good video explaining how to
do this in Spring. - In [5] @allardbz lists techniques you could use including using a 2 step process with a Saga.
- In [6] @Sebastian_Ganslandt1 suggests using “an interceptor that checks the incoming create-commands against this query-model and rejects the command if it contains a duplicate”.
- @Ivan_Dugalic in his answer in [1] wrote that you can also use ‘command side projections’.
If I was trying to solve this using a Saga then could I create a Saga which has @StartSaga
on a @CommandHandler
rather than an @EventHandler
? The saga would then send further commands until finally the last @CommandHandler
(annotated with @EndSaga
) either creates the User
or does not. Using a saga with events does not feel right for this purpose (but using commands seems to make more semantic sense to me).
Or if trying to solve this using ‘command side projections’ how exactly does that work?
- Do we essentially just create a
@Component
which has a@CommandHandler
that as part of
its logic takes some sort of lock and validates the constraint? - How exactly would you implement this?
Are there any code examples illustrating this ‘set validation’ pattern using command side
projections in Axon that I could use to understand?
Regards,
vab2048
[1] Route one command to multiple aggregates
[2] Validating Uniqueness
[3] Validating Uniqueness
[4] https://www.youtube.com/watch?v=firwCHbC7-c
[5] How can I prevent Asynchronous EventHandler handles events that should be rollbacked
[6] Best appoach to pre creation bus rules for aggregate