Juan Vega
Juan Vega

Reputation: 1120

How to process aggregates in batch and publish only one event in DDD?

I run into a situation while developing my domain I hope someone can help me solve.

In my current project I need to read from a cache all the stored aggregates of one type (let's say ClientAggregate). I read the aggregates from the service layer and then, for each one of them, I acquire a lock for the current aggregate to do some processing and then save it back. The business logic requires that only one event is sent out with information about the modified aggregates because the system listening to this event is a legacy system and has a schema already defined.

The problem I have is that, because of this locking process, the event I send is sent from the service layer instead of the domain. The logic requires to send information of the aggregates that had been modified all together in one event. Because I need to lock aggregates individually for performance reasons, I cannot pass all the aggregates to a domain service to handle the logic from there and generate the event. My option here would be to lock directly from inside the domain service but then I'd leak infrastructure logic into my domain.

So, in my current solution, the service contains domain logic to iterate through the aggregates and generate the event. Doing it inside a domain service, the logic would be in the domain but the locking mechanism would need to be moved along. A third option would be to publish an event for each modified aggregate but then there should be something able to consume them all, waiting somehow for the whole process to finish, so I don't know if this is even an option.

Upvotes: 2

Views: 1550

Answers (1)

theDmi
theDmi

Reputation: 18034

The business logic requires that only one event is sent out with information about the modified aggregates because the system listening to this event is a legacy system and has a schema already defined.

That doesn't sound like the event is a real domain event to me. If it was, the reason you are trying to build your system this way would be because the domain works like that and not "because the system listening to this event is a legacy system".

So what you should do is this:

  • Control the whole batch processing from the service layer as you already have it.
  • If the logic that processes each aggregate is domain logic, extract that into a domain service and call it from the service layer.
  • That domain service may also publish domain events, if the domain requires it.
  • Publish the "finished* event from the service layer when finished. This is not a domain event.

Upvotes: 1

Related Questions