Aggregates Design in DDD
What’s an aggregate?
An aggregate is a group of entities in our domain that needs to be treat in an atomic way. That means that every action in that group of entities must be transactional.
That constraint add some complexity to our design so we have to be sure it’s worth it. In the following sections we’ll see how we could know it.
The aggregate is formed by an aggregate root and could also include several child entities.
That’s the entity that works as entry point of any action in our aggregate. That’s very important since doing so we can reach transactionality in an easy manner.
That also means that in aggregate we should just have one single repository which will be the one that handles the aggregate root.
Then we can have several child entities that will be placed inside the aggregate root as a single instance or a collection of them.
We won’t have a repository to get just child entities, all this will be handled by the aggregate root.
How to know if a group of entities should form an aggregate
To know if we have to create an aggregate we have to look for invariants or business rules that makes very clear that we need that transaction when working with this group of entities.
If we don’t have a clear invariant we should try to deal with eventual consistency to gain simplicity since if we start creating big aggregates our system will end up being slow and hard to maintain so the size of our aggregates must be very concrete.