How to interact with other aggregates (same or different type)

Hi,

I have 2 aggregate roots “A” and “B” which can be linked together (many-to-many). “A” handles the events “created”, “updated”, “deleted”, “addedB” and “removedB”.
“A” maintains a List for linked "B"s. On addB command, it checks that the “B” uuid is not in the list and applies a “addedB” event. In the event handler it adds “B” to it’s list.
On “removeB” command it checks that “B” is on it’s list and fires a removedB event which removes “B” from the list. on “delete” command A fires a “removedB” event for each B in the list and then a “deleted” event.

So far so good. Now i got a new restriction. “A” gets a new attribute “year”. The restriction is: Any “B” must not linked to more than one “A” for a certain year.

To comply with that restriction, I need the following checks:

  1. If a “B” is linked to an “A”, check that the “B” is not linked to a different “A” with the same year.
  2. If I want to change the year of an “A”, check that it is not linked to a “B” that is linked to a different “A” with the same year. Or with other words: chech that no other “A” exists with the same year that is linked to one of the "B"s to which the changed “A” is linked to.

My first approach/mistake was to add a simple check to my DAO - which is the read side. That seemed work (but smelled a bit) and (of course) produces errors for events from the past where the restriction did not already apply.

Another approach would be to move the link handling from “A” to “B” but that brings other problems (like handling changes of “A”'s year).

How can I solve this problem? Can I somehow iterate over all other aggregates “A” during command handling in “A”? Is there a better approach?

Kind regards,
Michael.

Hi,

one way to handle this, is using a saga. It could maintain the relationship between A’s and B’s. When an A is changes to no longer comply with invariants, it can either remove it from B, or ‘reset’ a to the previous year. It depends mostly on domain specific details.
Validating invariants can also be done using a query database. There, you could check if a B is connected to several A’s. In that case, it wouldn’t be possible to change any of these A’s year.

Cheers,

Allard