Search code examples
microservicesdomain-driven-designaggregates

Details about Aggregates and where to use Aggregates


I read many articles and watched videos on youtube about aggregates but every time I am getting more confused by them. So please describe in detail with a specific example. I understood little about that is it is a collection and it can used in DDD(Domain Driven Design) pattern and in identifying microservices boundary. If I am wrong please correct me and describe more about aggregates.

Thanks in advance.


Solution

  • An AGGREGATE is a cluster of associated objects that we treat as a unit for the purpose of data changes. -- Evans, 2003.

    Aggregate is a pattern, that Evans describes in the lifecycle management chapter of the blue book.

    The motivation is that we often have two or more domain entities that must always agree with each other in some way. That will normally mean that we want to save them together (otherwise, a badly timed failure could leave us in a state where the entities are not consistent with each other), and will normally mean that we want to have both entities available in any case where we might change one (because we'll need to make sure that change is consistent with the other).

    See also: Coarse Grained Lock.


    A somewhat contrived example:

    Imagine a system that keeps track of bids for some commodity. Our entity might include a collection of BUY orders (with a price and an amount for each), and a similar collection of SELL orders.

    Our job is to pair off BUY and SELL orders that are close to each other and time and have a common price. So when a new BUY order comes in, either it gets added to the collection of BUY orders, or it is matched against a SELL order, which is removed from the SELL collection.

    In effect, these two collections are managed such that they never overlap. To ensure that property holds, we keep both collections in the same "aggregate", so that they are always saved as a unit, and we are protected from data races that might make the two entities inconsistent with each other.

    Often, this will constrain our data model - for instance, if we are using a document store to hold our domain information, then both of these entities would be represented within the same "document".