lundi 7 juin 2021

What exactly is the Aggregate in Event Sourcing?

I really like the concept of event sourcing. To replay specific events to calculate a domain model state is just wonderful.

When i read into Event Sourcing, i am still confused by the term "Aggregate". I understood that the Aggregate as a "Collection of Events related to a specific thing".

Different to this, a "Projection" is a kind of a Event Handler which is called when a event (which is supported by the Projector) is fired. When a event stream is replayed, the Projector may handle this events (again).

An event handler (Projector) can react to an event. For example, there is a ERP Application where the employee can ship, reserve or release a product. If a product is shipped, a new Event called ProductShipped is fired (and persisted to the database). The projector, which acts as the event handler, come into place and decrease the available stock quantity for that product.

The aggregate can act as a validator, if i read correctly. So if i look at all past events related to that product i am able to calculate the quantity. This calculation has to be done before the ProductShipped Event is persisted, and this is where is see the role of an Aggregate.

If i am right, when does the Aggregator show up? In a naive solution, i would inject a ProductStockAggregate into the projector and the projector now has to call it to get information about the available quantity. But this seems weird as the projector has to replay all the events (related to the SKU) just to get this information. Additionally, this seems as a violation to the separations of concerns principle.

In some tutorials i found out that the aggregate itself is the "Source of Control": If the employee ships a product, the application will call the method ProductStockAggregate.shipProduct(productId). This method would replay all past events related to that product and decides if the product is shipable (based on quantity availablity). The decision results in a new event (ProductShipped or ProductQuantityTooLow), which has to be handled by the application. But if this is true, there is also a Separation of Concerns violation as the Aggregate has to know about the events which has to be fired, the product model itself and also the logic to enforce business rules. Looks like a god object.

But I tend to think that I didn't really understand something in particular. Can you help me?

Aucun commentaire:

Enregistrer un commentaire