The best practices of modeling the recursive aggregate ?

Hi,

I’ve been struggling to model a recursive aggregate in recent days .

Let’s say Organization is aggregate and it has sub organizations with the same structure . When adding a new organization, the parent should know the new child . When deleting an organization, all of the children should be deleted.

Basically, there may be 2 options to model the aggregate:

------------Option 1----------------

@Aggregate
public class Organization {
  @AggregateIdentifier @EntityId private String organizationId;

  @AggregateMember private List<Organization> subOrganizations;
}

Question: Deleting the Aggregate will delete it’s member automatically I guess, but which ones are aggregate and which ones are member in a hierarchical relationship ? Is “Sub Organization C” aggregate or member in the following example ?

Organization root [Aggregate]

  • Sub Organization A [Member]
  • Sub Organization B [Member]
  • Sub Organization C [Member]

Or,

Organization root [Aggregate]

  • Sub Organization A [Member]
  • Sub Organization B [Member]
  • Sub Organization C [Aggregate]

------------Option 2----------------

@Aggregate
public class Organization {
  @AggregateIdentifier  private String organizationId;

  private String parentOranizationId;

Hi Sean,

these types of challenges ask for an ‘it depends’ answer :-). I’ll try to give you a bit more guidance.

Both options are valid implementations. Which one makes more sense depends on many details of the problem you’re trying to solve.

How ‘isolated’ does each organization need to be? Modeling them as a single organization hierarchy is simpler, as you automatically know the whole ‘tree’. It does restrict you to address each instance in isolation, though. You will need to always pass the root orgs ID with each command.
If isolation is important, option can help. Build logic that listens for a delete of an org (event handler) and sends commands to delete each org that had that org as a parent. You can use a saga or query model for that.

Hope that makes sense.
Cheers,

Allard

Where would the saga get the list of child organizations? Would it watch for “organization added” events and maintain a list of the parent organization’s children? This feels like it’s duplicating logic within the aggregate. Or would the saga query for all children? Is eventual consistency safe enough to ensure that all child orgs are deleted?

Hi Allard,
Thank you very much for the guidance, I’d controll the organization separately so I choosed to go to option2 .

Hi Joel,
I aggree with you that the logic in Saga seems duplicate with the aggregate . I don’t introduce Saga but sending the DeleteCommand to Organziation via a loop of the children origanizations in the Organziation Aggregate.

Regards,
Sean